From bec4c5aa820cad2cab3a839a7605ec8b7faca798 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 11:26:32 -0500 Subject: [PATCH 001/139] feat(walletconnect): preserve Runtime-mediated phase-one connector --- .github/workflows/release-package.yml | 5 +- .gitignore | 3 + capsules/home-gui/browser/home-gui-shell.js | 1 + capsules/home-gui/browser/shell-windows.js | 1 + capsules/home/browser/home-shell-host.js | 3 +- .../browser/home-wallet-connector-host.js | 159 +- capsules/home/browser/shell-core.js | 4 +- capsules/inbox/browser/inbox.js | 22 +- .../wallet-walletconnect/browser/index.html | 2 + .../browser/wallet-walletconnect.js | 528 +- .../wallet-walletconnect/vendor/LICENSES.txt | 8941 +++++++++++++++++ .../wallet-walletconnect/vendor/adapter.json | 6 + .../vendor/package-lock.json | 4930 +++++++++ .../vendor/reown-appkit.js | 6327 ++++++++++++ components.json | 1 + docs/WALLET_PROVIDER.md | 70 +- elastos/Cargo.lock | 10 + elastos/crates/elastos-server/Cargo.toml | 4 + .../elastos-server/src/api/auth_gateway.rs | 12 +- .../src/api/browser_capsules.rs | 6 +- .../src/api/capsule_inventory/preparation.rs | 2 + .../crates/elastos-server/src/api/gateway.rs | 29 +- .../src/api/gateway_browser_internet.rs | 5 + .../src/api/gateway_browser_remote.rs | 2 + .../src/api/gateway_browser_route_tests.rs | 2 + .../src/api/gateway_capsule_catalog.rs | 2 + .../gateway_capsule_catalog/contract_audit.rs | 1 + .../src/api/gateway_home_wallet_connector.rs | 91 +- .../elastos-server/src/api/gateway_inbox.rs | 14 + .../elastos-server/src/api/gateway_models.rs | 1 + .../src/api/gateway_passkey_step_up.rs | 11 + .../elastos-server/src/api/gateway_server.rs | 1 + .../src/api/gateway_tests/inspect.rs | 1 + .../src/api/gateway_tests/mod.rs | 19 + .../src/api/gateway_tests/model.rs | 2 + .../src/api/gateway_tests/room.rs | 3 + .../src/api/gateway_tests/wallet.rs | 2 + .../api/gateway_tests/wallet/connectors.rs | 2 +- .../api/gateway_tests/wallet/walletconnect.rs | 666 ++ .../src/api/gateway_transaction_effects.rs | 1 + .../src/api/gateway_wallet_approvals.rs | 7 +- .../src/api/gateway_wallet_connectors.rs | 25 +- .../src/api/gateway_walletconnect.rs | 765 ++ .../src/collaboration_startup.rs | 2 + elastos/crates/elastos-server/src/publish.rs | 8 +- .../crates/elastos-server/src/server_infra.rs | 45 +- elastos/crates/elastos-server/src/setup.rs | 2 +- .../elastos-server/src/setup/walletconnect.rs | 119 + scripts/browser-internet-consent.test.mjs | 54 +- scripts/check-product-data.mjs | 2 +- scripts/check-product-data.test.mjs | 2 +- scripts/configure-walletconnect-connector.mjs | 2 +- scripts/home-shell-bridge-smoke.mjs | 2 +- scripts/home-shell-regression-smoke.mjs | 4 +- ...wallet-connector-launch-headless-smoke.mjs | 23 +- scripts/home-walletconnect-launch.test.mjs | 5 + scripts/lib/walletconnect-adapter-loader.mjs | 11 + scripts/lib/walletconnect-sdk-fixture.mjs | 5 + scripts/prepare-release-platform-test.py | 23 +- scripts/publish-release.sh | 12 +- scripts/setup-source-home.sh | 3 + scripts/stage-walletconnect-release.mjs | 23 + scripts/vendor-walletconnect-adapter.sh | 273 +- .../wallet-connector-transaction-smoke.mjs | 97 +- .../walletconnect-adapter-lifecycle.test.mjs | 60 + .../walletconnect-connector-config-smoke.sh | 2 +- scripts/walletconnect-home-host.test.mjs | 116 + scripts/walletconnect-runtime.test.mjs | 133 + scripts/walletconnect-sdk.test.mjs | 104 + scripts/walletconnect/adapter.mjs | 78 + scripts/walletconnect/package-lock.json | 4930 +++++++++ scripts/walletconnect/package.json | 9 + scripts/walletconnect/runtime-storage.mjs | 16 + scripts/walletconnect/runtime-websocket.mjs | 61 + 74 files changed, 28116 insertions(+), 799 deletions(-) create mode 100644 capsules/wallet-walletconnect/vendor/LICENSES.txt create mode 100644 capsules/wallet-walletconnect/vendor/adapter.json create mode 100644 capsules/wallet-walletconnect/vendor/package-lock.json create mode 100644 capsules/wallet-walletconnect/vendor/reown-appkit.js create mode 100644 elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs create mode 100644 elastos/crates/elastos-server/src/api/gateway_walletconnect.rs create mode 100644 elastos/crates/elastos-server/src/setup/walletconnect.rs create mode 100644 scripts/home-walletconnect-launch.test.mjs create mode 100644 scripts/lib/walletconnect-adapter-loader.mjs create mode 100644 scripts/lib/walletconnect-sdk-fixture.mjs create mode 100644 scripts/stage-walletconnect-release.mjs create mode 100644 scripts/walletconnect-adapter-lifecycle.test.mjs create mode 100644 scripts/walletconnect-home-host.test.mjs create mode 100644 scripts/walletconnect-runtime.test.mjs create mode 100644 scripts/walletconnect-sdk.test.mjs create mode 100644 scripts/walletconnect/adapter.mjs create mode 100644 scripts/walletconnect/package-lock.json create mode 100644 scripts/walletconnect/package.json create mode 100644 scripts/walletconnect/runtime-storage.mjs create mode 100644 scripts/walletconnect/runtime-websocket.mjs diff --git a/.github/workflows/release-package.yml b/.github/workflows/release-package.yml index 5cb8f7dd4..05beada41 100644 --- a/.github/workflows/release-package.yml +++ b/.github/workflows/release-package.yml @@ -111,6 +111,7 @@ jobs: working-directory: source env: SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} + ELASTOS_WALLETCONNECT_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} RELEASE_PLATFORM: aarch64-darwin # Cargo and its C dependencies target macOS 11.0, not the runner SDK. MACOSX_DEPLOYMENT_TARGET: "11.0" @@ -388,6 +389,7 @@ jobs: working-directory: source env: SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} + ELASTOS_WALLETCONNECT_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} RELEASE_PLATFORM: ${{ matrix.platform }} RELEASE_ARCH: ${{ matrix.arch }} CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER: musl-gcc @@ -622,7 +624,8 @@ jobs: env: GH_TOKEN: ${{ github.token }} SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} - RELEASE_PLATFORM: ${{ matrix.platform }} + ELASTOS_WALLETCONNECT_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} + RELEASE_PLATFORM: ${{ matrix.platform }} RELEASE_PREFIX: ${{ matrix.prefix }} run: | set -euo pipefail diff --git a/.gitignore b/.gitignore index 1bd57991e..b267ca1b7 100644 --- a/.gitignore +++ b/.gitignore @@ -153,3 +153,6 @@ scripts/dev/dkms-docker/shared # Local rehearsal and review output; never part of the repository. /output/ + +# Operator WalletConnect config is staged into release archives, outside source. +/capsules/wallet-walletconnect/vendor/connector.json diff --git a/capsules/home-gui/browser/home-gui-shell.js b/capsules/home-gui/browser/home-gui-shell.js index ddf915405..5decb1f82 100644 --- a/capsules/home-gui/browser/home-gui-shell.js +++ b/capsules/home-gui/browser/home-gui-shell.js @@ -50,6 +50,7 @@ const BROWSER_AUTHORITY_RENEWAL_RESULT_TYPE = const AUTHORIZED_ATTACHMENT_TARGET_TITLES = Object.freeze({ "wallet-metamask": "MetaMask", "wallet-unisat": "UniSat", + "wallet-walletconnect": "WalletConnect", }); let currentSummary = null; let sessionRestore = null; diff --git a/capsules/home-gui/browser/shell-windows.js b/capsules/home-gui/browser/shell-windows.js index f1a616298..311fe6f5f 100644 --- a/capsules/home-gui/browser/shell-windows.js +++ b/capsules/home-gui/browser/shell-windows.js @@ -386,6 +386,7 @@ export function supportsMenuNewWindow(targetId) { const WALLET_CONNECTOR_TARGETS = new Set([ "wallet-metamask", "wallet-unisat", + "wallet-walletconnect", ]); const NON_RESTORABLE_SESSION_TARGETS = new Set(WALLET_CONNECTOR_TARGETS); const WALLET_CONNECTOR_WINDOW_WIDTH = 480; diff --git a/capsules/home/browser/home-shell-host.js b/capsules/home/browser/home-shell-host.js index a81b82f0a..615344d66 100644 --- a/capsules/home/browser/home-shell-host.js +++ b/capsules/home/browser/home-shell-host.js @@ -83,6 +83,7 @@ const HOME_GUI_AUTHORIZED_ATTACHMENT_SCHEMA = const WALLET_CONNECTOR_TARGET_TITLES = Object.freeze({ "wallet-metamask": "MetaMask", "wallet-unisat": "UniSat", + "wallet-walletconnect": "WalletConnect", }); const WALLET_CONNECTOR_TARGETS = new Set( Object.keys(WALLET_CONNECTOR_TARGET_TITLES), @@ -101,7 +102,7 @@ const SHELL_MESSAGE_OPEN_TARGET_SOURCES = Object.freeze({ marketplace: "runtime-target", people: new Set(["chat-room", "inbox", "system"]), system: "visible-target", - "wallet": new Set(["wallet-metamask", "wallet-unisat"]), + "wallet": new Set(["wallet-metamask", "wallet-unisat", "wallet-walletconnect"]), }); const SHELL_MESSAGE_DELIVER_TARGET_SOURCES = Object.freeze({ "chat-room": new Set(["documents"]), diff --git a/capsules/home/browser/home-wallet-connector-host.js b/capsules/home/browser/home-wallet-connector-host.js index 1950ab883..e6296c5c4 100644 --- a/capsules/home/browser/home-wallet-connector-host.js +++ b/capsules/home/browser/home-wallet-connector-host.js @@ -9,7 +9,14 @@ const RUNTIME_REQUEST_SCHEMA = "elastos.home.wallet-connector.effect.request/v1" const RUNTIME_RESULT_SCHEMA = "elastos.home.wallet-connector.effect.result/v1"; const METAMASK_CONNECTOR_ID = "wallet-metamask"; const UNISAT_CONNECTOR_ID = "wallet-unisat"; -const CONNECTOR_IDS = new Set([METAMASK_CONNECTOR_ID, UNISAT_CONNECTOR_ID]); +const WALLETCONNECT_ID = "wallet-walletconnect"; +const CONNECTOR_IDS = new Set([METAMASK_CONNECTOR_ID, UNISAT_CONNECTOR_ID, WALLETCONNECT_ID]); +let walletConnectProvider = null; +let walletConnectToken = ""; +let walletConnectGeneration = 0; +let walletConnectPrincipal = ""; +let walletConnectAdapter = null; +const observedWalletConnectProviders = new WeakSet(); const METAMASK_RDNS = "io.metamask"; const BRAVE_RDNS = "com.brave.wallet"; const MAX_EIP6963_PROVIDERS = 32; @@ -159,7 +166,62 @@ function selectMetaMaskCompatibleProvider() { throw new Error("MetaMask or Brave Wallet was not found in this browser profile."); } +async function walletConnect(connectorToken) { + const api = (path, init = {}) => fetchJson(`/api/apps/wallet-walletconnect/${path}`, { + ...init, headers: { "x-elastos-walletconnect-connector": connectorToken }, + }); + const config = await api("host-config", { method: "POST" }); + if (config.internet.status !== "granted") throw new Error("Allow WalletConnect internet access in Inbox, then connect again."); + if (walletConnectToken && walletConnectToken !== connectorToken) { + await walletConnectProvider?.signer.client.core.relayer.transportClose(); + } + // Each principal has its own bundled SDK module state and Core storage prefix. + const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(config.principal_id)); + const instance = [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, "0")).join(""); + const adapter = await import(`${config.sdk_asset_path}?instance=${instance}`); + walletConnectProvider = await adapter.connectWalletConnectEvm({ + contextKey: config.principal_id, projectId: config.projectId, chains: [1, 20, 8453, 11155111], api, + runtimeUrl: new URL("/api/apps/wallet-walletconnect", location.origin).href, + relayUrl: `${location.origin.replace(/^http/, "ws")}/api/apps/wallet-walletconnect/relay`, + metadata: { name: "ElastOS Home", description: "Runtime wallet approval", url: location.origin, icons: [] }, + }); + walletConnectToken = connectorToken; + walletConnectPrincipal = config.principal_id; + walletConnectAdapter = adapter; + if (!observedWalletConnectProviders.has(walletConnectProvider)) { + const current = walletConnectProvider; + observedWalletConnectProviders.add(current); + for (const event of ["accountsChanged", "chainChanged", "disconnect"]) { + current.on(event, () => { if (walletConnectProvider === current) walletConnectGeneration++; }); + } + } + return walletConnectProvider; +} + async function performConnectorEffect(connectorId, connectorToken, action) { + if (connectorId === WALLETCONNECT_ID && action.kind === "status") { + const current = await fetchJson("/api/apps/wallet-walletconnect/host-config", { + headers: { "x-elastos-walletconnect-connector": connectorToken }, + }); + const connected = current.internet.status === "granted" && current.principal_id === walletConnectPrincipal + && walletConnectProvider?.session?.expiry > Date.now() / 1000 + && walletConnectProvider?.connected && walletConnectProvider?.signer?.client.core.relayer.connected; + return Object.freeze({ status: connected ? "connected" : "disconnected", revision: walletConnectGeneration }); + } + if (connectorId === WALLETCONNECT_ID && action.kind === "disconnect") { + walletConnectGeneration++; + const api = (path, init = {}) => fetchJson(`/api/apps/wallet-walletconnect/${path}`, { + ...init, headers: { "x-elastos-walletconnect-connector": connectorToken }, + }); + const current = await api("host-config"); + if (walletConnectPrincipal === current.principal_id) await walletConnectAdapter?.disconnectWalletConnectEvm({ api }); + else await walletConnectProvider?.signer.client.core.relayer.transportClose(); + walletConnectProvider = null; walletConnectToken = ""; walletConnectPrincipal = ""; + return Object.freeze({ status: "disconnected" }); + } + if (connectorId === WALLETCONNECT_ID && action.kind === "link") { + return linkEvmWallet(connectorToken, await walletConnect(connectorToken), WALLETCONNECT_ID); + } if (connectorId === METAMASK_CONNECTOR_ID && action.kind === "link") { return linkEvmWallet(connectorToken); } @@ -172,33 +234,41 @@ async function performConnectorEffect(connectorId, connectorToken, action) { throw new Error("Unsupported wallet request."); } -async function linkEvmWallet(connectorToken) { - const provider = selectMetaMaskCompatibleProvider(); +function walletConnectSignData(message, connectorId) { + if (connectorId !== WALLETCONNECT_ID) return message; + if (/^0[xX](?:[0-9a-fA-F]{2})*$/.test(message)) return "0x" + message.slice(2); + return "0x" + [...new TextEncoder().encode(message)].map(byte => byte.toString(16).padStart(2, "0")).join(""); +} + +async function linkEvmWallet(connectorToken, provider = selectMetaMaskCompatibleProvider(), connectorId = METAMASK_CONNECTOR_ID) { + const generation = walletConnectGeneration; const accounts = await provider.request({ method: "eth_requestAccounts" }); const address = requireEvmAddress(firstProviderAccount(accounts)); const chainId = requireEvmChainId(await provider.request({ method: "eth_chainId" })); const challengeResult = await runtimePost( "/api/apps/home/wallet-connector/evm/link/challenge", - connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { + connectorBody(connectorId, connectorToken, { address, chain_id: chainId, }), ); - const challenge = requireEvmChallenge(challengeResult); + const challenge = requireEvmChallenge(challengeResult, connectorId); const signer = requireEvmAddress(await currentEvmAccount(provider)); ensureSameAddress(signer, address, "Wallet account changed before signing."); + if (connectorId === WALLETCONNECT_ID && (generation !== walletConnectGeneration || !Number.isSafeInteger(challenge.expires_at) || challenge.expires_at <= Date.now() / 1000)) throw new Error("Wallet changed. Connect again."); + if (connectorId === WALLETCONNECT_ID && requireEvmChainId(await provider.request({ method: "eth_chainId" })) !== chainId) throw new Error("Wallet network changed. Connect again."); const signature = requireProviderResult(await provider.request({ method: "personal_sign", - params: [challenge.message, signer], + params: [walletConnectSignData(challenge.message, connectorId), signer], }), 16 * 1024, "Wallet returned an invalid signature."); const verified = await runtimePost( "/api/apps/home/wallet-connector/evm/link/verify", - connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { + connectorBody(connectorId, connectorToken, { message: challenge.message, signature, }), ); - requireRuntimeCompletion(verified, "evm_link_complete", METAMASK_CONNECTOR_ID, "linked"); + requireRuntimeCompletion(verified, "evm_link_complete", connectorId, "linked"); return Object.freeze({ status: "linked" }); } @@ -230,26 +300,46 @@ async function linkBitcoinWallet(connectorToken) { } async function completeApproval(connectorId, connectorToken, approvalRequestId) { - const provider = connectorId === METAMASK_CONNECTOR_ID - ? selectMetaMaskCompatibleProvider() - : requireUniSatProvider(); + const provider = connectorId === WALLETCONNECT_ID ? await walletConnect(connectorToken) + : connectorId === METAMASK_CONNECTOR_ID ? selectMetaMaskCompatibleProvider() : requireUniSatProvider(); const encodedRequestId = encodeURIComponent(approvalRequestId); + if (connectorId === WALLETCONNECT_ID) { + const review = await runtimePost(`/api/apps/home/wallet-connector/approvals/${encodedRequestId}/review`, connectorBody(connectorId, connectorToken)); + ensureSameAddress(await currentEvmAccount(provider), review.address, "Select the requested account in your phone wallet, then review again."); + const chain = `eip155:${requireEvmChainId(await provider.request({ method: "eth_chainId" }))}`; + if (chain !== review.chain_namespace) throw new Error("Select the request network in your phone wallet, then review again."); + if (!Number.isSafeInteger(review.expires_at) || review.expires_at - Math.ceil(Date.now() / 1000) < 300) { + throw new Error("Wallet request expires soon. Request a fresh review."); + } + } const response = await runtimePost( `/api/apps/home/wallet-connector/approvals/${encodedRequestId}/handoff`, connectorBody(connectorId, connectorToken), ); - const { handoff, evmChains } = requireHandoffResponse( + const { handoff, evmChains, binding } = requireHandoffResponse( response, connectorId, approvalRequestId, ); - if (connectorId === METAMASK_CONNECTOR_ID) { - return completeEvmApproval(provider, connectorToken, handoff, evmChains); + if (connectorId !== UNISAT_CONNECTOR_ID) { + return completeEvmApproval(provider, connectorToken, handoff, evmChains, connectorId, binding); } return completeBitcoinApproval(provider, connectorToken, handoff); } -async function completeEvmApproval(provider, connectorToken, handoff, evmChains) { +async function completeEvmApproval(provider, connectorToken, handoff, evmChains, connectorId = METAMASK_CONNECTOR_ID, binding) { + const generation = walletConnectGeneration; + const checkBinding = async () => { + if (connectorId !== WALLETCONNECT_ID) return; + const chain = `eip155:${requireEvmChainId(await provider.request({ method: "eth_chainId" }))}`; + if (chain !== binding.chain_namespace || generation !== walletConnectGeneration + || !Number.isSafeInteger(binding.expires_at) || binding.expires_at <= Date.now() / 1000) { + throw new Error("Wallet request changed or expired. Request a new review."); + } + const ttl = binding.expires_at - Math.ceil(Date.now() / 1000); + if (ttl < 300) throw new Error("Wallet request expires soon. Request a fresh review."); + return ttl; + }; const signer = requireEvmAddress(await currentEvmAccount(provider)); ensureSameAddress(signer, handoff.signer, "Switch to the linked account before approving."); const path = `/api/apps/home/wallet-connector/approvals/${encodeURIComponent(handoff.request_id)}/complete`; @@ -261,16 +351,17 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains) handoff.signer, "Switch to the linked account before approving.", ); + const expiry = await checkBinding(); const transactionHash = requireProviderResult(await provider.request({ method: "eth_sendTransaction", params: [handoff.transaction], - }), 512, "Wallet returned an invalid transaction hash."); - const completed = await runtimePost(path, connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { + }, expiry), 512, "Wallet returned an invalid transaction hash."); + const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { payload_hash: handoff.payload_hash, signer: currentSigner, transaction_hash: transactionHash, })); - requireApprovalCompletion(completed, METAMASK_CONNECTOR_ID, handoff.request_id); + requireApprovalCompletion(completed, connectorId, handoff.request_id); return Object.freeze({ status: "completed", effect: "transaction" }); } const method = handoff.intent === "browser_typed_data_sign" @@ -278,16 +369,17 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains) : "personal_sign"; const params = method === "eth_signTypedData_v4" ? [signer, handoff.message] - : [handoff.message, signer]; - const signature = requireProviderResult(await provider.request({ method, params }), 16 * 1024, + : [walletConnectSignData(handoff.message, connectorId), signer]; + const expiry = await checkBinding(); + const signature = requireProviderResult(await provider.request({ method, params }, expiry), 16 * 1024, "Wallet returned an invalid signature."); - const completed = await runtimePost(path, connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { + const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { payload_hash: handoff.payload_hash, signature, signature_type: method === "eth_signTypedData_v4" ? "eip712" : "personal_sign", signer, })); - requireApprovalCompletion(completed, METAMASK_CONNECTOR_ID, handoff.request_id); + requireApprovalCompletion(completed, connectorId, handoff.request_id); return Object.freeze({ status: "completed", effect: "signature" }); } @@ -370,12 +462,8 @@ function requireEvmChain(chains, chainId) { function requireHandoffResponse(response, connectorId, requestId) { if ( !hasExactKeys(response, [ - "schema", - "action", - "connector_id", - "request_id", - "handoff", - "evm_chains", + "schema", "action", "connector_id", "request_id", "handoff", "evm_chains", + ...(connectorId === WALLETCONNECT_ID ? ["binding"] : []), ]) || response.schema !== RUNTIME_RESULT_SCHEMA || response.action !== "approval_handoff" @@ -434,7 +522,14 @@ function requireHandoffResponse(response, connectorId, requestId) { ) { throw new Error("Runtime returned an invalid EVM signature handoff."); } - return { handoff, evmChains: response.evm_chains }; + if (connectorId === WALLETCONNECT_ID && ( + !hasExactKeys(response.binding, ["principal_id", "requested_by_actor", "account_id", "chain_namespace", "payload_hash", "expires_at"]) + || !boundedText(response.binding.principal_id, 256) || !boundedText(response.binding.requested_by_actor, 256) + || !boundedText(response.binding.account_id, 256) || !/^eip155:[1-9][0-9]*$/.test(response.binding.chain_namespace) + || response.binding.payload_hash !== handoff.payload_hash + || !Number.isSafeInteger(response.binding.expires_at) || response.binding.expires_at <= Date.now() / 1000 + )) throw new Error("Runtime returned an invalid WalletConnect request binding."); + return { handoff, evmChains: response.evm_chains, binding: response.binding }; } function validTransaction(transaction, signer) { @@ -452,12 +547,12 @@ function validTransaction(transaction, signer) { && /^0x[0-9a-fA-F]+$/.test(transaction.chainId); } -function requireEvmChallenge(response) { +function requireEvmChallenge(response, connectorId = METAMASK_CONNECTOR_ID) { if ( !hasExactKeys(response, ["schema", "action", "connector_id", "challenge"]) || response.schema !== RUNTIME_RESULT_SCHEMA || response.action !== "evm_link_challenge" - || response.connector_id !== METAMASK_CONNECTOR_ID + || response.connector_id !== connectorId ) { throw new Error("Runtime returned an invalid EVM challenge envelope."); } @@ -682,7 +777,7 @@ function validAction(action) { if (!action || typeof action !== "object" || Array.isArray(action)) { return false; } - if (action.kind === "link") { + if (action.kind === "link" || action.kind === "disconnect" || action.kind === "status") { return hasExactKeys(action, ["kind"]); } return action.kind === "approve" diff --git a/capsules/home/browser/shell-core.js b/capsules/home/browser/shell-core.js index af4dae60e..1191d2bb0 100644 --- a/capsules/home/browser/shell-core.js +++ b/capsules/home/browser/shell-core.js @@ -82,7 +82,9 @@ export function createHomeBackgroundImageReader() { } export async function fetchJson(url, init) { - const requiresHomeAuthority = url === "/api/apps/home/launch" + const requiresHomeAuthority = url.startsWith("/api/apps/home/wallet-connector/") + || url.startsWith("/api/apps/wallet-walletconnect/") + || url === "/api/apps/home/launch" || url === "/api/apps/home/active-shell" || url === "/api/apps/home/shared-content/get" || url === "/api/apps/home/shared-content/check"; diff --git a/capsules/inbox/browser/inbox.js b/capsules/inbox/browser/inbox.js index 3e656ec03..f1a7657b3 100644 --- a/capsules/inbox/browser/inbox.js +++ b/capsules/inbox/browser/inbox.js @@ -387,7 +387,7 @@ } function pendingRequestEntries() { - return state.entries.filter((entry) => entry && entry.kind !== "service_access_grant" && entry.kind !== "hosted_route_history" && entry.kind !== "browser_internet_decision"); + return state.entries.filter((entry) => entry && entry.kind !== "service_access_grant" && entry.kind !== "hosted_route_history" && entry.kind !== "browser_internet_decision" && entry.kind !== "walletconnect_internet_decision"); } function renderInbox() { @@ -527,6 +527,25 @@ function fillEntryActions(actions, entry) { const actionId = entry.action_ref && entry.action_ref.action_id; + if (entry.kind === "walletconnect_internet_request" || entry.kind === "walletconnect_internet_decision") { + const path = "/api/apps/wallet-walletconnect/internet"; + const act = async (id, operation) => { + setButtonsDisabled(true); + try { + const current = await api(path); + const stepUpToken = current.status === "revoked" ? undefined : await requestPasskeyStepUp(operation, current.request); + await inboxAction(id, { step_up_token: stepUpToken }); + await loadInbox(); notifyHome(); + } finally { setButtonsDisabled(false); } + }; + if (actionId?.startsWith("walletconnect-internet-allow:")) { + actions.appendChild(createActionButton("Don't Allow", actionId.replace("-allow:", "-deny:"))); + actions.appendChild(createButton("Allow", () => act(actionId, "walletconnect.internet.grant"), "primary")); + } else if (actionId?.startsWith("walletconnect-internet-turn-off:")) { + actions.appendChild(createButton("Turn Off", () => act(actionId, "walletconnect.internet.revoke"), "danger")); + } + return; + } if (entry.kind === "browser_internet_decision") { if (actionId?.startsWith("browser-internet-turn-off:")) { actions.appendChild(createButton("Turn Off", async () => { @@ -888,6 +907,7 @@ .filter((entry) => entry && entry.id && !entry.read && entry.kind !== "wallet_approval_request" && entry.kind !== "browser_internet_request" + && entry.kind !== "walletconnect_internet_request" && entry.kind !== "contact_request" && entry.kind !== "service_access_request") .map((entry) => entry.id); if (unreadIds.length === 0) { diff --git a/capsules/wallet-walletconnect/browser/index.html b/capsules/wallet-walletconnect/browser/index.html index 30f966c61..c60499929 100644 --- a/capsules/wallet-walletconnect/browser/index.html +++ b/capsules/wallet-walletconnect/browser/index.html @@ -16,6 +16,8 @@
+ + Disconnected
diff --git a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js index ac86081a1..bc7013b45 100644 --- a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js +++ b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js @@ -3,6 +3,11 @@ import { } from "/apps/home/home-clipboard-client.js?v=home-20260726a"; const CONNECTOR_ID = "wallet-walletconnect"; +const HOST_EFFECT_TYPE = "home:wallet-connector-effect"; +const HOST_EFFECT_SCHEMA = "elastos.home.wallet-connector-effect/v1"; +const HOST_RESULT_TYPE = "home:wallet-connector-effect-result"; +const HOST_RESULT_SCHEMA = "elastos.home.wallet-connector-effect-result/v1"; +const HOST_EFFECT_TIMEOUT_MS = 180_000; const connectButton = document.querySelector("#wallet-connect"); const statusNode = document.querySelector("#wallet-status"); const stateNode = document.querySelector("#wallet-state"); @@ -10,8 +15,24 @@ const accountsNode = document.querySelector("#wallet-accounts"); const requestsNode = document.querySelector("#wallet-requests"); const frameHomeToken = readLaunchToken(); const homeOrigin = readQueryParam("home_origin"); - -let walletProvider = null; +let hostEffectInFlight = false; +let hostRequestSequence = 0; +let connectionTimer; +let connectionRevision; +function watchConnection() { + if (connectionTimer || typeof window.setInterval !== "function") return; + connectionTimer = window.setInterval(async () => { + if (hostEffectInFlight) return; + try { + const current = await requestHomeWalletEffect({ kind: "status" }); + document.querySelector("#wallet-connection").textContent = current.status === "connected" ? "Connected" : "Disconnected"; + if (current.status === "connected" && connectionRevision !== undefined && connectionRevision !== current.revision) { + showStatus("Wallet changed. Check the account and network on your phone.", "muted"); + } + connectionRevision = current.revision; + } catch { document.querySelector("#wallet-connection").textContent = "Disconnected"; } + }, 5000); +} const homeClipboard = createHomeClipboardClient({ targetId: CONNECTOR_ID, @@ -23,119 +44,41 @@ homeClipboard.start(); boot(); function boot() { - if (connectButton) { - connectButton.addEventListener("click", onConnect); - } - if (accountsNode) { - accountsNode.addEventListener("click", onAccountClick); - } - if (requestsNode) { - requestsNode.addEventListener("click", onRequestClick); - } + document.querySelector("#wallet-disconnect")?.addEventListener("click", async () => { + try { await requestHomeWalletEffect({ kind: "disconnect" }); document.querySelector("#wallet-connection").textContent = "Disconnected"; showStatus("Disconnected. Linked accounts stay in Wallet.", "muted"); } + catch (error) { showStatus(errorMessage(error), "error"); } + }); + connectButton?.addEventListener("click", onConnect); + accountsNode?.addEventListener("click", onAccountClick); + requestsNode?.addEventListener("click", onRequestClick); setState("0 linked"); - refreshWalletState().catch((error) => showStatus(String(error.message || error), "error")); + refreshWalletState().catch((error) => { + showStatus(errorMessage(error), "error"); + }); } async function onConnect() { setButtonBusy(connectButton, true); - showStatus("Opening wallet.", "muted"); + showStatus("Approve in your phone wallet.", "muted"); try { - const config = await connectorConfig(); - const provider = await loadWalletConnectProvider(config); - walletProvider = provider; - const { address, chainId } = await connectProvider(provider); - const challenge = await fetchJson("/api/auth/evm/challenge", { - method: "POST", - headers: shellHeaders({ "content-type": "application/json" }), - body: JSON.stringify({ address, chain_id: chainId }), - }); - const signer = await currentProviderAddress(provider); - ensureSameAddress(signer, address, "Wallet account changed before signing."); - const signature = await signProviderMessage(provider, challenge.message, signer); - await fetchJson("/api/auth/evm/verify", { - method: "POST", - headers: shellHeaders({ "content-type": "application/json" }), - body: JSON.stringify({ message: challenge.message, signature }), - }); + await requestHomeWalletEffect({ kind: "link" }); + document.querySelector("#wallet-connection").textContent = "Connected"; + watchConnection(); showStatus("Approval method added.", "success"); notifyHomeSummaryChanged(); await refreshWalletState(); } catch (error) { - showStatus(String(error.message || error), "error"); + showStatus(errorMessage(error), "error"); } finally { setButtonBusy(connectButton, false); } } -async function connectorConfig() { - const config = await fetchJson(`/api/apps/${CONNECTOR_ID}/wallet/config`, { - headers: shellHeaders(), - }); - const walletconnect = config && config.walletconnect; - if (!walletconnect || !readText(walletconnect.sdk_asset_path) || !readText(walletconnect.project_id)) { - throw new Error("WalletConnect is not configured."); - } - walletconnect.evm_chains = Array.isArray(config && config.evm_chains) ? config.evm_chains : []; - return walletconnect; -} - -async function loadWalletConnectProvider(config) { - const module = await import(readText(config.sdk_asset_path)); - if (typeof module.connectWalletConnectEvm !== "function") { - throw new Error("Pinned WalletConnect SDK adapter is missing connectWalletConnectEvm."); - } - const provider = await module.connectWalletConnectEvm({ - projectId: readText(config.project_id), - chains: [1, 20, 8453], - metadata: { - name: "ElastOS Home", - description: "Runtime-mediated WalletConnect proof", - url: window.location.origin, - icons: [`${window.location.origin}/apps/home/elastos-home-icon.svg`], - }, - }); - if (!provider || typeof provider.request !== "function") { - throw new Error("WalletConnect adapter returned no EIP-1193 provider."); - } - return provider; -} - -async function connectProvider(provider) { - const accounts = await provider.request({ method: "eth_requestAccounts" }); - const address = Array.isArray(accounts) && accounts[0] ? String(accounts[0]) : ""; - if (!address) { - throw new Error("Wallet returned no account."); - } - const chainHex = await provider.request({ method: "eth_chainId" }); - const chainId = Number.parseInt(String(chainHex), 16); - if (!Number.isFinite(chainId) || chainId <= 0) { - throw new Error("Wallet returned an invalid chain."); - } - return { address, chainId }; -} - -async function currentProviderAddress(provider) { - const accounts = await provider.request({ method: "eth_accounts" }); - const address = Array.isArray(accounts) && accounts[0] ? String(accounts[0]) : ""; - if (!address) { - throw new Error("Wallet has no selected account."); - } - return address; -} - -async function signProviderMessage(provider, message, signer) { - const signature = await provider.request({ - method: "personal_sign", - params: [message, signer], - }); - return readText(signature); -} - async function refreshWalletState() { if (!frameHomeToken) { renderAccounts([]); renderRequests([]); - showStatus("Open from Wallet to add an approval method.", "error"); + showStatus("Open from Wallet to review approval requests.", "error"); return; } const [accountSummary, requestSummary] = await Promise.all([ @@ -146,15 +89,13 @@ async function refreshWalletState() { headers: shellHeaders(), }), ]); - const accounts = Array.isArray(accountSummary && accountSummary.accounts) - ? accountSummary.accounts - : []; - const requests = Array.isArray(requestSummary && requestSummary.approval_requests) + const accounts = Array.isArray(accountSummary?.accounts) ? accountSummary.accounts : []; + const requests = Array.isArray(requestSummary?.approval_requests) ? requestSummary.approval_requests : []; renderAccounts(accounts); renderRequests(requests); - setState(`${accounts.length} linked`); + setState(accounts.length > 0 ? `${accounts.length} linked` : "0 linked"); } function renderAccounts(accounts) { @@ -163,10 +104,7 @@ function renderAccounts(accounts) { } accountsNode.replaceChildren(); if (accounts.length === 0) { - const empty = document.createElement("div"); - empty.className = "wallet-empty"; - empty.textContent = "No connected accounts."; - accountsNode.append(empty); + accountsNode.append(emptyNode("No connected accounts.")); return; } for (const account of accounts) { @@ -177,27 +115,21 @@ function renderAccounts(accounts) { function accountCard(account) { const card = document.createElement("div"); card.className = "wallet-account"; - const main = document.createElement("div"); main.className = "wallet-account-main"; - const title = document.createElement("strong"); - title.textContent = `Connected wallet · ${chainLabel(account.chain_namespace)}`; - + title.textContent = `Connected wallet · ${chainLabel(account?.chain_namespace)}`; const address = document.createElement("code"); - const addressText = readText(account.address); + const addressText = readText(account?.address); address.className = "wallet-address"; address.textContent = addressText || "Unknown address"; - main.append(title, address); - const copy = document.createElement("button"); copy.className = "wallet-button wallet-button-secondary wallet-copy-button"; copy.type = "button"; copy.textContent = "Copy"; copy.dataset.walletCopyAddress = addressText; copy.disabled = !addressText; - card.append(main, copy); return card; } @@ -207,15 +139,14 @@ function renderRequests(requests) { return; } requestsNode.replaceChildren(); - const externalRequests = requests.filter(isWalletConnectSignableRequest); - if (externalRequests.length === 0) { - const empty = document.createElement("div"); - empty.className = "wallet-empty"; - empty.textContent = "No approval requests."; - requestsNode.append(empty); + const connectorRequests = requests.filter((request) => ( + !isManagedWalletRequest(request) && isMetaMaskSignableRequest(request) + )); + if (connectorRequests.length === 0) { + requestsNode.append(emptyNode("No approval requests.")); return; } - for (const request of externalRequests) { + for (const request of connectorRequests) { requestsNode.append(requestCard(request)); } } @@ -223,40 +154,32 @@ function renderRequests(requests) { function requestCard(request) { const card = document.createElement("div"); card.className = "wallet-request"; - const main = document.createElement("div"); main.className = "wallet-request-main"; - const title = document.createElement("strong"); - title.textContent = walletIntentLabel(request.intent); - + title.textContent = walletIntentLabel(request?.intent); const meta = document.createElement("span"); - const capsule = readText(request.capsule_id) || "capsule"; - const address = shortAddress(request.address); - meta.textContent = address ? `${capsule} - ${address}` : capsule; - + const capsule = readText(request?.capsule_id) || "capsule"; + const address = shortAddress(request?.address); + meta.textContent = `${capsule} · ${chainLabel(request.chain_namespace)}${address ? ` · ${address}` : ""}`; const reason = document.createElement("small"); - reason.textContent = readText(request.reason) || readText(request.resource) || "Approval requested."; - + reason.textContent = readText(request?.reason) + || readText(request?.resource) + || "Approval requested."; main.append(title, meta, reason); - const sign = document.createElement("button"); sign.className = "wallet-button"; sign.type = "button"; sign.textContent = "Review"; - sign.dataset.walletRequestSign = readText(request.request_id); - + sign.dataset.walletRequestSign = readText(request?.request_id); card.append(main, sign); return card; } async function onAccountClick(event) { - const button = event.target && event.target.closest("[data-wallet-copy-address]"); - if (!button) { - return; - } - const address = readText(button.dataset.walletCopyAddress); - if (!address) { + const button = event.target?.closest?.("[data-wallet-copy-address]"); + const address = readText(button?.dataset?.walletCopyAddress); + if (!button || !address) { return; } setButtonBusy(button, true); @@ -264,173 +187,148 @@ async function onAccountClick(event) { await copyText(address); showStatus("Address copied.", "success"); } catch (error) { - showStatus(String(error.message || error), "error"); + showStatus(errorMessage(error), "error"); } finally { setButtonBusy(button, false); } } async function onRequestClick(event) { - const button = event.target && event.target.closest("[data-wallet-request-sign]"); - if (!button) { - return; - } - const requestId = readText(button.dataset.walletRequestSign); - if (!requestId) { + const button = event.target?.closest?.("[data-wallet-request-sign]"); + const approvalRequestId = readText(button?.dataset?.walletRequestSign); + if (!button || !approvalRequestId) { return; } setButtonBusy(button, true); showStatus("Preparing request.", "muted"); try { - const provider = walletProvider || await loadWalletConnectProvider(await connectorConfig()); - walletProvider = provider; - const handoffSummary = await fetchJson(`/api/apps/${CONNECTOR_ID}/wallet/approvals/${encodeURIComponent(requestId)}/approve`, { - method: "POST", - headers: shellHeaders({ "content-type": "application/json" }), - body: JSON.stringify({ reason: "Approved in wallet" }), - }); - const handoff = handoffSummary && handoffSummary.handoff; - const signer = readText(handoff && handoff.signer); - const payloadHash = readText(handoff && handoff.payload_hash); - if (!signer || !payloadHash) { - throw new Error("Wallet handoff is incomplete."); - } - if (readText(handoff.intent) === "transaction_intent") { - const transaction = handoff.transaction && typeof handoff.transaction === "object" - ? handoff.transaction - : null; - if (!transaction || !readText(transaction.chainId)) { - throw new Error("Wallet transaction handoff is incomplete."); - } - await ensureProviderChain(provider, readText(transaction.chainId)); - const activeSigner = await currentProviderAddress(provider); - ensureSameAddress(activeSigner, signer, "Switch to the linked account before approving."); - showStatus("Approve transaction in your wallet.", "muted"); - const transactionHash = await provider.request({ - method: "eth_sendTransaction", - params: [transaction], - }); - await fetchJson(`/api/apps/${CONNECTOR_ID}/wallet/approvals/${encodeURIComponent(requestId)}/complete`, { - method: "POST", - headers: shellHeaders({ "content-type": "application/json" }), - body: JSON.stringify({ payload_hash: payloadHash, transaction_hash: transactionHash, signer: activeSigner }), - }); - showStatus("Transaction sent.", "success"); - } else { - const message = readText(handoff && handoff.message); - if (!message) { - throw new Error("Wallet signature handoff is incomplete."); - } - const activeSigner = await currentProviderAddress(provider); - ensureSameAddress(activeSigner, signer, "Switch to the linked account before signing."); - showStatus("Approve in your wallet.", "muted"); - const signature = await signProviderMessage(provider, message, activeSigner); - await fetchJson(`/api/apps/${CONNECTOR_ID}/wallet/approvals/${encodeURIComponent(requestId)}/complete`, { - method: "POST", - headers: shellHeaders({ "content-type": "application/json" }), - body: JSON.stringify({ payload_hash: payloadHash, signature, signer: activeSigner }), - }); - showStatus("Request signed.", "success"); - } + const result = await requestHomeWalletEffect({ kind: "approve", approvalRequestId }); + watchConnection(); + showStatus( + result.effect === "transaction" ? "Transaction sent." : "Request signed.", + "success", + ); notifyHomeSummaryChanged(); await refreshWalletState(); } catch (error) { - showStatus(String(error.message || error), "error"); + showStatus(errorMessage(error), "error"); } finally { setButtonBusy(button, false); } } -async function ensureProviderChain(provider, chainId) { - const targetChainId = normalizeChainId(chainId); - const active = normalizeChainId(await provider.request({ method: "eth_chainId" })); - if (active === targetChainId) { - return; - } - try { - await provider.request({ - method: "wallet_switchEthereumChain", - params: [{ chainId: targetChainId }], - }); - } catch (error) { - if (!isUnknownChainError(error)) { - throw error; - } - const chain = await ethereumChainConfig(targetChainId); - if (!chain) { - throw error; - } - await provider.request({ - method: "wallet_addEthereumChain", - params: [chain], - }); - } - const current = normalizeChainId(await provider.request({ method: "eth_chainId" })); - if (current !== targetChainId) { - throw new Error(`Switch to ${chainLabel(`eip155:${Number.parseInt(targetChainId, 16)}`)} before approving.`); - } -} - -function normalizeChainId(value) { - const text = readText(value).toLowerCase(); - if (/^0x[0-9a-f]+$/.test(text)) { - return text; - } - const number = Number.parseInt(text, 10); - if (!Number.isFinite(number) || number <= 0) { - throw new Error("Wallet returned an invalid chain."); - } - return `0x${number.toString(16)}`; -} - -function isUnknownChainError(error) { - return Number(error && error.code) === 4902 - || String(error && error.message || "").toLowerCase().includes("unrecognized chain") - || String(error && error.message || "").toLowerCase().includes("unknown chain"); -} - -async function ethereumChainConfig(chainId) { - const config = await connectorConfig(); - const chains = Array.isArray(config && config.evm_chains) ? config.evm_chains : []; - return chains.find((chain) => normalizeChainId(chain && chain.chainId) === normalizeChainId(chainId)) || null; +function requestHomeWalletEffect(action) { + if (!frameHomeToken || !homeOrigin || window.top === window) { + return Promise.reject(new Error("Open this approval method from Wallet.")); + } + if (hostEffectInFlight) { + return Promise.reject(new Error("A wallet request is already active.")); + } + const requestId = nextHostRequestId(); + hostEffectInFlight = true; + return new Promise((resolve, reject) => { + const timeout = window.setTimeout(() => { + finish(); + reject(new Error("Wallet request timed out.")); + }, action.kind === "status" ? 10000 : HOST_EFFECT_TIMEOUT_MS); + const finish = () => { + window.clearTimeout(timeout); + window.removeEventListener("message", onMessage); + hostEffectInFlight = false; + }; + const onMessage = (event) => { + const data = event.data; + if ( + event.source !== window.top + || event.origin !== homeOrigin + || data?.type !== HOST_RESULT_TYPE + || data.schema !== HOST_RESULT_SCHEMA + || data.requestId !== requestId + || data.connectorId !== CONNECTOR_ID + ) { + return; + } + const hasResult = hasExactKeys(data, [ + "type", + "schema", + "requestId", + "connectorId", + "result", + ]); + const hasError = hasExactKeys(data, [ + "type", + "schema", + "requestId", + "connectorId", + "error", + ]); + if (!hasResult && !hasError) { + return; + } + finish(); + if (hasError) { + reject(new Error(readText(data.error) || "Wallet request failed.")); + return; + } + if (action.kind === "status") { + if (!hasExactKeys(data.result, ["status", "revision"]) || !["connected", "disconnected"].includes(data.result.status) + || !Number.isSafeInteger(data.result.revision)) { reject(new Error("Home returned an invalid connection state.")); return; } + resolve(data.result); return; + } + const expectedResultKeys = action.kind !== "approve" ? ["status"] : ["status", "effect"]; + if ( + !hasExactKeys(data.result, expectedResultKeys) + || data.result.status !== (action.kind === "link" ? "linked" : action.kind === "disconnect" ? "disconnected" : "completed") + || ( + action.kind === "approve" + && !["signature", "transaction"].includes(data.result.effect) + ) + ) { + reject(new Error("Home returned an invalid wallet result.")); + return; + } + resolve(data.result); + }; + window.addEventListener("message", onMessage); + window.top.postMessage({ + type: HOST_EFFECT_TYPE, + schema: HOST_EFFECT_SCHEMA, + requestId, + connectorId: CONNECTOR_ID, + connectorToken: frameHomeToken, + action, + }, homeOrigin); + }); } -function isWalletConnectSignableRequest(request) { - const connectorId = readText(request && request.connector_id); - const intent = readText(request && request.intent); - const proofType = readText(request && request.proof_type); - return connectorId === CONNECTOR_ID - && intent !== "bitcoin_bip322_proof" - && (proofType === "siwe" || proofType === "siwe_erc1271"); +function nextHostRequestId() { + hostRequestSequence += 1; + const random = typeof window.crypto?.randomUUID === "function" + ? window.crypto.randomUUID() + : `${Date.now().toString(36)}-${hostRequestSequence}`; + return `wallet-effect:${random}`; } function walletIntentLabel(intent) { switch (readText(intent)) { - case "auth_challenge": - return "Sign in"; - case "capability_grant": - return "Grant access"; - case "credential": - return "Issue credential"; - case "publish_envelope": - return "Publish"; - case "transaction_intent": - return "Transaction"; - case "revocation": - return "Revoke"; - default: - return "Wallet request"; + case "auth_challenge": return "Sign in"; + case "browser_personal_sign": return "Sign message"; + case "browser_typed_data_sign": return "Sign typed data"; + case "capability_grant": return "Grant access"; + case "credential": return "Issue credential"; + case "publish_envelope": return "Publish"; + case "transaction_intent": return "Transaction"; + case "revocation": return "Revoke"; + default: return "Wallet request"; } } function chainLabel(value) { switch (readText(value)) { - case "eip155:1": - return "Ethereum"; - case "eip155:20": - return "Elastos Smart Chain"; - case "eip155:8453": - return "Base"; + case "eip155:1": return "Ethereum"; + case "eip155:20": return "Elastos Smart Chain"; + case "eip155:8453": return "Base"; + case "eip155:11155111": return "Sepolia test network"; default: { const chainId = readText(value).replace(/^eip155:/, ""); return chainId ? `EVM ${chainId}` : "EVM"; @@ -438,20 +336,20 @@ function chainLabel(value) { } } -function ensureSameAddress(actual, expected, message) { - if (normalizeAddress(actual) !== normalizeAddress(expected)) { - throw new Error(message); - } +function isManagedWalletRequest(request) { + return ["managed_evm", "managed_btc_p2wpkh"].includes(readText(request?.proof_type)); } -function normalizeAddress(address) { - return readText(address).toLowerCase(); +function isMetaMaskSignableRequest(request) { + return readText(request?.connector_id) === CONNECTOR_ID + && readText(request?.intent) !== "bitcoin_bip322_proof" + && ["siwe", "siwe_erc1271"].includes(readText(request?.proof_type)); } async function copyText(value) { const text = readText(value); if (!text) { - throw new Error("Nothing to copy."); + throw new Error("Clipboard is unavailable."); } await homeClipboard.writeText(text, { purpose: "wallet.address" }); } @@ -460,37 +358,39 @@ async function fetchJson(url, init) { const response = await fetch(url, init); if (!response.ok) { const detail = await response.text().catch(() => ""); - const suffix = detail.trim() ? ` ${detail.trim()}` : ` ${response.statusText}`; - throw new Error(`request failed: ${response.status}${suffix}`); + throw new Error(`request failed: ${response.status}${detail.trim() ? ` ${detail.trim()}` : ""}`); } return response.json(); } function shellHeaders(extra = {}) { - return { - ...extra, - "x-elastos-home-token": frameHomeToken, - }; + return { ...extra, "x-elastos-home-token": frameHomeToken }; } function notifyHomeSummaryChanged() { - if (!frameHomeToken || !homeOrigin || window.top === window) { - return; + if (frameHomeToken && homeOrigin && window.top !== window) { + window.top.postMessage({ type: "home:refresh-summary", homeToken: frameHomeToken }, homeOrigin); + } +} + +function hasExactKeys(value, expectedKeys) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return false; } - window.top.postMessage({ - type: "home:refresh-summary", - homeToken: frameHomeToken, - }, homeOrigin); + const actual = Object.keys(value).sort(); + const expected = [...expectedKeys].sort(); + return actual.length === expected.length + && actual.every((key, index) => key === expected[index]); } function readQueryParam(name) { - const value = new URLSearchParams(window.location.search).get(name); - return typeof value === "string" ? value.trim() : ""; + return readText(new URLSearchParams(window.location.search).get(name)); } function readLaunchToken() { - const value = new URLSearchParams(window.location.hash.replace(/^#/, "")).get("home_token"); - return typeof value === "string" ? value.trim() : ""; + return readText( + new URLSearchParams(window.location.hash.replace(/^#/, "")).get("home_token"), + ); } function readText(value) { @@ -499,30 +399,32 @@ function readText(value) { function shortAddress(value) { const address = readText(value); - if (address.length <= 14) { - return address; - } - return `${address.slice(0, 6)}...${address.slice(-4)}`; + return address.length <= 14 ? address : `${address.slice(0, 6)}...${address.slice(-4)}`; +} + +function emptyNode(message) { + const empty = document.createElement("div"); + empty.className = "wallet-empty"; + empty.textContent = message; + return empty; } function setState(message) { - if (stateNode) { - stateNode.textContent = message; - } + if (stateNode) stateNode.textContent = message; } function showStatus(message, tone) { - if (!statusNode) { - return; - } + if (!statusNode) return; const text = readText(message); - statusNode.hidden = text.length === 0; + statusNode.hidden = !text; statusNode.textContent = text; statusNode.dataset.tone = tone || "muted"; } function setButtonBusy(button, busy) { - if (button) { - button.disabled = Boolean(busy); - } + if (button) button.disabled = Boolean(busy); +} + +function errorMessage(error) { + return error instanceof Error ? error.message : String(error || "Wallet request failed."); } diff --git a/capsules/wallet-walletconnect/vendor/LICENSES.txt b/capsules/wallet-walletconnect/vendor/LICENSES.txt new file mode 100644 index 000000000..144ffc208 --- /dev/null +++ b/capsules/wallet-walletconnect/vendor/LICENSES.txt @@ -0,0 +1,8941 @@ +node_modules/@adraffy/ens-normalize/LICENSE +MIT License + +Copyright (c) 2021 Andrew Raffensperger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@base-org/account/LICENSE +Copyright (c) 2018-2025 Coinbase, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + +node_modules/@coinbase/cdp-sdk/LICENSE +MIT License + +Copyright (c) 2025 Coinbase + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@lit/react/LICENSE +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +node_modules/@lit/reactive-element/LICENSE +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +node_modules/@msgpack/msgpack/LICENSE +Copyright 2019 The MessagePack Community. + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/@noble/ciphers/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) +Copyright (c) 2016 Thomas Pornin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@noble/curves/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@phosphor-icons/webcomponents/LICENSE +MIT License + +Copyright (c) 2020 Phosphor Icons + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +<<<<<<< HEAD +SOFTWARE. +======= +SOFTWARE. +>>>>>>> 821e884... Initial commit + + +node_modules/@reown/appkit/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-common/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/node_modules/@msgpack/msgpack/LICENSE +Copyright 2019 The MessagePack Community. + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/@reown/appkit-controllers/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit-controllers/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit-controllers/node_modules/@walletconnect/core/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/node_modules/@walletconnect/sign-client/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/node_modules/@walletconnect/types/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/node_modules/@walletconnect/universal-provider/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/node_modules/@walletconnect/utils/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-controllers/node_modules/abitype/LICENSE +MIT License + +Copyright (c) 2022-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@reown/appkit-controllers/node_modules/es-toolkit/LICENSE +MIT License + +Copyright (c) 2024 Viva Republica, Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some of the test code in this software comes from the lodash library (https://github.com/lodash/lodash). + +The copyright for this imported test code from lodash is owned by the JS Foundation and other contributors . + + +node_modules/@reown/appkit-controllers/node_modules/ox/LICENSE +MIT License + +Copyright (c) 2023-present wevm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@reown/appkit-controllers/node_modules/ox/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit-pay/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-polyfills/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-scaffold-ui/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-ui/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-ui/node_modules/qrcode/license +The MIT License (MIT) + +Copyright (c) 2012 Ryan Day + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +node_modules/@reown/appkit-utils/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-utils/node_modules/@msgpack/msgpack/LICENSE +Copyright 2019 The MessagePack Community. + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/@reown/appkit-utils/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit-utils/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit-utils/node_modules/@walletconnect/core/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-utils/node_modules/@walletconnect/sign-client/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-utils/node_modules/@walletconnect/types/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-utils/node_modules/@walletconnect/universal-provider/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-utils/node_modules/@walletconnect/utils/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-utils/node_modules/abitype/LICENSE +MIT License + +Copyright (c) 2022-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@reown/appkit-utils/node_modules/es-toolkit/LICENSE +MIT License + +Copyright (c) 2024 Viva Republica, Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some of the test code in this software comes from the lodash library (https://github.com/lodash/lodash). + +The copyright for this imported test code from lodash is owned by the JS Foundation and other contributors . + + +node_modules/@reown/appkit-utils/node_modules/ox/LICENSE +MIT License + +Copyright (c) 2023-present wevm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@reown/appkit-utils/node_modules/ox/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit-wallet/LICENSE.md +**REOWN COMMUNITY LICENSE AGREEMENT** + +**Release Date: 25 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the Reown AppKit, Blockchain-API software development kit, documentation and related materials (collectively, “**AppKit Items**”). Before You access the AppKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the AppKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. By downloading, installing, integrating and/or using the AppKit Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the AppKit Items. + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the AppKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the AppKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of AppKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of AppKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the AppKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the AppKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the AppKit Items are not modifications or derivative works of the AppKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the AppKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the AppKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such AppKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the AppKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the AppKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of AppKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from AppKit Items or any products or services that use AppKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the AppKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using AppKit Items, or your product or service that uses AppKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE APPKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE APPKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the AppKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the AppKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the AppKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the AppKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the AppKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the AppKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the AppKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of AppKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of AppKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating AppKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the AppKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the AppKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit-wallet/node_modules/zod/LICENSE +MIT License + +Copyright (c) 2020 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@reown/appkit/node_modules/@msgpack/msgpack/LICENSE +Copyright 2019 The MessagePack Community. + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/@reown/appkit/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@reown/appkit/node_modules/@walletconnect/core/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit/node_modules/@walletconnect/sign-client/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit/node_modules/@walletconnect/types/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit/node_modules/@walletconnect/universal-provider/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit/node_modules/@walletconnect/utils/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@reown/appkit/node_modules/abitype/LICENSE +MIT License + +Copyright (c) 2022-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@reown/appkit/node_modules/es-toolkit/LICENSE +MIT License + +Copyright (c) 2024 Viva Republica, Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some of the test code in this software comes from the lodash library (https://github.com/lodash/lodash). + +The copyright for this imported test code from lodash is owned by the JS Foundation and other contributors . + + +node_modules/@reown/appkit/node_modules/ox/LICENSE +MIT License + +Copyright (c) 2023-present wevm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@reown/appkit/node_modules/ox/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@safe-global/safe-gateway-typescript-sdk/LICENSE.md +MIT License + +Copyright (c) 2021-2023 Safe Ecosystem Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@scure/base/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/@scure/bip32/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/@scure/bip32/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@scure/bip32/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@scure/bip39/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/@scure/bip39/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@solana/accounts/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/addresses/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/assertions/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/codecs/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/codecs-core/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/codecs-data-structures/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/codecs-numbers/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/codecs-strings/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/errors/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/fast-stable-stringify/LICENSE +Copyright (c) 2023 Solana Labs, Inc +Copyright (c) 2017 Nicolaas Johannes Out + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/fixed-points/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/functional/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/instruction-plans/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/instructions/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/keys/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/kit/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/nominal-types/LICENSE +Copyright (c) 2025 Anza Technology, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/offchain-messages/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/options/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/plugin-core/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/plugin-interfaces/LICENSE +Copyright (c) 2025 Anza Technology, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/program-client-core/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/programs/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/promises/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-api/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-parsed-types/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-spec/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-spec-types/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-subscriptions/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-subscriptions-api/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-subscriptions-channel-websocket/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-subscriptions-spec/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-transformers/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-transport-http/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/rpc-types/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/signers/LICENSE +Copyright (c) 2018 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/subscribable/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/sysvars/LICENSE +Copyright (c) 2018 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/transaction-confirmation/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/transaction-introspection/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/transaction-messages/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@solana/transactions/LICENSE +Copyright (c) 2023 Solana Labs, Inc + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/@types/react/LICENSE + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + +node_modules/@types/trusted-types/LICENSE + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE + + +node_modules/@wallet-standard/base/LICENSE + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +node_modules/@wallet-standard/wallet/LICENSE + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +node_modules/@walletconnect/core/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@walletconnect/environment/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/ethereum-provider/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@walletconnect/events/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/heartbeat/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/jsonrpc-http-connection/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@walletconnect/jsonrpc-provider/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/jsonrpc-types/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/jsonrpc-utils/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/jsonrpc-ws-connection/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/jsonrpc-ws-connection/node_modules/ws/LICENSE +The MIT License (MIT) + +Copyright (c) 2011 Einar Otto Stangvik + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@walletconnect/keyvaluestorage/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@walletconnect/logger/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/relay-api/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/relay-auth/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/relay-auth/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@walletconnect/safe-json/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/sign-client/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@walletconnect/time/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/types/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@walletconnect/universal-provider/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@walletconnect/utils/LICENSE.md +**WALLETCONNECT COMMUNITY LICENSE AGREEMENT** + +**Release Date: 20 August 2025** + +You, or the company or organization of which you are an employee, agent, or contractor (“**You**”, “**Your**”), desire a license from Reown, Inc. (“**We**”, “**Us**”, “**Our**”) to use the WalletKit software development kit, documentation and related materials (collectively, “**WalletKit Items**”). Before You access the WalletKit Items, We need to establish what you can expect from Us, and what We expect from You. By accessing and using the WalletKit Items, You confirm that You reviewed and You agree to this License Agreement (“**License**”), and that You are authorized to bind the company or organization you represent to this License. **_By downloading, installing, integrating and/or using the_** \*WalletKit **Items, you or the organization you represent, as applicable, agree to be bound by and become a party to this License as a "Licensee". If you do not agree to all of the terms of this License, you are not a Licensee and you may not download, install, or use (or must cease using) the WalletKit Items.\*** + +**1\. LICENSE** + +**a. Grant of Rights.** Subject to the terms and conditions of this License We grant You (and not Your affiliates or related persons), and You accept, a perpetual (subject to Section 8(b) Termination), non-exclusive, non-transferable (subject to Section 11(c) Assignment), non-sublicensable, and worldwide license under Our intellectual property rights to use, display, copy, transmit, distribute, modify, adapt, and create derivative works of the WalletKit Items. + +**b. Educational, Research and New Application Uses.** If You are using the WalletKit Items for educational or non-commercial research purposes, the License We grant You is royalty-free. In addition, Your use of WalletKit Items for development, maintenance and enhancement of Your applications and wallets is royalty-free, subject to Section 3\. + +**c. Modification of WalletKit Items.** We own all right, title and interest to the intellectual property rights (including, but not limited to patent, copyright, and trademark rights) to any modification to or derivative work of the WalletKit Items that You may develop, and you hereby assign any and all such rights to such modifications and derivative works to Us, subject to the following: + +(i) We hereby grant back to You a perpetual, non-exclusive, non-transferable, royalty-free, worldwide right and license to use these modifications and derivative works solely in conjunction with the WalletKit Items and only while this License remains in effect. You must cause any modified files to carry prominent notices stating that You changed the files. We and our assignees and Our and their licensees may use such modifications and derivative works without any approval from You and without compensation or attribution to You. You also agree to provide the source and binary code of any such modifications and derivative works to Us at the email address We may designate from time to time. + + (ii) For the avoidance of doubt, Your applications and wallets that you develop using the WalletKit Items are not modifications or derivative works of the WalletKit Items. You retain all rights to your applications and wallets, and you have no obligation to share or license Your applications or wallets with Us or with any third parties; provided, however, We retain all rights to the WalletKit Items and any modifications or derivative works thereof that may be incorporated into your applications and wallets. + +**2\. REDISTRIBUTION AND USE** + +**a. Distribution Requirements.** If You distribute or make available the WalletKit Items (including any modifications to or derivative works thereof) or any product or service that uses them (including Your applications and wallets), You must (i) include the following copyright notice in the notices or readme.txt of the product, or the about section of the website for the services: “Portions © 2025 Reown, Inc. All Rights Reserved” ; (ii) provide a copy of this License Agreement with any applications or wallets containing such WalletKit Items or that are required for the use thereof; and (iii) applicable logo and branding. + +**b. Network Connection.** As a material condition of this License, all use, distribution or derivatives works of the WalletKit Items must connect to the proprietary Reown gateway infrastructure, or its successor, and its related WalletConnect messaging protocol (collectively, the “**Network**”) unless we explicitly approve you doing otherwise. You further agree not to circumvent this requirement, or instruct or suggest to Your end users to do so. + +**c. Compliance with Law.** We are not in a position to monitor and assess the legality and regulatory treatment of your business and operations. Your use of the WalletKit Items must comply with all applicable laws and regulations and Our Terms of Service and Acceptable Use Policy, as amended from time to time, the terms of which are incorporated herein by reference. + +**d. Use of Marks.** This License does not grant permission to use Our trade names, trademarks, service marks, or product names (collectively, the “**Marks**”), except as permitted by Our Marks usage guidelines or as required for disclosure of the development of Your applications or wallets, reproducing the attribution notice in the readme.txt file, or Your redistribution of WalletKit Items. We reserve all rights not expressly granted to you under this License. Unless explicitly approved by Us, in no event will You use Our name, trademarks, or logos to endorse or imply Our endorsement of products derived from WalletKit Items or any products or services that use WalletKit Items. Where You are permitted to use the Marks, You must comply with Our then-current trademark and logo usage guidelines, as may be updated from time to time without notice from Us. All goodwill arising out of Your use of any Mark will inure solely to Us. + +**e. Export Controls.** You and We acknowledge that the WalletKit Items and all related technical information, documents and materials are subject to export controls under the U.S. Export Administration Regulations. You and We will (i) comply strictly with all legal requirements established under these controls, (ii) cooperate fully with each other in any official or unofficial audit or inspection that relates to these controls and (iii) not export, re-export, divert or transfer, directly or indirectly, any such item or direct products thereof to Cuba, Iran, North Korea, Sudan, and the Crimea, Donetsk, Luhansk, Kherson and Zaporizhzhia region not controlled by the government of Ukraine, or any national thereof or to any country or national thereof that is embargoed by Executive order, unless such party has obtained the prior written authorization of the other party and U.S. Commerce Department. We may modify this list to conform to changes in the U.S. Export Administration Regulations. + +**3\. LIMITED COMMERCIAL USE** + +If the number of remote processing calls (RPCs) made by, or monthly active users of (MAUs), associated with Your application or wallet developed using WalletKit Items, or your product or service that uses WalletKit Items exceed the thresholds set forth below, determined in our sole discretion, You must enter into and pay applicable fees and charges for a commercial license. You may contact Reown for these purposes using [this form](https://share.hsforms.com/1_oWa8QkwRXi6oR0nZ_SIxQnxw6s). + +- Monthly RPC limit of 2,500,000 + +- Monthly MAU limit of 500 + +MAU means, as applicable: (1) a unique externally owned account that authenticates and connects to your app in a 30 day period; or (2) a unique embedded wallet that is created on, and authenticates and connects, to your app in a 30 day period + +We reserve the right to change the RPC and/or MAU limit thresholds and/or set different or additional triggers or thresholds for requiring a commercial license. The current thresholds or triggers for a commercial license may be published on Our [Terms of Service](https://reown.com/terms-of-service). + +**4\. DISCLAIMER OF WARRANTY** + +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE WALLETKIT ITEMS ARE PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND. ALL WARRANTIES, CONDITIONS, REPRESENTATIONS, INDEMNITIES AND GUARANTEES WITH RESPECT TO THE WALLETKIT ITEMS, WHETHER EXPRESS OR IMPLIED, ARISING BY LAW, CUSTOM, PRIOR ORAL OR WRITTEN STATEMENTS BY US OR OTHERWISE (INCLUDING, BUT NOT LIMITED TO ANY WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT) ARE HEREBY OVERRIDDEN, EXCLUDED AND DISCLAIMED. SOME JURISDICTIONS DO NOT PERMIT THE DISCLAIMER OF ALL WARRANTIES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**5\. LIMITATION OF LIABILITY** + +IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW DESPITE THIS LIMITATION OR AGREED TO IN WRITING BY US, WILL WE BE LIABLE TO YOU OR YOUR LICENSEES OR SUBLICENSEES FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR OUT OF THE USE OR INABILITY TO USE THE WALLETKIT ITEMS OR ANY PORTION THEREOF (INCLUDING BUT NOT LIMITED TO DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES), EVEN IF WE OR OUR AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF ALL DAMAGES SO YOU MAY HAVE ADDITIONAL RIGHTS PROVIDED BY LAW. + +**6\. INTELLECTUAL PROPERTY** + +All trademarks, service marks, patents, copyrights, trade secrets, or other proprietary rights in or related to the WalletKit Items are and will remain Our exclusive property (or that of Our licensors). You will not take any action that jeopardizes those rights, nor will you acquire any right in the WalletKit Items, except the limited use rights specified in this License. You acknowledge that We (or Our licensors) will own all rights in any copy, translation, modification, adaptation or derivative works of the WalletKit Items (whether or not authorized by Us), and You will provide any instrument We reasonably request that you obtain to give full legal effect to Our rights under this Section. + +**7\. CONFIDENTIALITY** + +You acknowledge that the WalletKit Items incorporate nonpublic confidential and proprietary information We have developed or acquired or licensed ("**Confidential Information**"). You will keep the Confidential Information in the strictest confidence and will not use or copy any Confidential Information, or disclose it to any other person. You will not permit removal or defacing of any confidentiality or proprietary notice placed on or in the WalletKit Items, and any copyright notices on or in these items does not constitute publication or make them non-confidential. + +**8\. TERM AND TERMINATION** + +**a. Term.** The term of this Agreement will commence upon Your accessing the WalletKit Items and will continue in full force and effect until terminated in accordance with the terms and conditions of this License. As this License is updated for future releases of the WalletKit Items, You must abide by and meet all requirements of future updates of this License for those future releases of WalletKit Items, and such future updates of this License will apply to such future applications and wallets that may be developed with that future release of WalletKit Items or any portion thereof. You may not use older versions of the SDK to circumvent the terms applicable to new versions you choose to download or use. + + **b. Termination.** This License terminates (i) 30 days after either We notify you in writing that You have breached a material term of this License, if that breach is not cured before then, or (ii) immediately and automatically if You are declared bankrupt or become insolvent. Your right to access the Network ceases, if this License terminates, and We may disable Your access to the Network upon such termination. You may terminate this License at any time by disintegrating WalletKit Items from your products and services and disabling access to the Network. If this License terminates, You must immediately cease all use of and delete the WalletKit Items, in whole or in part, as well as any Confidential Information, in Your possession or control. At Our request, You will certify Your compliance with these obligations in writing. Sections 2, 4 through 7, 8(b), and 9 through 11 will survive any termination of this Agreement. + +**9\. GOVERNING LAW** + +This Agreement will be governed and construed under the laws of the State of Delaware, U.S.A., without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. + +**10\. DISPUTE RESOLUTION** + +PLEASE READ THE FOLLOWING SECTION CAREFULLY BECAUSE IT REQUIRES YOU TO SUBMIT TO BINDING ARBITRATION (JURY TRIAL WAIVER) OF ANY AND ALL DISPUTES (OTHER THAN SPECIFIED SMALL CLAIMS) WITH REOWN, INC. AND LIMITS THE MANNER IN WHICH YOU CAN SEEK RELIEF FROM REOWN, INC. (NO CLASS ARBITRATIONS, CLASS ACTIONS OR REPRESENTATIVE ACTIONS OR ARBITRATIONS). + +**a. Binding Arbitration; Disputes; Small Claims.** **You and We waive any right to a jury trial, or the right to have any Dispute resolved in any court, and instead accept the use of binding arbitration (which is the referral of a Dispute to one or more impartial persons for a final and binding determination); provided, however, that you have the right to litigate any Dispute in small claims court, if all the requirements of the small claims court, including any limitations on jurisdiction and the amount at issue in the Dispute, are satisfied. You agree to bring a Dispute in small claims court in the State of Delaware**. “**Dispute**” **as used in this Section 10 means any dispute, cause of action, claim, or controversy arising out of or in any way related to Us, this License, the subject matter of this License, or access to and use of the WalletKit Items, in whole or in part, or the Network, including but not limited to personal injury disputes and disputes that involve third parties (such as developers of applications or wallets).** + +**b. No Class Arbitrations, Class Actions or Representative Actions.** **You and We agree that any Dispute is personal to You and Us, and that any Dispute must only be resolved by an individual arbitration and may not be brought as a class arbitration, a class action, or any other representative proceeding. Neither party agrees to class arbitration, or an arbitration where a person brings a Dispute as a representative of any other person or persons. Neither You nor We agree that a Dispute can be brought as a class or representative action whether inside or outside of arbitration, or on behalf of any other person or persons**. + +**c. Federal Arbitration Act.** You and We agree that the terms of this License affect interstate commerce and that the enforceability of Section 10 is governed by, construed, and enforced, both substantively and procedurally, by the Federal Arbitration Act, 9 U.S.C. § 1 et seq. (“**FAA**”) to the maximum extent permitted by applicable law. + +**d. Confidentiality.** The arbitrator, You and We must maintain the confidentiality of any proceedings, including but not limited to, any and all information gathered, prepared, and presented for purposes of the arbitration or related to the Dispute(s) therein. The arbitrator has the authority to make appropriate rulings to safeguard that confidentiality, unless the law provides to the contrary. + +**e. Process.** Our goal is to resolve claims fairly and quickly. Accordingly, for any Dispute that you have against Us, you must first contact Us and attempt to resolve the claim informally by sending a written notice of your claim (“**Notice**”) to Us. The Notice to Us must be sent by certified mail addressed to: Reown Inc., 200 Continental Drive, 401, Newark, DE 19713 USA and a copy must be sent on the same day via email to Legal@walletconnect.com. The Notice must (a) include Your name, residence address, projectID and the email address and/or mobile telephone number associated with your account; (b) describe the nature and basis of the claim; and (c) set forth the specific relief sought. If You and We cannot reach an agreement to resolve the claim within 30 days after such Notice is received, then either party may, as appropriate in accordance with this Section 10, commence an arbitration proceeding or file a claim in small claims court. + +**f. Binding Arbitration.** In the event that You and We cannot resolve a Dispute and do not pursue the matter through small claims court, You or We must promptly submit the Dispute to binding arbitration before the American Arbitration Association (“**AAA**”). In the event AAA declines or is unable to administer the arbitration, You and We agree to use an arbitration forum or arbitrator that You and We mutually agree upon. If, after making a reasonable effort, You and We are not able to agree upon an arbitration forum or arbitrator, AAA or a court having proper jurisdiction will appoint an arbitration forum or arbitrator. The arbitration will be conducted in accordance with the AAA Consumer Arbitration Rules (“**AAA Rules**”) then in effect. The AAA Rules and other information about AAA and arbitration are readily available at [http://www.adr.org](http://www.adr.org/), by calling 1-800-778-7879, or by mail at 120 Broadway, Floor 21, New York, NY 10271\. By entering into this License, you either (1) acknowledge that you have read and understand the AAA Rules or (2) waive reading the AAA Rules and waive any claim that the AAA Rules are unfair in any way. You and We agree that the terms of this License govern the arbitration, and that the applicable AAA Rules are subject to changes in procedures that AAA may make from time to time. + +**g. Arbitrator Empowered.** As limited by the FAA, the terms of this License, and the applicable AAA Rules, the arbitrator will have the exclusive power and jurisdiction to make all procedural and substantive decisions concerning the Dispute; provided, however, that this power does not include: (i) the power to determine the question of arbitrability, which power You and We agree is vested solely in a court of competent jurisdiction; or (ii) the power to conduct a class arbitration or a representative action, which is prohibited by the terms of this License (as stated above). The arbitrator may only conduct an individual arbitration, and may not consolidate more than one person’s claims and may not preside over any form of representative or class proceeding, or any proceeding on behalf of or involving more than one person or persons. + +**11\. MISCELLANEOUS** + +**a. Amendment.** This License may be amended by Us on a prospective basis, and your usage of the License after such amendments or changes signifies your consent to and acceptance of any such amendments or changes on a going forward basis. + +**b. Severability.** In the event any provision of this License is determined to be invalid, prohibited or unenforceable by a court or other body of competent jurisdiction, this License must be construed as if such invalid, prohibited or unenforceable provision has been more narrowly drawn so as not to be invalid, prohibited or unenforceable. + +**c. Assignment.** You may not assign any rights or obligations under this License, including by operation of law, without Our prior written consent, which may be withheld in its sole discretion. We may assign Our rights or obligations under this License in Our sole discretion. + +**d. Waiver.** Failure of either party at any time to enforce any of the provisions of this License will not be construed as a waiver of such provisions or in any way affect the validity of this License or parts thereof. + + +node_modules/@walletconnect/utils/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@walletconnect/utils/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@walletconnect/utils/node_modules/abitype/LICENSE +MIT License + +Copyright (c) 2022-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/@walletconnect/utils/node_modules/ox/LICENSE +MIT License + +Copyright (c) 2023-present wevm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/utils/node_modules/ox/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/@walletconnect/window-getters/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/@walletconnect/window-metadata/LICENSE +MIT License + +Copyright (c) 2022 WalletConnect, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/abitype/LICENSE +MIT License + +Copyright (c) 2022-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/ansi-regex/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/ansi-styles/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/anymatch/LICENSE +The ISC License + +Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/asynckit/LICENSE +The MIT License (MIT) + +Copyright (c) 2016 Alex Indigo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/atomic-sleep/LICENSE +The MIT License (MIT) +Copyright (c) 2020 David Mark Clements + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + + + +node_modules/axios/LICENSE +# Copyright (c) 2014-present Matt Zabriskie & Collaborators + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/axios-retry/LICENSE +Copyright 2019 Softonic International S.A. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +node_modules/base-x/LICENSE.md +The MIT License (MIT) + +Copyright (c) 2018 base-x contributors +Copyright (c) 2014-2018 The Bitcoin Core developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/base64-js/LICENSE +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/big.js/LICENCE.md +The MIT License (MIT) +===================== + +Copyright © `<2024>` `Michael Mclaughlin` + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + + + +node_modules/blakejs/LICENSE +Copyright (c) 2022 Blakejs contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + +node_modules/bs58/LICENSE +MIT License + +Copyright (c) 2018 cryptocoinjs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/buffer/LICENSE +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh, and other contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/call-bind-apply-helpers/LICENSE +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/camelcase/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/chalk/license +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/charenc/LICENSE.mkd +Copyright © 2011, Paul Vorbach. All rights reserved. +Copyright © 2009, Jeff Mott. All rights reserved. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name Crypto-JS nor the names of its contributors may be used to + endorse or promote products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +node_modules/chokidar/LICENSE +The MIT License (MIT) + +Copyright (c) 2012 Paul Miller (https://paulmillr.com), Elan Shanker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/cliui/LICENSE.txt +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/clsx/license +MIT License + +Copyright (c) Luke Edwards (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/color-convert/LICENSE +Copyright (c) 2011-2016 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +node_modules/color-name/LICENSE +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +node_modules/combined-stream/License +Copyright (c) 2011 Debuggable Limited + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/commander/LICENSE +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/cookie-es/LICENSE +MIT License + +Cookie-es copyright (c) Pooya Parsa + +Cookie parsing based on https://github.com/jshttp/cookie +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +Set-Cookie parsing based on https://github.com/nfriedly/set-cookie-parser +Copyright (c) 2015 Nathan Friedly (http://nfriedly.com/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/cross-fetch/LICENSE +The MIT License (MIT) + +Copyright (c) 2017 Leonardo Quixadá + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/crossws/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Bundled with https://github.com/websockets/ws + +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/crypt/LICENSE.mkd +Copyright © 2011, Paul Vorbach. All rights reserved. +Copyright © 2009, Jeff Mott. All rights reserved. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name Crypto-JS nor the names of its contributors may be used to + endorse or promote products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +node_modules/csstype/LICENSE +Copyright (c) 2017-2018 Fredrik Nicol + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/dayjs/LICENSE +MIT License + +Copyright (c) 2018-present, iamkun + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/debug/LICENSE +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +node_modules/decamelize/license +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/defu/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/delayed-stream/License +Copyright (c) 2011 Debuggable Limited + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/destr/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/detect-browser/LICENSE +The MIT License (MIT) + +Copyright (c) 2019 Damon Oehlman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/dijkstrajs/LICENSE.md +``` +Dijkstra path-finding functions. Adapted from the Dijkstar Python project. + +Copyright (C) 2008 + Wyatt Baldwin + All rights reserved + +Licensed under the MIT license. + + http://www.opensource.org/licenses/mit-license.php + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + + +node_modules/dunder-proto/LICENSE +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/es-define-property/LICENSE +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/es-errors/LICENSE +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/es-object-atoms/LICENSE +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/es-set-tostringtag/LICENSE +MIT License + +Copyright (c) 2022 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/es-toolkit/LICENSE +MIT License + +Copyright (c) 2024 Viva Republica, Inc + +Copyright OpenJS Foundation and other contributors + +Parts of the test suite and compatibility layer in `es-toolkit/compat` are derived from Lodash (https://github.com/lodash/lodash) by the OpenJS Foundation (https://openjsf.org/) and Underscore.js by Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors (http://underscorejs.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/esbuild/LICENSE.md +MIT License + +Copyright (c) 2020 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/eventemitter3/LICENSE +The MIT License (MIT) + +Copyright (c) 2014 Arnout Kazemier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/events/LICENSE +MIT + +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/find-up/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/follow-redirects/LICENSE +Copyright 2014–present Olivier Lalonde , James Talmage , Ruben Verborgh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/form-data/License +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + +node_modules/function-bind/LICENSE +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + +node_modules/get-caller-file/LICENSE.md +ISC License (ISC) +Copyright 2018 Stefan Penner + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/get-intrinsic/LICENSE +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/get-proto/LICENSE +MIT License + +Copyright (c) 2025 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/gopd/LICENSE +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/h3/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/has-symbols/LICENSE +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/has-tostringtag/LICENSE +MIT License + +Copyright (c) 2021 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/hasown/LICENSE +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/idb-keyval/LICENCE +Copyright 2016, Jake Archibald + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +node_modules/ieee754/LICENSE +Copyright 2008 Fair Oaks Labs, Inc. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +node_modules/iron-webcrypto/LICENSE.md +MIT License + +Copyright (c) 2021 Divyansh Singh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/is-buffer/LICENSE +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/is-fullwidth-code-point/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/is-retry-allowed/license +MIT License + +Copyright (c) Vsevolod Strukchinsky (github.com/floatdrop) +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/isows/LICENSE +MIT License + +Copyright (c) 2023-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/jose/LICENSE.md +The MIT License (MIT) + +Copyright (c) 2018 Filip Skokan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/keyvaluestorage-interface/LICENSE +MIT License + +Copyright (c) 2020 Pedro Gomes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/lit/LICENSE +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +node_modules/lit-element/LICENSE +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +node_modules/lit-html/LICENSE +BSD 3-Clause License + +Copyright (c) 2017 Google LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +node_modules/locate-path/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/lru-cache/LICENSE.md +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** + + +node_modules/math-intrinsics/LICENSE +MIT License + +Copyright (c) 2024 ECMAScript Shims + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/md5/LICENSE +Copyright © 2011-2012, Paul Vorbach. +Copyright © 2009, Jeff Mott. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name Crypto-JS nor the names of its contributors may be used to + endorse or promote products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +node_modules/mime-db/LICENSE +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/mime-types/LICENSE +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/ms/license.md +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/node-fetch/LICENSE.md +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +node_modules/node-fetch-native/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +https://github.com/node-fetch/node-fetch + +The MIT License (MIT) + +Copyright (c) 2016 - 2020 Node Fetch Team + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +https://github.com/mysticatea/abort-controller + +MIT License + +Copyright (c) 2017 Toru Nagashima + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +https://github.com/TooTallNate/proxy-agents + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +https://github.com/nodejs/undici + +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/node-mock-http/LICENSE +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/normalize-path/LICENSE +The MIT License (MIT) + +Copyright (c) 2014-2018, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/ofetch/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/on-exit-leak-free/LICENSE +MIT License + +Copyright (c) 2021 Matteo Collina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/ox/LICENSE +MIT License + +Copyright (c) 2023-present wevm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/ox/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/p-limit/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/p-locate/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/p-try/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/path-exists/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/picomatch/LICENSE +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/pino/LICENSE +The MIT License (MIT) + +Copyright (c) 2016-2025 Matteo Collina, David Mark Clements and the Pino contributors listed at and in the README file. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/pino-abstract-transport/LICENSE +MIT License + +Copyright (c) 2021 pino + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/pino-std-serializers/LICENSE +Copyright Mateo Collina, David Mark Clements, James Sumners + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/pngjs/LICENSE +pngjs2 original work Copyright (c) 2015 Luke Page & Original Contributors +pngjs derived work Copyright (c) 2012 Kuba Niegowski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/preact/LICENSE +The MIT License (MIT) + +Copyright (c) 2015-present Jason Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/process-warning/LICENSE +MIT License + +Copyright (c) 2020-present The Fastify team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/proxy-compare/LICENSE +The MIT License (MIT) + +Copyright (c) 2020 Daishi Kato + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/proxy-from-env/LICENSE +The MIT License + +Copyright (C) 2016-2018 Rob Wu + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/qrcode/license +The MIT License (MIT) + +Copyright (c) 2012 Ryan Day + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +node_modules/quick-format-unescaped/LICENSE +The MIT License (MIT) + +Copyright (c) 2016-2019 David Mark Clements + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/radix3/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/readdirp/LICENSE +MIT License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/real-require/LICENSE.md +The MIT License (MIT) + +Copyright (c) 2021 Paolo Insogna and the real-require contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/require-directory/LICENSE +The MIT License (MIT) + +Copyright (c) 2011 Troy Goode + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/require-main-filename/LICENSE.txt +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/safe-stable-stringify/LICENSE +The MIT License (MIT) + +Copyright (c) Ruben Bridgewater + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/semver/LICENSE +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/set-blocking/LICENSE.txt +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/slow-redact/LICENSE +MIT License + +Copyright (c) 2025 pinojs contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/sonic-boom/LICENSE +MIT License + +Copyright (c) 2017 Matteo Collina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/split2/LICENSE +Copyright (c) 2014-2018, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/string-width/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/strip-ansi/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/thread-stream/LICENSE +MIT License + +Copyright (c) 2021 Matteo Collina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/tslib/LICENSE.txt +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +node_modules/ufo/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/uncrypto/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/undici-types/LICENSE +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/unstorage/LICENSE +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/valtio/LICENSE +MIT License + +Copyright (c) 2020 Poimandres + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/viem/LICENSE +MIT License + +Copyright (c) 2023-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/viem/node_modules/@noble/curves/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/viem/node_modules/@noble/hashes/LICENSE +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +node_modules/viem/node_modules/abitype/LICENSE +MIT License + +Copyright (c) 2022-present weth, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/viem/node_modules/ox/LICENSE +MIT License + +Copyright (c) 2023-present wevm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +node_modules/viem/node_modules/ws/LICENSE +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/webidl-conversions/LICENSE.md +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +node_modules/whatwg-url/LICENSE.txt +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/which-module/LICENSE +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +node_modules/wrap-ansi/license +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/ws/LICENSE +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +node_modules/y18n/LICENSE +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +node_modules/yargs/LICENSE +MIT License + +Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +node_modules/yargs-parser/LICENSE.txt +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +node_modules/zod/LICENSE +MIT License + +Copyright (c) 2025 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +node_modules/zustand/LICENSE +MIT License + +Copyright (c) 2019 Paul Henschel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/capsules/wallet-walletconnect/vendor/adapter.json b/capsules/wallet-walletconnect/vendor/adapter.json new file mode 100644 index 000000000..94035ff70 --- /dev/null +++ b/capsules/wallet-walletconnect/vendor/adapter.json @@ -0,0 +1,6 @@ +{ + "sdk_package": "@walletconnect/ethereum-provider", + "sdk_version": "2.23.9", + "sdk_sha256": "2d49248cf55d0f7f6a37ca3836d28681384a23be32ac3e9158f98619cbd84dc7", + "dependency_lock_sha256": "a12af83d3f92729c8bf06ff21505973a68c01d9fe08e157d837adc6c4b08833d" +} diff --git a/capsules/wallet-walletconnect/vendor/package-lock.json b/capsules/wallet-walletconnect/vendor/package-lock.json new file mode 100644 index 000000000..f231e7c35 --- /dev/null +++ b/capsules/wallet-walletconnect/vendor/package-lock.json @@ -0,0 +1,4930 @@ +{ + "name": "walletconnect", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@walletconnect/ethereum-provider": "2.23.9", + "qrcode": "1.5.4" + }, + "devDependencies": { + "esbuild": "0.28.0" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@base-org/account": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@base-org/account/-/account-2.4.0.tgz", + "integrity": "sha512-A4Umpi8B9/pqR78D1Yoze4xHyQaujioVRqqO3d6xuDFw9VRtjg6tK3bPlwE0aW+nVH/ntllCpPa2PbI8Rnjcug==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@coinbase/cdp-sdk": "^1.0.0", + "@noble/hashes": "1.4.0", + "clsx": "1.2.1", + "eventemitter3": "5.0.1", + "idb-keyval": "6.2.1", + "ox": "0.6.9", + "preact": "10.24.2", + "viem": "^2.31.7", + "zustand": "5.0.3" + } + }, + "node_modules/@coinbase/cdp-sdk": { + "version": "1.62.0", + "resolved": "https://registry.npmjs.org/@coinbase/cdp-sdk/-/cdp-sdk-1.62.0.tgz", + "integrity": "sha512-i25CM7YkheI4bIUUfdEl1ZFl8OhPtlr6HsOULSSPrOOetEEIo6KC81vr3RmrhejwYLzC9GSbVbfxy2pxgjPIXQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana-program/system": "^0.16.0", + "@solana-program/token": "^0.16.0", + "@solana/kit": "^8.6.0", + "abitype": "1.0.6", + "axios": "^1.18.0", + "axios-retry": "^4.5.0", + "bs58": "^6.0.0", + "jose": "^6.2.0", + "md5": "^2.3.0", + "uncrypto": "^0.1.3", + "viem": "^2.47.0", + "zod": "^3.25.76" + }, + "peerDependencies": { + "@x402/core": "^2.29.0", + "@x402/evm": "^2.29.0", + "@x402/extensions": "^2.29.0", + "@x402/svm": "^2.29.0" + }, + "peerDependenciesMeta": { + "@x402/core": { + "optional": true + }, + "@x402/evm": { + "optional": true + }, + "@x402/extensions": { + "optional": true + }, + "@x402/svm": { + "optional": true + } + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", + "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", + "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", + "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", + "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", + "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", + "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", + "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", + "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", + "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", + "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", + "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", + "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", + "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", + "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", + "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", + "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", + "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", + "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", + "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", + "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", + "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", + "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", + "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", + "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", + "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@lit-labs/ssr-dom-shim": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz", + "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@lit/react": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@lit/react/-/react-1.0.8.tgz", + "integrity": "sha512-p2+YcF+JE67SRX3mMlJ1TKCSTsgyOVdAwd/nxp3NuV1+Cb6MWALbN6nT7Ld4tpmYofcE5kcaSY1YBB9erY+6fw==", + "license": "BSD-3-Clause", + "optional": true, + "peerDependencies": { + "@types/react": "17 || 18 || 19" + } + }, + "node_modules/@lit/reactive-element": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz", + "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0" + } + }, + "node_modules/@msgpack/msgpack": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz", + "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.8.0.tgz", + "integrity": "sha512-j84kjAbzEnQHaSIhRPUmB3/eVXu2k3dKPl2LOrR8fSOIL+89U+7lV117EWHtq/GHM3ReGHM46iRBdZfpc4HRUQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.7.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves/node_modules/@noble/hashes": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.0.tgz", + "integrity": "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz", + "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@phosphor-icons/webcomponents": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@phosphor-icons/webcomponents/-/webcomponents-2.1.5.tgz", + "integrity": "sha512-JcvQkZxvcX2jK+QCclm8+e8HXqtdFW9xV4/kk2aL9Y3dJA2oQVt+pzbv1orkumz3rfx4K9mn9fDoMr1He1yr7Q==", + "license": "MIT", + "dependencies": { + "lit": "^3" + } + }, + "node_modules/@reown/appkit": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit/-/appkit-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-7JjEp+JNxRUDOa7CxOCbUbG8uYVo38ojc9FN/fuzJuJADUzKDaH287MLV9qI1ZyQyXA8qXvhXRqjtw+3xo2/7A==", + "hasInstallScript": true, + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-pay": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-scaffold-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/universal-provider": "2.23.2", + "bs58": "6.0.0", + "semver": "7.7.2", + "valtio": "2.1.7", + "viem": ">=2.37.9" + }, + "optionalDependencies": { + "@lit/react": "1.0.8" + } + }, + "node_modules/@reown/appkit-common": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-common/-/appkit-common-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-wf53EzDmCJ5ICtDY5B1MddVeCwoqDGPVmaxD4wQJLR9uanhBXfKq1sJou+Uj8lZCyI72Z+r9YlsePOlYH2Ge3A==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "big.js": "6.2.2", + "dayjs": "1.11.13", + "viem": ">=2.37.9" + } + }, + "node_modules/@reown/appkit-controllers": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-controllers/-/appkit-controllers-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-wY5yvMB0o2AwitwDHHO0u2tmqR+n3Crv0AHjIcY037PC3mhF9TPEUKqE9vlrFImQWQRxl0WRfuKfzmUAPxZExw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/universal-provider": "2.23.2", + "valtio": "2.1.7", + "viem": ">=2.37.9" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@msgpack/msgpack": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", + "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/core": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", + "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.39.3", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/sign-client": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", + "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.2", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/types": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", + "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/universal-provider": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", + "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "es-toolkit": "1.39.3", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/utils": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", + "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.2", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "bs58": "6.0.0", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-controllers/node_modules/es-toolkit": { + "version": "1.39.3", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", + "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/@reown/appkit-controllers/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-controllers/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-pay": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-pay/-/appkit-pay-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-sVE8UT7CDA8zsg3opvbGjSZHSnohOVPF77vP6Ln4G0+vfoiXNhZaZa89Pg0MDjh+KGy0OulWVUdXuZ9jJQFvPg==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", + "lit": "3.3.0", + "valtio": "2.1.7" + } + }, + "node_modules/@reown/appkit-polyfills": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-polyfills/-/appkit-polyfills-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-OyYavslCegfUlKu8Ah6BZhbqQrK7bImvUm+EKjjvnfNN9J0F9uWMFwbTpZxenBcfAI6cyaD9aTTUunMn5no1Og==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "buffer": "6.0.3" + } + }, + "node_modules/@reown/appkit-scaffold-ui": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-scaffold-ui/-/appkit-scaffold-ui-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-f+SYFGDy+uY1EAvWcH6vZgga1bOuzBvYSKYiRX2QQy8INtZqwwiLLvS4cgm5Yp1WvYRal5RdfZkKl5qha498gw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-pay": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "lit": "3.3.0" + } + }, + "node_modules/@reown/appkit-ui": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-ui/-/appkit-ui-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-E1u2ZVZV0iFDSgrgtdQTZAXNbI+Lakj8E8V+jJQ47JaEVKv9SROvPu2fVqfIrqHQF68NmAk1dnbYi4luOiM0Fg==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@phosphor-icons/webcomponents": "2.1.5", + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "lit": "3.3.0", + "qrcode": "1.5.3" + } + }, + "node_modules/@reown/appkit-ui/node_modules/qrcode": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.3.tgz", + "integrity": "sha512-puyri6ApkEHYiVl4CFzo1tDkAZ+ATcnbJrJ6RiBM1Fhctdn/ix9MTE3hRph33omisEbC/2fcfemsseiKgBPKZg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "encode-utf8": "^1.0.3", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/@reown/appkit-utils": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-utils/-/appkit-utils-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-9El8sYbXDaMYxg4R6LujA965yYQGjNcPMXqympLtzNl1es5qkniW7eAdEpLmZrsaqNrfTaHT1G65wYy7sA595w==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "@wallet-standard/wallet": "1.1.0", + "@walletconnect/logger": "3.0.2", + "@walletconnect/universal-provider": "2.23.2", + "valtio": "2.1.7", + "viem": ">=2.37.9" + }, + "optionalDependencies": { + "@base-org/account": "2.4.0", + "@safe-global/safe-apps-provider": "0.18.6", + "@safe-global/safe-apps-sdk": "9.1.0" + }, + "peerDependencies": { + "valtio": "2.1.7" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@msgpack/msgpack": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", + "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/core": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", + "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.39.3", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/sign-client": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", + "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.2", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/types": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", + "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/universal-provider": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", + "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "es-toolkit": "1.39.3", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/utils": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", + "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.2", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "bs58": "6.0.0", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@reown/appkit-utils/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-utils/node_modules/es-toolkit": { + "version": "1.39.3", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", + "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/@reown/appkit-utils/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-utils/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-wallet": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-wallet/-/appkit-wallet-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-s0RTVNtgPtXGs+eZELVvTu1FRLuN15MyhVS//3/4XafVQkBBJarciXk9pFP71xeSHRzjYR1lXHnVw28687cUvQ==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/logger": "3.0.2", + "zod": "3.22.4" + } + }, + "node_modules/@reown/appkit-wallet/node_modules/zod": { + "version": "3.22.4", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz", + "integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/@reown/appkit/node_modules/@msgpack/msgpack": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", + "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@reown/appkit/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/core": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", + "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.39.3", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/sign-client": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", + "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.2", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/types": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", + "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/universal-provider": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", + "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "es-toolkit": "1.39.3", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/utils": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", + "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.2", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "bs58": "6.0.0", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@reown/appkit/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@reown/appkit/node_modules/es-toolkit": { + "version": "1.39.3", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", + "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/@reown/appkit/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@reown/appkit/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@safe-global/safe-apps-provider": { + "version": "0.18.6", + "resolved": "https://registry.npmjs.org/@safe-global/safe-apps-provider/-/safe-apps-provider-0.18.6.tgz", + "integrity": "sha512-4LhMmjPWlIO8TTDC2AwLk44XKXaK6hfBTWyljDm0HQ6TWlOEijVWNrt2s3OCVMSxlXAcEzYfqyu1daHZooTC2Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@safe-global/safe-apps-sdk": "^9.1.0", + "events": "^3.3.0" + } + }, + "node_modules/@safe-global/safe-apps-sdk": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/@safe-global/safe-apps-sdk/-/safe-apps-sdk-9.1.0.tgz", + "integrity": "sha512-N5p/ulfnnA2Pi2M3YeWjULeWbjo7ei22JwU/IXnhoHzKq3pYCN6ynL9mJBOlvDVv892EgLPCWCOwQk/uBT2v0Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@safe-global/safe-gateway-typescript-sdk": "^3.5.3", + "viem": "^2.1.1" + } + }, + "node_modules/@safe-global/safe-gateway-typescript-sdk": { + "version": "3.23.1", + "resolved": "https://registry.npmjs.org/@safe-global/safe-gateway-typescript-sdk/-/safe-gateway-typescript-sdk-3.23.1.tgz", + "integrity": "sha512-6ORQfwtEJYpalCeVO21L4XXGSdbEMfyp2hEv6cP82afKXSwvse6d3sdelgaPWUxHIsFRkWvHDdzh8IyyKHZKxw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=16" + } + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", + "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.9.0", + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", + "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@solana-program/system": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@solana-program/system/-/system-0.16.0.tgz", + "integrity": "sha512-/RG6q2E2vG/XpdOt8Jj/kbQktPlL5JyJuNGAeN9wDcxKDKQtrGTJpDrJgQUxiEy23fsPNXQbLN8XeCtYoMof3Q==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@solana/kit": "^8.5.0" + } + }, + "node_modules/@solana-program/token": { + "version": "0.16.1", + "resolved": "https://registry.npmjs.org/@solana-program/token/-/token-0.16.1.tgz", + "integrity": "sha512-X9dsvbh+VDq4SuCfvxn95P1DCvtBYHJOBiVmgBJMfW8l/lp8uSwEhy9IurpcdltnGi5kNIkCm4sk4YOXKAMiCw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@solana-program/system": "^0.14.0" + }, + "peerDependencies": { + "@solana/kit": "^8.0.0" + } + }, + "node_modules/@solana-program/token/node_modules/@solana-program/system": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/@solana-program/system/-/system-0.14.1.tgz", + "integrity": "sha512-K6ZiIrAKoJAfcwfUdsoFvfSAxeRJaRrV7BPFTJvUVRS4m3zszN+nLcdaNMMe2F1/zTriZqC+xh+Kgw6ziGUqpQ==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@solana/kit": "^8.0.0" + } + }, + "node_modules/@solana/accounts": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/accounts/-/accounts-8.6.0.tgz", + "integrity": "sha512-yIcrKjbUXzs1K6KkcRJfAHFOsn8Jpp9AeczcHOHQoBv11AxHM5KmdCTv8rnv7OObq696sd3gpbamVxtqnL0meQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/addresses": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/addresses/-/addresses-8.6.0.tgz", + "integrity": "sha512-V30spa+zKsY7i4elEEOZQB/1xpRc0CzbSypI/yTZwj/Bg1o09T6A+pflMDTBoIWH3sglmigdK1jApEOOA7Bypg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/assertions": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/nominal-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/assertions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/assertions/-/assertions-8.6.0.tgz", + "integrity": "sha512-zQFbZoPFE3GqBw/7JyZxaH5t/Ibm7eHOmOfRI542/zz0BHWSnMkR0N5aSndPJd9creMUP+mFtX8hAr6bZ6rDBg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs/-/codecs-8.6.0.tgz", + "integrity": "sha512-7vUVLdYlTay3rsijiBPN4g992V8RXbgY2DNAXrsE6eHFnwaX8gzdDNASgF4Z0mbgNC026qdLG6LTY4l16tvE8g==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/fixed-points": "8.6.0", + "@solana/options": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-core": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-core/-/codecs-core-8.6.0.tgz", + "integrity": "sha512-1N2XZ1yCJGmdTE3g5Fh6/UOE6y46qing+7CZpxfrgB4Q+1l+R/d0z4G15IpQUNl3vzqML8CFF791f/A1XSVmJA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-data-structures": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-data-structures/-/codecs-data-structures-8.6.0.tgz", + "integrity": "sha512-BLwclFSLVqugUktXucjGfpUFSaX4V7payjSi6x0DDdLs6PaFfjiH3ykQPV5QRkTeOlf0xC6dOMUUntDhYzVyGw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-numbers": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-numbers/-/codecs-numbers-8.6.0.tgz", + "integrity": "sha512-GRIArvWJiYxH5w1RMKn7IOCLy0uYB/WRT2kFW/uyXHzL1VNFyud2BIzG0D3iM+AxTd85SdS/x93aV7NEw0mTOQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-strings": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-strings/-/codecs-strings-8.6.0.tgz", + "integrity": "sha512-bLS/o5NdCRb9xj23zLACPjxYvDhdjvSDH4XoBAmQ1CPn3cDvVqVvAz0T41Bs/LMykhamkmpqTcWLoTOVqjTz3w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "fastestsmallesttextencoderdecoder": "^1.0.22", + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "fastestsmallesttextencoderdecoder": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/errors": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/errors/-/errors-8.6.0.tgz", + "integrity": "sha512-viHL51ymR1HZB7ZTp0ESkLOyHCa4bPfok9dvRYbMmYokY5ys1xinISKHUhcOHsg9zbuAWBRJUOnZRWAPbb4+yA==", + "license": "MIT", + "optional": true, + "dependencies": { + "chalk": "5.6.2", + "commander": "15.0.0" + }, + "bin": { + "errors": "bin/cli.mjs" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/fast-stable-stringify": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/fast-stable-stringify/-/fast-stable-stringify-8.6.0.tgz", + "integrity": "sha512-PVuzLesqjvuW1qeg0brkUtpRnQYCLS0mB7SsFu+iio+dxFzbrrHzkSYVoUBEEbjXysCq1L350Frs1+v7CEsXGQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/fixed-points": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/fixed-points/-/fixed-points-8.6.0.tgz", + "integrity": "sha512-yS0XIHwWETtTjAgUHPhpQpcigPvC6phba3vW7rvVPSvVz1FhxNki82ojyl1pISglK7IkUTYcGhaXDhsY/oz8rQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/functional": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/functional/-/functional-8.6.0.tgz", + "integrity": "sha512-greLf2tiMJ5oWaSdp3zkAcUF3sIG3CU1UssxoMYNHy/xywbZifKnOl5syQjKY1XdYPZZmLAWJBFYCkzVns5bxA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/instruction-plans": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/instruction-plans/-/instruction-plans-8.6.0.tgz", + "integrity": "sha512-hq1bLZStauHKmwHWheCoF9UxcFlJsYm9X4saUj4llkJl6GmTrDTmeiE93mJngz4GO6cAkm65D/AjYRcp69jUVw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/instructions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/instructions/-/instructions-8.6.0.tgz", + "integrity": "sha512-1mXhgf5XaIJir02TgkUwzNRJs8mCCRRRsW45ZwqCp66bnIxmxEy3a91twgGXvBfE6dvzzg3TNSjcfqGQ/ADBog==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/keys": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/keys/-/keys-8.6.0.tgz", + "integrity": "sha512-vxj3zmcHfY0EqDSJR8nn7w/qQAdCG3uSyGGcIfLgf/ZhVUgVDYDUyUqrxSL5DxAs64czhSu+ufRh7B5AKwMtaQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/assertions": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/promises": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/kit": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/kit/-/kit-8.6.0.tgz", + "integrity": "sha512-UaigU+LiTzkU237FxfiJhxufvEfb1J02djJOnGpSz1GAjZtbZ8oc4EkQ1bS4sHewSRyR9RUk6yhBb5bLHG0w4w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/addresses": "8.6.0", + "@solana/codecs": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/offchain-messages": "8.6.0", + "@solana/plugin-core": "8.6.0", + "@solana/plugin-interfaces": "8.6.0", + "@solana/program-client-core": "8.6.0", + "@solana/programs": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc": "8.6.0", + "@solana/rpc-api": "8.6.0", + "@solana/rpc-parsed-types": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-subscriptions": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/signers": "8.6.0", + "@solana/subscribable": "8.6.0", + "@solana/sysvars": "8.6.0", + "@solana/transaction-confirmation": "8.6.0", + "@solana/transaction-introspection": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/nominal-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/nominal-types/-/nominal-types-8.6.0.tgz", + "integrity": "sha512-uuRReiuEWfTTwtlJNvTSStuHrDF45Itl2k3BGg/4kHWxqUdtS5u4PK4bMgzoPWoyPorDj5y6TEMa+MydM5D7Sg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/offchain-messages": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/offchain-messages/-/offchain-messages-8.6.0.tgz", + "integrity": "sha512-VFic3fotmL9fIjs7Amk402CMWLeWwhNQvAF9cyZO++x42oU2FNeTe27rxfgFLYPaIHaRonlII+5pmsHQHA240Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/nominal-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/options": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/options/-/options-8.6.0.tgz", + "integrity": "sha512-WFsTtIQukNGGHRImcmn8Se8o6A4vu4wY0fuLSeB/L7C45FPoQI2fTIud6hf9g2fum0dR3U0pFNIciwQjlVq2LA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/plugin-core": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/plugin-core/-/plugin-core-8.6.0.tgz", + "integrity": "sha512-wvjpR66FreDxDXfF5RrIay7aXW+JfcmSj1TiDu+rUyWaV1Xu390E/KKL3dM6OfkIOtP66H9M9w1XihB8syMkfg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/plugin-interfaces": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/plugin-interfaces/-/plugin-interfaces-8.6.0.tgz", + "integrity": "sha512-ta+JYsKD7GMUoBLbeE1nYKDPN9nOwQN1y04xR4tbyfDbNsGLPz3fTKH8Y48bOs552sW4OcUB8F3pGVZefqPyWg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/addresses": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/signers": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/program-client-core": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/program-client-core/-/program-client-core-8.6.0.tgz", + "integrity": "sha512-e6Wx2Y2UrQ0dPB6hndVcyUXQwBt9/DLr8k2P7tRgW0JNVhHNylZQ6aYQAqxZzS8Z92gGz7l3XL+r9tCLKBkIVw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/plugin-interfaces": "8.6.0", + "@solana/rpc-api": "8.6.0", + "@solana/signers": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/programs": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/programs/-/programs-8.6.0.tgz", + "integrity": "sha512-JKGtqXtiT4zon7xZkmys2G1/HchwbNjzbP+E+0Rp/Cko+svB9w9SE2PROEVJZS8UH98lbi1epjsHYAgESamwvg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/promises": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/promises/-/promises-8.6.0.tgz", + "integrity": "sha512-HLlAMwXnEyhg9HxVJGDlWgFlM4QUt/Qq0nL69bbC7COCHhUQFRcKLq5uIbaXPy7FNJlNBSTTCBZwI0IK9up0SQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc/-/rpc-8.6.0.tgz", + "integrity": "sha512-u5dg96ThDVAeklC9vtVpuYL7wRqkyolm++qYKd6yL7tPRdKZNxdGHbFHQR2qIcMQ0oVfEA9tGnQhplj+6Yt/0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/fast-stable-stringify": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/rpc-api": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-transport-http": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-api": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-api/-/rpc-api-8.6.0.tgz", + "integrity": "sha512-NFHtOB9z4HyV8frN84o+d9jKj5luRzrySZJLgwMgcG/Q2fWahTDrP+ZqRKLmqibvFBg/fwhcxl77+TfKZjpvhA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/rpc-parsed-types": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-parsed-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-parsed-types/-/rpc-parsed-types-8.6.0.tgz", + "integrity": "sha512-wZKtQOS3RdHZqJ3ycpdibup31tfbY6lHYGUKjmzeF6N2E2y7WEpB7qiEr9AMBB00mDUtorcqBMpOli6PyT4Gog==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-spec": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-spec/-/rpc-spec-8.6.0.tgz", + "integrity": "sha512-V1c+r6HXTb/nCEl5SHKLPzzb6aMEbr0lFOcgjEX8TQ8fE6ZlLzNz3tKvcgbBlOJCeyVXSrcNl3tv8i8xNp+n/g==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/subscribable": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-spec-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-spec-types/-/rpc-spec-types-8.6.0.tgz", + "integrity": "sha512-6+2F2BN2CXp4g7cnvLp2mRo/XwdN5At7f3HbdEablxNe1UvI5S8WIEY3l/Y+nh2NQIaEVz9fLjmTYV+UfZNzEg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions/-/rpc-subscriptions-8.6.0.tgz", + "integrity": "sha512-ZaoFtiKg25KqYykBslB8TDWqfm7S162FyTJvFI0HL0U94K1O675IG2h913mes3voatigpqLneFxkNrVs5yE7tA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/fast-stable-stringify": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-subscriptions-api": "8.6.0", + "@solana/rpc-subscriptions-channel-websocket": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/subscribable": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions-api": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-api/-/rpc-subscriptions-api-8.6.0.tgz", + "integrity": "sha512-Cbyi0ZpwNCcxRgjjc1vKVWBdwNOAKGT1VjryfQU/FDySUo2Lg8u5LUsJb6d53QD5dhEU+0nooxfBmRUUyebZug==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions-channel-websocket": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-channel-websocket/-/rpc-subscriptions-channel-websocket-8.6.0.tgz", + "integrity": "sha512-k1UmMiIJFeo7wAUTiqg7Ni6gdsJAd65D3Wxqdtf5iBX9TjkvWGrL3KXdJq2ZzS1c9eqd220W0v7fkFTA8tfX5Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/subscribable": "8.6.0", + "ws": "^8.21.3" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions-spec": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-spec/-/rpc-subscriptions-spec-8.6.0.tgz", + "integrity": "sha512-m7lBQS9hgzWN1ZI+JUy5rV8ctG7oy0WbGHoj4vevB4esK2SYUyI0eQB4GrQhVwGnkyTxATS/R91ZZzWYDKGXlg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/subscribable": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-transformers": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-transformers/-/rpc-transformers-8.6.0.tgz", + "integrity": "sha512-aSfctQeLTszEQdNGDrPWbi/7voJYrYo/rvIZRDbokYQRDwMuphw7kENGdwaQB7A9XSX0tsPe+dKkbxjWf0Druw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-transport-http": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-transport-http/-/rpc-transport-http-8.6.0.tgz", + "integrity": "sha512-jr7ef/UOIO7bRjI7DEXji3J7nCFO3jIYPGw3L0fyF7VEJox9Bh8TNHsn9G9jv1kqdwkUnFrPPWVMvmAWQwSmvg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "undici-types": "^8.12.3" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-types/-/rpc-types-8.6.0.tgz", + "integrity": "sha512-gg05ZjZq8sFcf0JKO6/MQ1oYSFQuT5SU51dhirGjfl8UCxX/Q6ocsUgzb9a/zPNrRsXJkduaZF1bARah7MrrYw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/fixed-points": "8.6.0", + "@solana/nominal-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/signers": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/signers/-/signers-8.6.0.tgz", + "integrity": "sha512-q8FNQfGnMsHc7VLBhh+TwsMfodiYtYhoTqNj6lDIP2bz93l173rzcZWSRH/hg/7ksFdhHuV4nEkWj0L65N0S0Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/offchain-messages": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/subscribable": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/subscribable/-/subscribable-8.6.0.tgz", + "integrity": "sha512-z6qRloUTxoI459dUV2K/HQZO1HYuP5f6NQxXxd25TtM2TDpnjOzoO3pJAlOZP3cwXGgtGk6UWmMEY1a4j0TILw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/promises": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/sysvars": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/sysvars/-/sysvars-8.6.0.tgz", + "integrity": "sha512-oAIVThVcZr2qDwdvc3Fx+CKCbG1d4VwwRDXbu/tDKVDUIZXDWoTP//BX0u1FimkuirMHHW9Sl+AsSGFba0KPew==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transaction-confirmation": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transaction-confirmation/-/transaction-confirmation-8.6.0.tgz", + "integrity": "sha512-kd7LwN1k6L+k9jXMjzm6KqGDuUsETZ1pWMnWY7ZT+1bDjRPbki/RylQc+2CIF7YYphT5GIloTmUziAAmhyw4eQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc": "8.6.0", + "@solana/rpc-subscriptions": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transaction-introspection": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transaction-introspection/-/transaction-introspection-8.6.0.tgz", + "integrity": "sha512-/7MYRLnM7AF0983oaicjhvWWQEdeFgknBiKG5LVFd8WT68m5vL18d7/fZHkvsA41zWkIIrRVuh0PM4COeENNlQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transaction-messages": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transaction-messages/-/transaction-messages-8.6.0.tgz", + "integrity": "sha512-Zb7mB8Xu+AXaNiSmgghsyliGNoi7HO4hKdyQC0Qth4hW9QOBMdjSJ687KIUwsAzDSVXwdIbsnkUPpwCl1fcMdw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transactions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transactions/-/transactions-8.6.0.tgz", + "integrity": "sha512-m2i0dxDtB9mGqhJd714OQpKzGFp9cQbU80kwIBFflOrHdZ2cJzZ61xjGe+vegz/WGsqPec604pUbHKXXIFkNjg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/@wallet-standard/base": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@wallet-standard/base/-/base-1.1.1.tgz", + "integrity": "sha512-gggIHTtxicF9XFMQ12DkfS6NAG92Ak795JeSA7f2whAQ6Y3AkMWWuCMxSZXG2NIPN42kEaZSNVjqMsJRaJRxMQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=22" + } + }, + "node_modules/@wallet-standard/wallet": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@wallet-standard/wallet/-/wallet-1.1.0.tgz", + "integrity": "sha512-Gt8TnSlDZpAl+RWOOAB/kuvC7RpcdWAlFbHNoi4gsXsfaWa1QCT6LBcfIYTPdOZC9OVZUDwqGuGAcqZejDmHjg==", + "license": "Apache-2.0", + "dependencies": { + "@wallet-standard/base": "^1.1.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@walletconnect/core": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.9.tgz", + "integrity": "sha512-ws4WG8LeagUo2ERRo02HryXRcpwIRmCQ3pHLW5gWbVReLXXIpgk6ZAfID3fEGHevIwwnHSGww+nNhNpdXyiq0g==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.9", + "@walletconnect/utils": "2.23.9", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.44.0", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@walletconnect/environment": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/environment/-/environment-1.0.1.tgz", + "integrity": "sha512-T426LLZtHj8e8rYnKfzsw1aG6+M0BT1ZxayMdv/p8yM0MU+eJDISqNY3/bccxRr4LrF9csq02Rhqt08Ibl0VRg==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/ethereum-provider": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/ethereum-provider/-/ethereum-provider-2.23.9.tgz", + "integrity": "sha512-Cb72KWl9S6mMs+c1MVGlSx07Dap1LFznYyWrg/XT5B8VtBKaH9Sw2lAvAL0ajGet6J5sq8sUx1pkg68tZwkqmA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.9", + "@walletconnect/types": "2.23.9", + "@walletconnect/universal-provider": "2.23.9", + "@walletconnect/utils": "2.23.9", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/events": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/events/-/events-1.0.1.tgz", + "integrity": "sha512-NPTqaoi0oPBVNuLv7qPaJazmGHs5JGyO8eEAk5VGKmJzDR7AHzD4k6ilox5kxk1iwiOnFopBOOMLs86Oa76HpQ==", + "license": "MIT", + "dependencies": { + "keyvaluestorage-interface": "^1.0.0", + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/heartbeat": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@walletconnect/heartbeat/-/heartbeat-1.2.2.tgz", + "integrity": "sha512-uASiRmC5MwhuRuf05vq4AT48Pq8RMi876zV8rr8cV969uTOzWdB/k+Lj5yI2PBtB1bGQisGen7MM1GcZlQTBXw==", + "license": "MIT", + "dependencies": { + "@walletconnect/events": "^1.0.1", + "@walletconnect/time": "^1.0.2", + "events": "^3.3.0" + } + }, + "node_modules/@walletconnect/jsonrpc-http-connection": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-http-connection/-/jsonrpc-http-connection-1.0.8.tgz", + "integrity": "sha512-+B7cRuaxijLeFDJUq5hAzNyef3e3tBDIxyaCNmFtjwnod5AGis3RToNqzFU33vpVcxFhofkpE7Cx+5MYejbMGw==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-utils": "^1.0.6", + "@walletconnect/safe-json": "^1.0.1", + "cross-fetch": "^3.1.4", + "events": "^3.3.0" + } + }, + "node_modules/@walletconnect/jsonrpc-provider": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-provider/-/jsonrpc-provider-1.0.14.tgz", + "integrity": "sha512-rtsNY1XqHvWj0EtITNeuf8PHMvlCLiS3EjQL+WOkxEOA4KPxsohFnBDeyPYiNm4ZvkQdLnece36opYidmtbmow==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-utils": "^1.0.8", + "@walletconnect/safe-json": "^1.0.2", + "events": "^3.3.0" + } + }, + "node_modules/@walletconnect/jsonrpc-types": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-types/-/jsonrpc-types-1.0.4.tgz", + "integrity": "sha512-P6679fG/M+wuWg9TY8mh6xFSdYnFyFjwFelxyISxMDrlbXokorEVXYOxiqEbrU3x1BmBoCAJJ+vtEaEoMlpCBQ==", + "license": "MIT", + "dependencies": { + "events": "^3.3.0", + "keyvaluestorage-interface": "^1.0.0" + } + }, + "node_modules/@walletconnect/jsonrpc-utils": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-utils/-/jsonrpc-utils-1.0.8.tgz", + "integrity": "sha512-vdeb03bD8VzJUL6ZtzRYsFMq1eZQcM3EAzT0a3st59dyLfJ0wq+tKMpmGH7HlB7waD858UWgfIcudbPFsbzVdw==", + "license": "MIT", + "dependencies": { + "@walletconnect/environment": "^1.0.1", + "@walletconnect/jsonrpc-types": "^1.0.3", + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/jsonrpc-ws-connection": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-ws-connection/-/jsonrpc-ws-connection-1.0.16.tgz", + "integrity": "sha512-G81JmsMqh5nJheE1mPst1W0WfVv0SG3N7JggwLLGnI7iuDZJq8cRJvQwLGKHn5H1WTW7DEPCo00zz5w62AbL3Q==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-utils": "^1.0.6", + "@walletconnect/safe-json": "^1.0.2", + "events": "^3.3.0", + "ws": "^7.5.1" + } + }, + "node_modules/@walletconnect/jsonrpc-ws-connection/node_modules/ws": { + "version": "7.5.13", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", + "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/@walletconnect/keyvaluestorage": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@walletconnect/keyvaluestorage/-/keyvaluestorage-1.1.1.tgz", + "integrity": "sha512-V7ZQq2+mSxAq7MrRqDxanTzu2RcElfK1PfNYiaVnJgJ7Q7G7hTVwF8voIBx92qsRyGHZihrwNPHuZd1aKkd0rA==", + "license": "MIT", + "dependencies": { + "@walletconnect/safe-json": "^1.0.1", + "idb-keyval": "^6.2.1", + "unstorage": "^1.9.0" + }, + "peerDependencies": { + "@react-native-async-storage/async-storage": "1.x" + }, + "peerDependenciesMeta": { + "@react-native-async-storage/async-storage": { + "optional": true + } + } + }, + "node_modules/@walletconnect/logger": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@walletconnect/logger/-/logger-3.0.2.tgz", + "integrity": "sha512-7wR3wAwJTOmX4gbcUZcFMov8fjftY05+5cO/d4cpDD8wDzJ+cIlKdYOXaXfxHLSYeDazMXIsxMYjHYVDfkx+nA==", + "license": "MIT", + "dependencies": { + "@walletconnect/safe-json": "^1.0.2", + "pino": "10.0.0" + } + }, + "node_modules/@walletconnect/relay-api": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@walletconnect/relay-api/-/relay-api-1.0.11.tgz", + "integrity": "sha512-tLPErkze/HmC9aCmdZOhtVmYZq1wKfWTJtygQHoWtgg722Jd4homo54Cs4ak2RUFUZIGO2RsOpIcWipaua5D5Q==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-types": "^1.0.2" + } + }, + "node_modules/@walletconnect/relay-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@walletconnect/relay-auth/-/relay-auth-1.1.0.tgz", + "integrity": "sha512-qFw+a9uRz26jRCDgL7Q5TA9qYIgcNY8jpJzI1zAWNZ8i7mQjaijRnWFKsCHAU9CyGjvt6RKrRXyFtFOpWTVmCQ==", + "license": "MIT", + "dependencies": { + "@noble/curves": "1.8.0", + "@noble/hashes": "1.7.0", + "@walletconnect/safe-json": "^1.0.1", + "@walletconnect/time": "^1.0.2", + "uint8arrays": "^3.0.0" + } + }, + "node_modules/@walletconnect/relay-auth/node_modules/@noble/hashes": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.0.tgz", + "integrity": "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/safe-json": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@walletconnect/safe-json/-/safe-json-1.0.2.tgz", + "integrity": "sha512-Ogb7I27kZ3LPC3ibn8ldyUr5544t3/STow9+lzz7Sfo808YD7SBWk7SAsdBFlYgP2zDRy2hS3sKRcuSRM0OTmA==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/sign-client": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.9.tgz", + "integrity": "sha512-Xj+hw4E6mGRyhCdVOT/RMgnG+up/Y3v0ho5PlkVozvXWeVSqHNh9DmjLuU97a7OACoGd/oHBF6g3NVqD7MgCMQ==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.9", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.9", + "@walletconnect/utils": "2.23.9", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/time": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@walletconnect/time/-/time-1.0.2.tgz", + "integrity": "sha512-uzdd9woDcJ1AaBZRhqy5rNC9laqWGErfc4dxA9a87mPdKOgWMD85mcFo9dIYIts/Jwocfwn07EC6EzclKubk/g==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/types": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.9.tgz", + "integrity": "sha512-IUl1PpD/Dig8IE2OZ9XtjbPohEyOZJ73xs92EDUzoIyzRtfm36g2D340pY3iu3AAdLv1yFiaZafB8Hf8RFze8A==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/universal-provider": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.9.tgz", + "integrity": "sha512-dNk6X1USUcIX1nx3H61V3pO15E/2ejyeBsKLBOo8YXrnYCrKGG/KB1LIqJXHpQlXT+9bJE9cOnn61ETdCXgkPw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.9", + "@walletconnect/types": "2.23.9", + "@walletconnect/utils": "2.23.9", + "es-toolkit": "1.44.0", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/utils": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.9.tgz", + "integrity": "sha512-C5TltCs8UPypNiteYnKSv8+ZDK2EjVDyXCxN6kA9bkA+j6KGsNIV7l9MUA8WBAvE5Gi5EcBdhD3R9Hpo/1HHqQ==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.3", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.9", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@walletconnect/utils/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/utils/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/utils/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@walletconnect/utils/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@walletconnect/utils/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/window-getters": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/window-getters/-/window-getters-1.0.1.tgz", + "integrity": "sha512-vHp+HqzGxORPAN8gY03qnbTMnhqIwjeRJNOMOAzePRg4xVEEE2WvYsI9G2NMjOknA8hnuYbU3/hwLcKbjhc8+Q==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/window-metadata": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/window-metadata/-/window-metadata-1.0.1.tgz", + "integrity": "sha512-9koTqyGrM2cqFRW517BPY/iEtUDx2r1+Pwwu5m7sJ7ka79wi3EyqhqcICk/yDmv6jAS1rjKgTKXlEhanYjijcA==", + "license": "MIT", + "dependencies": { + "@walletconnect/window-getters": "^1.0.1", + "tslib": "1.14.1" + } + }, + "node_modules/abitype": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.0.6.tgz", + "integrity": "sha512-MMSqYh4+C/aVqI2RQaWqbvI4Kxo5cQV40WQ4QFtDnNzCkqChm8MuENhElmynZlO0qUy/ObkEUaXtKqYnx1Kp3A==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3 >=3.22.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT", + "optional": true + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/axios": { + "version": "1.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", + "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "follow-redirects": "^1.16.2", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/axios-retry": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-4.5.0.tgz", + "integrity": "sha512-aR99oXhpEDGo0UuAlYcn2iGRds30k366Zfa05XWScR9QaQD4JYiP3/1Qt1u7YlefUOK+cn0CcwoL1oefavQUlQ==", + "deprecated": "axios-retry is no longer maintained. See https://github.com/softonic/axios-retry for alternatives.", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "is-retry-allowed": "^2.2.0" + }, + "peerDependencies": { + "axios": "0.x || 1.x" + } + }, + "node_modules/base-x": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz", + "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/big.js": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-6.2.2.tgz", + "integrity": "sha512-y/ie+Faknx7sZA5MfGA2xKlu0GDv8RWrXGsmlteyJQ2lvoKv9GBK/fpRMc2qlSoBAgNxrixICFCBefIq8WCQpQ==", + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/bigjs" + } + }, + "node_modules/blakejs": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/blakejs/-/blakejs-1.2.1.tgz", + "integrity": "sha512-QXUSXI3QVc/gJME0dBpXrag1kbzOqCjCX8/b54ntNyW6sjtoqxqRk3LTmXzaJoh71zMsDCjM+47jS7XiwN/+fQ==", + "license": "MIT" + }, + "node_modules/bs58": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", + "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", + "license": "MIT", + "dependencies": { + "base-x": "^5.0.0" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "optional": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/cookie-es": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-1.2.3.tgz", + "integrity": "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw==", + "license": "MIT" + }, + "node_modules/cross-fetch": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.2.0.tgz", + "integrity": "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.7.0" + } + }, + "node_modules/crossws": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/crossws/-/crossws-0.3.5.tgz", + "integrity": "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==", + "license": "MIT", + "dependencies": { + "uncrypto": "^0.1.3" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/dayjs": { + "version": "1.11.13", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", + "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "optional": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, + "node_modules/detect-browser": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/detect-browser/-/detect-browser-5.3.0.tgz", + "integrity": "sha512-53rsFbGdwMwlF7qvCt0ypLM5V5/Mbl0szB7GPN8y9NCcbknYOeVVXdrXEq+90IwAfrrzt6Hd+u2E2ntakICU8w==", + "license": "MIT" + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/encode-utf8": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/encode-utf8/-/encode-utf8-1.0.3.tgz", + "integrity": "sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw==", + "license": "MIT" + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-toolkit": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.44.0.tgz", + "integrity": "sha512-6penXeZalaV88MM3cGkFZZfOoLGWshWWfdy0tWw/RlVVyhvMaWSBTOvXNeiW3e5FwdS5ePW0LGEu17zT139ktg==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/esbuild": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.0", + "@esbuild/android-arm": "0.28.0", + "@esbuild/android-arm64": "0.28.0", + "@esbuild/android-x64": "0.28.0", + "@esbuild/darwin-arm64": "0.28.0", + "@esbuild/darwin-x64": "0.28.0", + "@esbuild/freebsd-arm64": "0.28.0", + "@esbuild/freebsd-x64": "0.28.0", + "@esbuild/linux-arm": "0.28.0", + "@esbuild/linux-arm64": "0.28.0", + "@esbuild/linux-ia32": "0.28.0", + "@esbuild/linux-loong64": "0.28.0", + "@esbuild/linux-mips64el": "0.28.0", + "@esbuild/linux-ppc64": "0.28.0", + "@esbuild/linux-riscv64": "0.28.0", + "@esbuild/linux-s390x": "0.28.0", + "@esbuild/linux-x64": "0.28.0", + "@esbuild/netbsd-arm64": "0.28.0", + "@esbuild/netbsd-x64": "0.28.0", + "@esbuild/openbsd-arm64": "0.28.0", + "@esbuild/openbsd-x64": "0.28.0", + "@esbuild/openharmony-arm64": "0.28.0", + "@esbuild/sunos-x64": "0.28.0", + "@esbuild/win32-arm64": "0.28.0", + "@esbuild/win32-ia32": "0.28.0", + "@esbuild/win32-x64": "0.28.0" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "optional": true, + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/h3": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.11.tgz", + "integrity": "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==", + "license": "MIT", + "dependencies": { + "cookie-es": "^1.2.3", + "crossws": "^0.3.5", + "defu": "^6.1.6", + "destr": "^2.0.5", + "iron-webcrypto": "^1.2.1", + "node-mock-http": "^1.0.4", + "radix3": "^1.1.2", + "ufo": "^1.6.3", + "uncrypto": "^0.1.3" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "optional": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/idb-keyval": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/idb-keyval/-/idb-keyval-6.2.1.tgz", + "integrity": "sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==", + "license": "Apache-2.0" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/iron-webcrypto": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz", + "integrity": "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/brc-dd" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "license": "MIT", + "optional": true + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-retry-allowed": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-2.2.0.tgz", + "integrity": "sha512-XVm7LOeLpTW4jV19QSH38vkswxoLud8sQ57YwJVTPWdiaI9I8keEhGFpBlslyVsgdQy4Opg8QOLb8YRgsyZiQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isows": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", + "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/jose": { + "version": "6.2.17", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", + "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/keyvaluestorage-interface": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/keyvaluestorage-interface/-/keyvaluestorage-interface-1.0.0.tgz", + "integrity": "sha512-8t6Q3TclQ4uZynJY9IGr2+SsIGwK9JHcO6ootkHCGA0CrQCRy+VkouYNO2xicET6b9al7QKzpebNow+gkpCL8g==", + "license": "MIT" + }, + "node_modules/lit": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.0.tgz", + "integrity": "sha512-DGVsqsOIHBww2DqnuZzW7QsuCdahp50ojuDaBPC7jUDRpYoH0z7kHBBYZewRzer75FwtrkmkKk7iOAwSaWdBmw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit/reactive-element": "^2.1.0", + "lit-element": "^4.2.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-element": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz", + "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0", + "@lit/reactive-element": "^2.1.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-html": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz", + "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==", + "license": "BSD-3-Clause", + "dependencies": { + "@types/trusted-types": "^2.0.2" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT", + "optional": true + }, + "node_modules/multiformats": { + "version": "9.9.0", + "resolved": "https://registry.npmjs.org/multiformats/-/multiformats-9.9.0.tgz", + "integrity": "sha512-HoMUjhH9T8DDBNT+6xzkrd9ga/XiBI4xLr58LJACwK6G3HTOPeMz4nB4KJs33L2BelrIJa7P0VuNaVF3hMYfjg==", + "license": "(Apache-2.0 AND MIT)" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "license": "MIT" + }, + "node_modules/node-mock-http": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.5.tgz", + "integrity": "sha512-KQyt/wLjG3TAc7DOUhpqWzgd4ERxR80JOlTK5VE5R1S12IaPVN5qkj4klBce9HPG1Njuup4Sb5bljaT34lIyjw==", + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ofetch": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/ofetch/-/ofetch-1.5.1.tgz", + "integrity": "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==", + "license": "MIT", + "dependencies": { + "destr": "^2.0.5", + "node-fetch-native": "^1.6.7", + "ufo": "^1.6.1" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ox": { + "version": "0.6.9", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.6.9.tgz", + "integrity": "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@adraffy/ens-normalize": "^1.10.1", + "@noble/curves": "^1.6.0", + "@noble/hashes": "^1.5.0", + "@scure/bip32": "^1.5.0", + "@scure/bip39": "^1.4.0", + "abitype": "^1.0.6", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/ox/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pino": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.0.0.tgz", + "integrity": "sha512-eI9pKwWEix40kfvSzqEP6ldqOoBIN7dwD/o91TY5z8vQI12sAffpR/pOqAD1IVVwIVHDpHjkq0joBPdJD0rafA==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "slow-redact": "^0.3.0", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/preact": { + "version": "10.24.2", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.2.tgz", + "integrity": "sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==", + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/process-warning": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", + "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/proxy-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/proxy-compare/-/proxy-compare-3.0.1.tgz", + "integrity": "sha512-V9plBAt3qjMlS1+nC8771KNf6oJ12gExvaxnNzN/9yVRLdTv/lc+oJlnSzrdYDAvBfTStPCoiaCOTmTs0adv7Q==", + "license": "MIT" + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/radix3": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.2.tgz", + "integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, + "node_modules/slow-redact": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/slow-redact/-/slow-redact-0.3.2.tgz", + "integrity": "sha512-MseHyi2+E/hBRqdOi5COy6wZ7j7DxXRz9NkseavNYSvvWC06D8a5cidVZX3tcG5eCW3NIyVU4zT63hw0Q486jw==", + "license": "MIT" + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/thread-stream": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz", + "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "license": "MIT" + }, + "node_modules/uint8arrays": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/uint8arrays/-/uint8arrays-3.1.1.tgz", + "integrity": "sha512-+QJa8QRnbdXVpHYjLoTpJIdCTiw9Ir62nocClWuXIq2JIh4Uta0cQsTSpFL678p2CN8B+XSApwcU+pQEqVpKWg==", + "license": "MIT", + "dependencies": { + "multiformats": "^9.4.2" + } + }, + "node_modules/uncrypto": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz", + "integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.12.4.tgz", + "integrity": "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ==", + "license": "MIT", + "optional": true + }, + "node_modules/unstorage": { + "version": "1.17.6", + "resolved": "https://registry.npmjs.org/unstorage/-/unstorage-1.17.6.tgz", + "integrity": "sha512-gjKtcmn/KwZuJZO9o2sc0esAQnhmTw0LviDHwevTXbJMYs0dRTp8ZEEWXHU0vTpzbN3cA0yxlTeyXssMp3zDqw==", + "license": "MIT", + "dependencies": { + "anymatch": "^3.1.3", + "chokidar": "^5.0.0", + "destr": "^2.0.5", + "h3": "^1.15.11", + "lru-cache": "^11.5.3", + "node-fetch-native": "^1.6.7", + "ofetch": "^1.5.1", + "ufo": "^1.6.4" + }, + "peerDependencies": { + "@azure/app-configuration": "^1.8.0", + "@azure/cosmos": "^4.2.0", + "@azure/data-tables": "^13.3.0", + "@azure/identity": "^4.6.0", + "@azure/keyvault-secrets": "^4.9.0", + "@azure/storage-blob": "^12.26.0", + "@capacitor/preferences": "^6 || ^7 || ^8", + "@deno/kv": ">=0.9.0", + "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0 || ^11.0.0", + "@planetscale/database": "^1.19.0", + "@upstash/redis": "^1.34.3", + "@vercel/blob": ">=0.27.1", + "@vercel/functions": "^2.2.12 || ^3.0.0", + "@vercel/kv": "^1 || ^2 || ^3", + "aws4fetch": "^1.0.20", + "db0": ">=0.2.1", + "idb-keyval": "^6.2.1", + "ioredis": "^5.4.2", + "uploadthing": "^7.4.4" + }, + "peerDependenciesMeta": { + "@azure/app-configuration": { + "optional": true + }, + "@azure/cosmos": { + "optional": true + }, + "@azure/data-tables": { + "optional": true + }, + "@azure/identity": { + "optional": true + }, + "@azure/keyvault-secrets": { + "optional": true + }, + "@azure/storage-blob": { + "optional": true + }, + "@capacitor/preferences": { + "optional": true + }, + "@deno/kv": { + "optional": true + }, + "@netlify/blobs": { + "optional": true + }, + "@planetscale/database": { + "optional": true + }, + "@upstash/redis": { + "optional": true + }, + "@vercel/blob": { + "optional": true + }, + "@vercel/functions": { + "optional": true + }, + "@vercel/kv": { + "optional": true + }, + "aws4fetch": { + "optional": true + }, + "db0": { + "optional": true + }, + "idb-keyval": { + "optional": true + }, + "ioredis": { + "optional": true + }, + "uploadthing": { + "optional": true + } + } + }, + "node_modules/valtio": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/valtio/-/valtio-2.1.7.tgz", + "integrity": "sha512-DwJhCDpujuQuKdJ2H84VbTjEJJteaSmqsuUltsfbfdbotVfNeTE4K/qc/Wi57I9x8/2ed4JNdjEna7O6PfavRg==", + "license": "MIT", + "dependencies": { + "proxy-compare": "^3.0.1" + }, + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "react": ">=18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/viem": { + "version": "2.57.19", + "resolved": "https://registry.npmjs.org/viem/-/viem-2.57.19.tgz", + "integrity": "sha512-ULAHSwef42oL1reV41Os40iR34PF9BFNIX/RBapHLAJL1X6VmrgQikS4q4ulZ7/8GqlFLqrRI5GoNms3hcxsHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@noble/curves": "1.9.1", + "@noble/hashes": "1.8.0", + "@scure/bip32": "1.7.0", + "@scure/bip39": "1.6.0", + "abitype": "1.2.3", + "isows": "1.0.7", + "ox": "0.14.65", + "ws": "8.21.0" + }, + "peerDependencies": { + "mppx": ">=0.17.0", + "typescript": ">=5.0.4" + }, + "peerDependenciesMeta": { + "mppx": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/viem/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/viem/node_modules/abitype": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz", + "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/ox": { + "version": "0.14.65", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.65.tgz", + "integrity": "sha512-K7oj+jvEP4Gf78ZOYuWAWzKEX/g5z7p6ukj84gdbFnezmFSt6SpprEp9tH5tymXsywSqRdeqk+8JL4+9o0Schw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.2.3", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zustand": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.3.tgz", + "integrity": "sha512-14fwWQtU3pH4dE0dOpdMiWjddcH+QzKIgk1cl8epwSE7yag43k/AD/m4L6+K7DytAOr9gGBe3/EXj9g7cdostg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + } + } +} diff --git a/capsules/wallet-walletconnect/vendor/reown-appkit.js b/capsules/wallet-walletconnect/vendor/reown-appkit.js new file mode 100644 index 000000000..952929045 --- /dev/null +++ b/capsules/wallet-walletconnect/vendor/reown-appkit.js @@ -0,0 +1,6327 @@ +var PCe=Object.create;var nA=Object.defineProperty;var NCe=Object.getOwnPropertyDescriptor;var RCe=Object.getOwnPropertyNames;var OCe=Object.getPrototypeOf,BCe=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Te=(e,t)=>{for(var r in t)nA(e,r,{get:t[r],enumerable:!0})},rA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of RCe(t))!BCe.call(e,o)&&o!==r&&nA(e,o,{get:()=>t[o],enumerable:!(n=NCe(t,o))||n.enumerable});return e},Bo=(e,t,r)=>(rA(e,t,"default"),r&&rA(r,t,"default")),Ht=(e,t,r)=>(r=e!=null?PCe(OCe(e)):{},rA(t||!e||!e.__esModule?nA(r,"default",{value:e,enumerable:!0}):r,e)),Yx=e=>rA(nA({},"__esModule",{value:!0}),e);function g(e){zN=e}var zN,m,l=b(()=>{m=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;readyState=0;bufferedAmount=0;protocol="";extensions="";constructor(t){if(super(),!zN)throw new Error("WalletConnect Runtime transport is unavailable.");let r=zN;this.url="Runtime WalletConnect relay";let n=r.WebSocket||globalThis.WebSocket,o=this.socket=new n(r.url);o.onopen=async()=>{try{let s=r.authorize?(await r.authorize()).token:r.token;this.readyState===0&&o.send(JSON.stringify({token:s,relay:t}))}catch{this.close()}},o.onmessage=s=>{if(this.readyState===0){if(s.data!=='{"ready":true}'){this.close();return}this.readyState=1,this.emit("open",new Event("open"))}else this.emit("message",new MessageEvent("message",{data:s.data}))},o.onerror=()=>this.emit("error",new Event("error")),o.onclose=()=>{this.readyState=3,this.emit("close",new Event("close"))}}emit(t,r){this[`on${t}`]?.(r),this.dispatchEvent(r)}send(t){if(this.readyState!==1)throw new Error("WalletConnect connection is closed.");this.socket.send(t)}close(){this.readyState=2,this.socket.close()}}});var ks=_e((ent,VN)=>{"use strict";l();var y2=typeof Reflect=="object"?Reflect:null,uW=y2&&typeof y2.apply=="function"?y2.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},oA;y2&&typeof y2.ownKeys=="function"?oA=y2.ownKeys:Object.getOwnPropertySymbols?oA=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:oA=function(t){return Object.getOwnPropertyNames(t)};function kCe(e){console&&console.warn&&console.warn(e)}var fW=Number.isNaN||function(t){return t!==t};function Ar(){Ar.init.call(this)}VN.exports=Ar;VN.exports.once=MCe;Ar.EventEmitter=Ar;Ar.prototype._events=void 0;Ar.prototype._eventsCount=0;Ar.prototype._maxListeners=void 0;var dW=10;function sA(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(Ar,"defaultMaxListeners",{enumerable:!0,get:function(){return dW},set:function(e){if(typeof e!="number"||e<0||fW(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");dW=e}});Ar.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Ar.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||fW(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function pW(e){return e._maxListeners===void 0?Ar.defaultMaxListeners:e._maxListeners}Ar.prototype.getMaxListeners=function(){return pW(this)};Ar.prototype.emit=function(t){for(var r=[],n=1;n0&&(i=r[0]),i instanceof Error)throw i;var a=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw a.context=i,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")uW(c,this,r);else for(var u=c.length,d=wW(c,u),n=0;n0&&i.length>o&&!i.warned){i.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=i.length,kCe(a)}return e}Ar.prototype.addListener=function(t,r){return hW(this,t,r,!1)};Ar.prototype.on=Ar.prototype.addListener;Ar.prototype.prependListener=function(t,r){return hW(this,t,r,!0)};function UCe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function mW(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=UCe.bind(n);return o.listener=r,n.wrapFn=o,o}Ar.prototype.once=function(t,r){return sA(r),this.on(t,mW(this,t,r)),this};Ar.prototype.prependOnceListener=function(t,r){return sA(r),this.prependListener(t,mW(this,t,r)),this};Ar.prototype.removeListener=function(t,r){var n,o,s,i,a;if(sA(r),o=this._events,o===void 0)return this;if(n=o[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(s=-1,i=n.length-1;i>=0;i--)if(n[i]===r||n[i].listener===r){a=n[i].listener,s=i;break}if(s<0)return this;s===0?n.shift():DCe(n,s),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,a||r)}return this};Ar.prototype.off=Ar.prototype.removeListener;Ar.prototype.removeAllListeners=function(t){var r,n,o;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),i;for(o=0;o=0;o--)this.removeListener(t,r[o]);return this};function gW(e,t,r){var n=e._events;if(n===void 0)return[];var o=n[t];return o===void 0?[]:typeof o=="function"?r?[o.listener||o]:[o]:r?LCe(o):wW(o,o.length)}Ar.prototype.listeners=function(t){return gW(this,t,!0)};Ar.prototype.rawListeners=function(t){return gW(this,t,!1)};Ar.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):yW.call(e,t)};Ar.prototype.listenerCount=yW;function yW(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ar.prototype.eventNames=function(){return this._eventsCount>0?oA(this._events):[]};function wW(e,t){for(var r=new Array(t),n=0;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new jCe:typeof navigator<"u"?AW(navigator.userAgent):YCe()}function ZCe(e){return e!==""&&KCe.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var s=o.exec(e);return!!s&&[n,s]},!1)}function AW(e){var t=ZCe(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new VCe;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length{l();xW=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;nWN,__asyncDelegator:()=>uSe,__asyncGenerator:()=>lSe,__asyncValues:()=>dSe,__await:()=>Jx,__awaiter:()=>nSe,__classPrivateFieldGet:()=>mSe,__classPrivateFieldSet:()=>gSe,__createBinding:()=>sSe,__decorate:()=>eSe,__exportStar:()=>iSe,__extends:()=>QCe,__generator:()=>oSe,__importDefault:()=>hSe,__importStar:()=>pSe,__makeTemplateObject:()=>fSe,__metadata:()=>rSe,__param:()=>tSe,__read:()=>CW,__rest:()=>XCe,__spread:()=>aSe,__spreadArrays:()=>cSe,__values:()=>KN});function QCe(e,t){qN(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function XCe(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(e);o=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s}function tSe(e,t){return function(r,n){t(r,n,e)}}function rSe(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function nSe(e,t,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(d){try{u(n.next(d))}catch(f){i(f)}}function c(d){try{u(n.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(a,c)}u((n=n.apply(e,t||[])).next())})}function oSe(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(d){return c([u,d])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function CW(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function aSe(){for(var e=[],t=0;t1||a(p,h)})})}function a(p,h){try{c(n[p](h))}catch(y){f(s[0][3],y)}}function c(p){p.value instanceof Jx?Promise.resolve(p.value.v).then(u,d):f(s[0][2],p)}function u(p){a("next",p)}function d(p){a("throw",p)}function f(p,h){p(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function uSe(e){var t,r;return t={},n("next"),n("throw",function(o){throw o}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(o,s){t[o]=e[o]?function(i){return(r=!r)?{value:Jx(e[o](i)),done:o==="return"}:s?s(i):i}:s}}function dSe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof KN=="function"?KN(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=e[s]&&function(i){return new Promise(function(a,c){i=e[s](i),o(a,c,i.done,i.value)})}}function o(s,i,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},i)}}function fSe(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function pSe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function hSe(e){return e&&e.__esModule?e:{default:e}}function mSe(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function gSe(e,t,r){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,r),r}var qN,WN,b2=b(()=>{l();qN=function(e,t){return qN=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},qN(e,t)};WN=function(){return WN=Object.assign||function(t){for(var r,n=1,o=arguments.length;n{"use strict";l();Object.defineProperty(aA,"__esModule",{value:!0});aA.delay=void 0;function ySe(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}aA.delay=ySe});var IW=_e(x2=>{"use strict";l();Object.defineProperty(x2,"__esModule",{value:!0});x2.ONE_THOUSAND=x2.ONE_HUNDRED=void 0;x2.ONE_HUNDRED=100;x2.ONE_THOUSAND=1e3});var TW=_e(Ue=>{"use strict";l();Object.defineProperty(Ue,"__esModule",{value:!0});Ue.ONE_YEAR=Ue.FOUR_WEEKS=Ue.THREE_WEEKS=Ue.TWO_WEEKS=Ue.ONE_WEEK=Ue.THIRTY_DAYS=Ue.SEVEN_DAYS=Ue.FIVE_DAYS=Ue.THREE_DAYS=Ue.ONE_DAY=Ue.TWENTY_FOUR_HOURS=Ue.TWELVE_HOURS=Ue.SIX_HOURS=Ue.THREE_HOURS=Ue.ONE_HOUR=Ue.SIXTY_MINUTES=Ue.THIRTY_MINUTES=Ue.TEN_MINUTES=Ue.FIVE_MINUTES=Ue.ONE_MINUTE=Ue.SIXTY_SECONDS=Ue.THIRTY_SECONDS=Ue.TEN_SECONDS=Ue.FIVE_SECONDS=Ue.ONE_SECOND=void 0;Ue.ONE_SECOND=1;Ue.FIVE_SECONDS=5;Ue.TEN_SECONDS=10;Ue.THIRTY_SECONDS=30;Ue.SIXTY_SECONDS=60;Ue.ONE_MINUTE=Ue.SIXTY_SECONDS;Ue.FIVE_MINUTES=Ue.ONE_MINUTE*5;Ue.TEN_MINUTES=Ue.ONE_MINUTE*10;Ue.THIRTY_MINUTES=Ue.ONE_MINUTE*30;Ue.SIXTY_MINUTES=Ue.ONE_MINUTE*60;Ue.ONE_HOUR=Ue.SIXTY_MINUTES;Ue.THREE_HOURS=Ue.ONE_HOUR*3;Ue.SIX_HOURS=Ue.ONE_HOUR*6;Ue.TWELVE_HOURS=Ue.ONE_HOUR*12;Ue.TWENTY_FOUR_HOURS=Ue.ONE_HOUR*24;Ue.ONE_DAY=Ue.TWENTY_FOUR_HOURS;Ue.THREE_DAYS=Ue.ONE_DAY*3;Ue.FIVE_DAYS=Ue.ONE_DAY*5;Ue.SEVEN_DAYS=Ue.ONE_DAY*7;Ue.THIRTY_DAYS=Ue.ONE_DAY*30;Ue.ONE_WEEK=Ue.SEVEN_DAYS;Ue.TWO_WEEKS=Ue.ONE_WEEK*2;Ue.THREE_WEEKS=Ue.ONE_WEEK*3;Ue.FOUR_WEEKS=Ue.ONE_WEEK*4;Ue.ONE_YEAR=Ue.ONE_DAY*365});var ZN=_e(cA=>{"use strict";l();Object.defineProperty(cA,"__esModule",{value:!0});var _W=(b2(),Yx(w2));_W.__exportStar(IW(),cA);_W.__exportStar(TW(),cA)});var NW=_e(v2=>{"use strict";l();Object.defineProperty(v2,"__esModule",{value:!0});v2.fromMiliseconds=v2.toMiliseconds=void 0;var PW=ZN();function wSe(e){return e*PW.ONE_THOUSAND}v2.toMiliseconds=wSe;function bSe(e){return Math.floor(e/PW.ONE_THOUSAND)}v2.fromMiliseconds=bSe});var OW=_e(lA=>{"use strict";l();Object.defineProperty(lA,"__esModule",{value:!0});var RW=(b2(),Yx(w2));RW.__exportStar(SW(),lA);RW.__exportStar(NW(),lA)});var BW=_e(Qx=>{"use strict";l();Object.defineProperty(Qx,"__esModule",{value:!0});Qx.Watch=void 0;var uA=class{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){let r=this.get(t);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);let n=Date.now()-r.started;this.timestamps.set(t,{started:r.started,elapsed:n})}get(t){let r=this.timestamps.get(t);if(typeof r>"u")throw new Error(`No timestamp found for label: ${t}`);return r}elapsed(t){let r=this.get(t);return r.elapsed||Date.now()-r.started}};Qx.Watch=uA;Qx.default=uA});var kW=_e(dA=>{"use strict";l();Object.defineProperty(dA,"__esModule",{value:!0});dA.IWatch=void 0;var GN=class{};dA.IWatch=GN});var UW=_e(YN=>{"use strict";l();Object.defineProperty(YN,"__esModule",{value:!0});var xSe=(b2(),Yx(w2));xSe.__exportStar(kW(),YN)});var jd=_e(E2=>{"use strict";l();Object.defineProperty(E2,"__esModule",{value:!0});var fA=(b2(),Yx(w2));fA.__exportStar(OW(),E2);fA.__exportStar(BW(),E2);fA.__exportStar(UW(),E2);fA.__exportStar(ZN(),E2)});var C2=_e(Ur=>{"use strict";l();Object.defineProperty(Ur,"__esModule",{value:!0});Ur.getLocalStorage=Ur.getLocalStorageOrThrow=Ur.getCrypto=Ur.getCryptoOrThrow=Ur.getLocation=Ur.getLocationOrThrow=Ur.getNavigator=Ur.getNavigatorOrThrow=Ur.getDocument=Ur.getDocumentOrThrow=Ur.getFromWindowOrThrow=Ur.getFromWindow=void 0;function l1(e){let t;return typeof window<"u"&&typeof window[e]<"u"&&(t=window[e]),t}Ur.getFromWindow=l1;function A2(e){let t=l1(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Ur.getFromWindowOrThrow=A2;function vSe(){return A2("document")}Ur.getDocumentOrThrow=vSe;function ESe(){return l1("document")}Ur.getDocument=ESe;function ASe(){return A2("navigator")}Ur.getNavigatorOrThrow=ASe;function CSe(){return l1("navigator")}Ur.getNavigator=CSe;function SSe(){return A2("location")}Ur.getLocationOrThrow=SSe;function ISe(){return l1("location")}Ur.getLocation=ISe;function TSe(){return A2("crypto")}Ur.getCryptoOrThrow=TSe;function _Se(){return l1("crypto")}Ur.getCrypto=_Se;function PSe(){return A2("localStorage")}Ur.getLocalStorageOrThrow=PSe;function NSe(){return l1("localStorage")}Ur.getLocalStorage=NSe});var JN=_e(pA=>{"use strict";l();Object.defineProperty(pA,"__esModule",{value:!0});pA.getWindowMetadata=void 0;var DW=C2();function RSe(){let e,t;try{e=DW.getDocumentOrThrow(),t=DW.getLocationOrThrow()}catch{return null}function r(){let f=e.getElementsByTagName("link"),p=[];for(let h=0;h-1){let x=y.getAttribute("href");if(x)if(x.toLowerCase().indexOf("https:")===-1&&x.toLowerCase().indexOf("http:")===-1&&x.indexOf("//")!==0){let v=t.protocol+"//"+t.host;if(x.indexOf("/")===0)v+=x;else{let T=t.pathname.split("/");T.pop();let E=T.join("/");v+=E+"/"+x}p.push(v)}else if(x.indexOf("//")===0){let v=t.protocol+x;p.push(v)}else p.push(x)}}return p}function n(...f){let p=e.getElementsByTagName("meta");for(let h=0;hy.getAttribute(x)).filter(x=>x?f.includes(x):!1);if(w.length&&w){let x=y.getAttribute("content");if(x)return x}}return""}function o(){let f=n("name","og:site_name","og:title","twitter:title");return f||(f=e.title),f}function s(){return n("description","og:description","twitter:description","keywords")}let i=o(),a=s(),c=t.origin,u=r();return{description:a,url:c,icons:u,name:i}}pA.getWindowMetadata=RSe});var UIe,DIe,LIe,MIe,uZ,dZ,fZ,HIe,$Ie,Qit,Xit,eat,tat,pZ=b(()=>{l();UIe=44032,DIe=4352,LIe=4449,MIe=4519,uZ=19,dZ=21,fZ=28,HIe=dZ*fZ,$Ie=uZ*HIe,Qit=UIe+$Ie,Xit=DIe+uZ,eat=LIe+dZ,tat=MIe+fZ});function gZ(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function yZ(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(r=>typeof r=="string"):t.every(r=>Number.isSafeInteger(r)):!1}function VA(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function p8(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function jA(e){if(!Array.isArray(e))throw new Error("array expected")}function qA(e,t){if(!yZ(!0,t))throw new Error(`${e}: array of strings expected`)}function wZ(e,t){if(!yZ(!1,t))throw new Error(`${e}: array of numbers expected`)}function bZ(...e){let t=s=>s,r=(s,i)=>a=>s(i(a)),n=e.map(s=>s.encode).reduceRight(r,t),o=e.map(s=>s.decode).reduce(r,t);return{encode:n,decode:o}}function xZ(e){let t=typeof e=="string"?e.split(""):e,r=t.length;qA("alphabet",t);let n=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(jA(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:o=>(jA(o),o.map(s=>{VA("alphabet.decode",s);let i=n.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function vZ(e=""){return VA("join",e),{encode:t=>(qA("join.decode",t),t.join(e)),decode:t=>(VA("join.decode",t),t.split(e))}}function FIe(e,t="="){return p8(e),VA("padding",t),{encode(r){for(qA("padding.encode",r);r.length*e%8;)r.push(t);return r},decode(r){qA("padding.decode",r);let n=r.length;if(n*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if((n-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}function hZ(e,t,r){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(jA(e),!e.length)return[];let n=0,o=[],s=Array.from(e,a=>{if(p8(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),i=s.length;for(;;){let a=0,c=!0;for(let u=n;u32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(WA(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${WA(t,r)}`);let o=0,s=0,i=YR[t],a=YR[r]-1,c=[];for(let u of e){if(p8(u),u>=i)throw new Error(`convertRadix2: invalid data word=${u} from=${t}`);if(o=o<32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=r;s-=r)c.push((o>>s-r&a)>>>0);let d=YR[s];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<=t)throw new Error("Excess padding");if(!n&&o>0)throw new Error(`Non-zero padding: ${o}`);return n&&s>0&&c.push(o>>>0),c}function zIe(e){p8(e);let t=2**8;return{encode:r=>{if(!gZ(r))throw new Error("radix.encode input should be Uint8Array");return hZ(Array.from(r),t,e)},decode:r=>(wZ("radix.decode",r),Uint8Array.from(hZ(r,e,t)))}}function VIe(e,t=!1){if(p8(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(WA(8,e)>32||WA(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!gZ(r))throw new Error("radix2.encode input should be Uint8Array");return mZ(Array.from(r),8,e,!t)},decode:r=>(wZ("radix2.decode",r),Uint8Array.from(mZ(r,e,8,t)))}}var EZ,WA,YR,KA,jIe,B2,JR=b(()=>{l();EZ=(e,t)=>t===0?e:EZ(t,e%t),WA=(e,t)=>e+(t-EZ(e,t)),YR=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();KA=bZ(VIe(5),xZ("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),FIe(5),vZ("")),jIe=e=>bZ(zIe(58),xZ(e),vZ("")),B2=jIe("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")});function PZ(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function GA(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function YA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function rs(e,...t){if(!PZ(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function QR(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function NZ(e,t){rs(e);let r=t.outputLen;if(e.length>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function BZ(e,t,r){GA(r);let n=new Uint8Array(16),o=JIe(n);return _Z(o,0,BigInt(t),r),_Z(o,8,BigInt(e),r),n}function e9e(e){return e.byteOffset%4===0}function QA(e){return Uint8Array.from(e)}var QIe,XR,XA=b(()=>{l();QIe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;XR=(e,t)=>{function r(n,...o){if(rs(n),!QIe)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let d=o[0];if(!d)throw new Error("nonce / iv required");e.varSizeNonce?rs(d):rs(d,e.nonceLength)}let s=e.tagLength;s&&o[1]!==void 0&&rs(o[1]);let i=t(n,...o),a=(d,f)=>{if(f!==void 0){if(d!==2)throw new Error("cipher output not supported");rs(f)}},c=!1;return{encrypt(d,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,rs(d),a(i.encrypt.length,f),i.encrypt(d,f)},decrypt(d,f){if(rs(d),s&&d.length{l();LZ=Ht(DZ(),1)});var KZ=b(()=>{l()});function I1(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}var b8=b(()=>{l()});function x8(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?I1(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}var aC=b(()=>{l();b8()});function Ms(e,t){t||(t=e.reduce((o,s)=>o+s.length,0));let r=x8(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return I1(r)}var ZZ=b(()=>{l();aC();b8()});var GZ=b(()=>{l()});function T9e(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}var _9e,P9e,YZ,JZ=b(()=>{l();_9e=T9e,P9e=_9e,YZ=P9e});var Rlt,QZ,rf,XZ,eG,rh=b(()=>{l();Rlt=new Uint8Array(0),QZ=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},XZ=e=>new TextEncoder().encode(e),eG=e=>new TextDecoder().decode(e)});var cO,lO,uO,rG,dO,U2,nh,N9e,R9e,mn,Bc=b(()=>{l();JZ();rh();cO=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},lO=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return rG(this,t)}},uO=class{constructor(t){this.decoders=t}or(t){return rG(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},rG=(e,t)=>new uO({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),dO=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new cO(t,r,n),this.decoder=new lO(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},U2=({name:e,prefix:t,encode:r,decode:n})=>new dO(e,t,r,n),nh=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=YZ(r,t);return U2({prefix:e,name:t,encode:n,decode:s=>rf(o(s))})},N9e=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},R9e=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<U2({prefix:t,name:e,encode(o){return R9e(o,n,r)},decode(o){return N9e(o,n,r,e)}})});var fO={};Te(fO,{identity:()=>O9e});var O9e,nG=b(()=>{l();Bc();rh();O9e=U2({prefix:"\0",name:"identity",encode:e=>eG(e),decode:e=>XZ(e)})});var pO={};Te(pO,{base2:()=>B9e});var B9e,oG=b(()=>{l();Bc();B9e=mn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var hO={};Te(hO,{base8:()=>k9e});var k9e,sG=b(()=>{l();Bc();k9e=mn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var mO={};Te(mO,{base10:()=>U9e});var U9e,iG=b(()=>{l();Bc();U9e=nh({prefix:"9",name:"base10",alphabet:"0123456789"})});var gO={};Te(gO,{base16:()=>D9e,base16upper:()=>L9e});var D9e,L9e,aG=b(()=>{l();Bc();D9e=mn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L9e=mn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var yO={};Te(yO,{base32:()=>D2,base32hex:()=>F9e,base32hexpad:()=>V9e,base32hexpadupper:()=>j9e,base32hexupper:()=>z9e,base32pad:()=>H9e,base32padupper:()=>$9e,base32upper:()=>M9e,base32z:()=>q9e});var D2,M9e,H9e,$9e,F9e,z9e,V9e,j9e,q9e,wO=b(()=>{l();Bc();D2=mn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),M9e=mn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),H9e=mn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$9e=mn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),F9e=mn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z9e=mn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),V9e=mn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),j9e=mn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),q9e=mn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bO={};Te(bO,{base36:()=>W9e,base36upper:()=>K9e});var W9e,K9e,cG=b(()=>{l();Bc();W9e=nh({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),K9e=nh({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var xO={};Te(xO,{base58btc:()=>Dl,base58flickr:()=>Z9e});var Dl,Z9e,vO=b(()=>{l();Bc();Dl=nh({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Z9e=nh({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var EO={};Te(EO,{base64:()=>G9e,base64pad:()=>Y9e,base64url:()=>J9e,base64urlpad:()=>Q9e});var G9e,Y9e,J9e,Q9e,lG=b(()=>{l();Bc();G9e=mn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Y9e=mn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J9e=mn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Q9e=mn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var AO={};Te(AO,{base256emoji:()=>nTe});function tTe(e){return e.reduce((t,r)=>(t+=X9e[r],t),"")}function rTe(e){let t=[];for(let r of e){let n=eTe[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}var uG,X9e,eTe,nTe,dG=b(()=>{l();Bc();uG=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),X9e=uG.reduce((e,t,r)=>(e[r]=t,e),[]),eTe=uG.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);nTe=U2({prefix:"\u{1F680}",name:"base256emoji",encode:tTe,decode:rTe})});function hG(e,t,r){t=t||[],r=r||0;for(var n=r;e>=aTe;)t[r++]=e&255|fG,e/=128;for(;e&iTe;)t[r++]=e&255|fG,e>>>=7;return t[r]=e|0,hG.bytes=r-n+1,t}function CO(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw CO.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&pG)<=lTe);return CO.bytes=s-n,r}var oTe,fG,sTe,iTe,aTe,cTe,lTe,pG,uTe,dTe,fTe,pTe,hTe,mTe,gTe,yTe,wTe,bTe,xTe,vTe,v8,mG=b(()=>{l();oTe=hG,fG=128,sTe=127,iTe=~sTe,aTe=Math.pow(2,31);cTe=CO,lTe=128,pG=127;uTe=Math.pow(2,7),dTe=Math.pow(2,14),fTe=Math.pow(2,21),pTe=Math.pow(2,28),hTe=Math.pow(2,35),mTe=Math.pow(2,42),gTe=Math.pow(2,49),yTe=Math.pow(2,56),wTe=Math.pow(2,63),bTe=function(e){return e{l();mG();E8=(e,t=0)=>[v8.decode(e,t),v8.decode.bytes],L2=(e,t,r=0)=>(v8.encode(e,t,r),t),M2=e=>v8.encodingLength(e)});var T1,gG,yG,H2,C8=b(()=>{l();rh();lC();T1=(e,t)=>{let r=t.byteLength,n=M2(e),o=n+M2(r),s=new Uint8Array(o+r);return L2(e,s,0),L2(r,s,n),s.set(t,o),new H2(e,r,t,s)},gG=e=>{let t=rf(e),[r,n]=E8(t),[o,s]=E8(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new H2(r,o,i,t)},yG=(e,t)=>e===t?!0:e.code===t.code&&e.size===t.size&&QZ(e.bytes,t.bytes),H2=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}});var IO,SO,TO=b(()=>{l();C8();IO=({name:e,code:t,encode:r})=>new SO(e,t,r),SO=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?T1(this.code,r):r.then(n=>T1(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var _O={};Te(_O,{sha256:()=>ETe,sha512:()=>ATe});var bG,ETe,ATe,xG=b(()=>{l();TO();bG=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),ETe=IO({name:"sha2-256",code:18,encode:bG("SHA-256")}),ATe=IO({name:"sha2-512",code:19,encode:bG("SHA-512")})});var PO={};Te(PO,{identity:()=>ITe});var vG,CTe,EG,STe,ITe,AG=b(()=>{l();rh();C8();vG=0,CTe="identity",EG=rf,STe=e=>T1(vG,EG(e)),ITe={code:vG,name:CTe,encode:EG,digest:STe}});var CG=b(()=>{l();rh()});var yut,wut,SG=b(()=>{l();yut=new TextEncoder,wut=new TextDecoder});var fC,PTe,NTe,RTe,S8,OTe,IG,TG,uC,dC,BTe,kTe,UTe,_G=b(()=>{l();lC();C8();vO();wO();rh();fC=class e{constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this.byteOffset=o.byteOffset,this.byteLength=o.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:dC,byteLength:dC,code:uC,version:uC,multihash:uC,bytes:uC,_baseCache:dC,asCID:dC})}toV0(){switch(this.version){case 0:return this;default:{let{code:t,multihash:r}=this;if(t!==S8)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==OTe)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=T1(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(t){return t&&this.code===t.code&&this.version===t.version&&yG(this.multihash,t.multihash)}toString(t){let{bytes:r,version:n,_baseCache:o}=this;return n===0?NTe(r,o,t||Dl.encoder):RTe(r,o,t||D2.encoder)}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(t){return kTe(/^0\.0/,UTe),!!(t&&(t[TG]||t.asCID===t))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(t){if(t instanceof e)return t;if(t!=null&&t.asCID===t){let{version:r,code:n,multihash:o,bytes:s}=t;return new e(r,n,o,s||IG(r,n,o.bytes))}else if(t!=null&&t[TG]===!0){let{version:r,multihash:n,code:o}=t,s=gG(n);return e.create(r,o,s)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(t){case 0:{if(r!==S8)throw new Error(`Version 0 CID must use dag-pb (code: ${S8}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=IG(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,S8,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=rf(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new H2(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[f,p]=E8(t.subarray(r));return r+=p,f},o=n(),s=S8;if(o===18?(o=0,r=0):o===1&&(s=n()),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,d=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:u}}static parse(t,r){let[n,o]=PTe(t,r),s=e.decode(o);return s._baseCache.set(n,t),s}},PTe=(e,t)=>{switch(e[0]){case"Q":{let r=t||Dl;return[Dl.prefix,r.decode(`${Dl.prefix}${e}`)]}case Dl.prefix:{let r=t||Dl;return[Dl.prefix,r.decode(e)]}case D2.prefix:{let r=t||D2;return[D2.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},NTe=(e,t,r)=>{let{prefix:n}=r;if(n!==Dl.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o},RTe=(e,t,r)=>{let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o},S8=112,OTe=18,IG=(e,t,r)=>{let n=M2(e),o=n+M2(t),s=new Uint8Array(o+r.byteLength);return L2(e,s,0),L2(t,s,n),s.set(r,o),s},TG=Symbol.for("@ipld/js-cid/CID"),uC={writable:!1,configurable:!1,enumerable:!0},dC={writable:!1,enumerable:!1,configurable:!1},BTe="0.0.0-dev",kTe=(e,t)=>{if(e.test(BTe))console.warn(t);else throw new Error(t)},UTe=`CID.isCID(v) is deprecated and will be removed in the next major release. +Following code pattern: + +if (CID.isCID(value)) { + doSomethingWithCID(value) +} + +Is replaced with: + +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) +} +`});var PG=b(()=>{l();_G();lC();rh();TO();C8()});var NO,Put,NG=b(()=>{l();nG();oG();sG();iG();aG();wO();cG();vO();lG();dG();xG();AG();CG();SG();PG();NO={...fO,...pO,...hO,...mO,...gO,...yO,...bO,...xO,...EO,...AO},Put={..._O,...PO}});function OG(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var RG,RO,DTe,pC,OO=b(()=>{l();NG();aC();RG=OG("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),RO=OG("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=x8(e.length);for(let r=0;r{l();OO();b8()});function Ut(e,t="utf8"){let r=pC[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var BG=b(()=>{l();OO()});var kG=b(()=>{l();aC();b8()});var I8=b(()=>{l();KZ();ZZ();GZ();BO();BG();kG()});function Fs(e){if(typeof e!="string")throw new Error(`Cannot safe json parse value of type ${typeof e}`);try{return L_e(e)}catch{return e}}function yi(e){return typeof e=="string"?e:D_e(e)||""}var D_e,L_e,R1=b(()=>{l();D_e=e=>JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString()+"n":r),L_e=e=>{let t=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=e.replace(t,'$1"$2n"$3');return JSON.parse(r,(n,o)=>typeof o=="string"&&o.match(/^\d+n$/)?BigInt(o.substring(0,o.length-1)):o)}});function M_e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ZY(e,...t){if(!M_e(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function PY(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function H_e(e,t){ZY(e);let r=t.outputLen;if(e.lengthe().update(GY(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function YY(e=32){if(G2&&typeof G2.getRandomValues=="function")return G2.getRandomValues(new Uint8Array(e));if(G2&&typeof G2.randomBytes=="function")return G2.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function z_e(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function JY(e,t=!1){return t?{h:Number(e&CC),l:Number(e>>hB&CC)}:{h:Number(e>>hB&CC)|0,l:Number(e&CC)|0}}function V_e(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;o>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}function TB(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function _B(e){if(!TB(e))throw new Error("Uint8Array expected")}function sB(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function PB(e){_B(e);let t="";for(let r=0;r=ff._0&&e<=ff._9)return e-ff._0;if(e>=ff.A&&e<=ff.F)return e-(ff.A-10);if(e>=ff.a&&e<=ff.f)return e-(ff.a-10)}function eJ(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oIB;e>>=QY,t+=1);return t}function NB(e,t,r={}){let n=(o,s,i)=>{let a=b7e[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function OY(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}function eo(e,t){let r=e%t;return r>=go?r:t+r}function v7e(e,t,r){if(tgo;)t&Sn&&(n=n*e%r),e=e*e%r,t>>=Sn;return n}function Ml(e,t,r){let n=e;for(;t-- >go;)n*=n,n%=r;return n}function UY(e,t){if(e===go)throw new Error("invert: expected non-zero number");if(t<=go)throw new Error("invert: expected positive modulus, got "+t);let r=eo(e,t),n=t,o=go,s=Sn;for(;r!==go;){let i=n/r,a=n%r,c=o-s*i;n=r,r=a,o=s,s=c}if(n!==Sn)throw new Error("invert: does not exist");return eo(o,t)}function E7e(e){let t=(e-Sn)/O1,r,n,o;for(r=e-Sn,n=0;r%O1===go;r/=O1,n++);for(o=O1;o1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(e+Sn)/yB;return function(a,c){let u=a.pow(c,i);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}let s=(r+Sn)/O1;return function(i,a){if(i.pow(a,t)===i.neg(i.ONE))throw new Error("Cannot find square root");let c=n,u=i.pow(i.mul(i.ONE,o),r),d=i.pow(a,s),f=i.pow(a,r);for(;!i.eql(f,i.ONE);){if(i.eql(f,i.ZERO))return i.ZERO;let p=1;for(let y=i.sqr(f);p(n[o]="function",n),t);return NB(e,r)}function T7e(e,t,r){if(rgo;)r&Sn&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Sn;return n}function _7e(e,t){let r=new Array(t.length),n=t.reduce((s,i,a)=>e.is0(i)?s:(r[a]=s,e.mul(s,i)),e.ONE),o=e.inv(n);return t.reduceRight((s,i,a)=>e.is0(i)?s:(r[a]=e.mul(s,r[a]),e.mul(s,i)),o),r}function rJ(e,t){let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function nJ(e,t,r=!1,n={}){if(e<=go)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=rJ(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:w7e(o),ZERO:go,ONE:Sn,create:c=>eo(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return go<=c&&cc===go,isOdd:c=>(c&Sn)===Sn,neg:c=>eo(-c,e),eql:(c,u)=>c===u,sqr:c=>eo(c*c,e),add:(c,u)=>eo(c+u,e),sub:(c,u)=>eo(c-u,e),mul:(c,u)=>eo(c*u,e),pow:(c,u)=>T7e(a,c,u),div:(c,u)=>eo(c*UY(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>UY(c,e),sqrt:n.sqrt||(c=>(i||(i=A7e(e)),i(a,c))),invertBatch:c=>_7e(a,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?gB(c,s):tJ(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?TC(c):m7e(c)}});return Object.freeze(a)}function aB(e,t){let r=t.negate();return e?r:t}function oJ(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function cB(e,t){oJ(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1);return{windows:r,windowSize:n}}function P7e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function N7e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function uB(e){return sJ.get(e)||1}function R7e(e,t){return{constTimeNegate:aB,hasPrecomputes(r){return uB(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>DY;)n&SC&&(o=o.add(s)),s=s.double(),n>>=SC;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=cB(n,t),i=[],a=r,c=a;for(let u=0;u>=f,y>i&&(y-=d,o+=SC);let w=h,x=h+Math.abs(y)-1,v=p%2!==0,T=y<0;y===0?c=c.add(aB(v,n[w])):a=a.add(aB(T,n[x]))}return{p:a,f:c}},wNAFUnsafe(r,n,o,s=e.ZERO){let{windows:i,windowSize:a}=cB(r,t),c=BigInt(2**r-1),u=2**r,d=BigInt(r);for(let f=0;f>=d,h>a&&(h-=u,o+=SC),h===0)continue;let y=n[p+Math.abs(h)-1];h<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(r,n,o){let s=lB.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&lB.set(n,o(s))),s},wNAFCached(r,n,o){let s=uB(r);return this.wNAF(s,this.getPrecomputes(s,r,o),n)},wNAFCachedUnsafe(r,n,o,s){let i=uB(r);return i===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,r,o),n,s)},setWindowSize(r,n){oJ(n,t),sJ.set(r,n),lB.delete(r)}}}function O7e(e,t,r,n){if(P7e(r,e),N7e(n,t),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=e.ZERO,s=y7e(BigInt(r.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<=0;f-=i){c.fill(o);for(let h=0;h>BigInt(f)&BigInt(a));c[w]=c[w].add(r[h])}let p=o;for(let h=c.length-1,y=o;h>0;h--)y=y.add(c[h]),p=p.add(y);if(d=d.add(p),f!==0)for(let h=0;h{try{return{isValid:!0,value:r.sqrt(C*r.inv(A))}}catch{return{isValid:!1,value:kc}}}),h=t.adjustScalarBytes||(C=>C),y=t.domain||((C,A,U)=>{if(sB("phflag",U),A.length||U)throw new Error("Contexts/pre-hash are not supported");return C});function w(C,A){B8("coordinate "+C,A,kc,u)}function x(C){if(!(C instanceof E))throw new Error("ExtendedPoint expected")}let v=OY((C,A)=>{let{ex:U,ey:H,ez:k}=C,F=C.is0();A==null&&(A=F?k7e:r.inv(k));let j=d(U*A),W=d(H*A),ae=d(k*A);if(F)return{x:kc,y:wi};if(ae!==wi)throw new Error("invZ was invalid");return{x:j,y:W}}),T=OY(C=>{let{a:A,d:U}=t;if(C.is0())throw new Error("bad point: ZERO");let{ex:H,ey:k,ez:F,et:j}=C,W=d(H*H),ae=d(k*k),te=d(F*F),X=d(te*te),pe=d(W*A),me=d(te*d(pe+ae)),Ne=d(X+d(U*d(W*ae)));if(me!==Ne)throw new Error("bad point: equation left != right (1)");let ye=d(H*k),Re=d(F*j);if(ye!==Re)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(A,U,H,k){this.ex=A,this.ey=U,this.ez=H,this.et=k,w("x",A),w("y",U),w("z",H),w("t",k),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof E)throw new Error("extended point not allowed");let{x:U,y:H}=A||{};return w("x",U),w("y",H),new E(U,H,wi,d(U*H))}static normalizeZ(A){let U=r.invertBatch(A.map(H=>H.ez));return A.map((H,k)=>H.toAffine(U[k])).map(E.fromAffine)}static msm(A,U){return O7e(E,f,A,U)}_setWindowSize(A){O.setWindowSize(this,A)}assertValidity(){T(this)}equals(A){x(A);let{ex:U,ey:H,ez:k}=this,{ex:F,ey:j,ez:W}=A,ae=d(U*W),te=d(F*k),X=d(H*W),pe=d(j*k);return ae===te&&X===pe}is0(){return this.equals(E.ZERO)}negate(){return new E(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:A}=t,{ex:U,ey:H,ez:k}=this,F=d(U*U),j=d(H*H),W=d(IC*d(k*k)),ae=d(A*F),te=U+H,X=d(d(te*te)-F-j),pe=ae+j,me=pe-W,Ne=ae-j,ye=d(X*me),Re=d(pe*Ne),Et=d(X*Ne),kt=d(me*pe);return new E(ye,Re,kt,Et)}add(A){x(A);let{a:U,d:H}=t,{ex:k,ey:F,ez:j,et:W}=this,{ex:ae,ey:te,ez:X,et:pe}=A;if(U===BigInt(-1)){let nW=d((F-k)*(te+ae)),oW=d((F+k)*(te-ae)),FN=d(oW-nW);if(FN===kc)return this.double();let sW=d(j*IC*pe),iW=d(W*IC*X),aW=iW+sW,cW=oW+nW,lW=iW-sW,SCe=d(aW*FN),ICe=d(cW*lW),TCe=d(aW*lW),_Ce=d(FN*cW);return new E(SCe,ICe,_Ce,TCe)}let me=d(k*ae),Ne=d(F*te),ye=d(W*H*pe),Re=d(j*X),Et=d((k+F)*(ae+te)-me-Ne),kt=Re-ye,At=Re+ye,ur=d(Ne-U*me),_r=d(Et*kt),Pl=d(At*ur),ACe=d(Et*ur),CCe=d(kt*At);return new E(_r,Pl,CCe,ACe)}subtract(A){return this.add(A.negate())}wNAF(A){return O.wNAFCached(this,A,E.normalizeZ)}multiply(A){let U=A;B8("scalar",U,wi,n);let{p:H,f:k}=this.wNAF(U);return E.normalizeZ([H,k])[0]}multiplyUnsafe(A,U=E.ZERO){let H=A;return B8("scalar",H,kc,n),H===kc?_:this.is0()||H===wi?this:O.wNAFCachedUnsafe(this,H,E.normalizeZ,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(A){return v(this,A)}clearCofactor(){let{h:A}=t;return A===wi?this:this.multiplyUnsafe(A)}static fromHex(A,U=!1){let{d:H,a:k}=t,F=r.BYTES;A=pf("pointHex",A,F),sB("zip215",U);let j=A.slice(),W=A[F-1];j[F-1]=W&-129;let ae=TC(j),te=U?u:r.ORDER;B8("pointHex.y",ae,kc,te);let X=d(ae*ae),pe=d(X-wi),me=d(H*X-k),{isValid:Ne,value:ye}=p(pe,me);if(!Ne)throw new Error("Point.fromHex: invalid y coordinate");let Re=(ye&wi)===wi,Et=(W&128)!==0;if(!U&&ye===kc&&Et)throw new Error("Point.fromHex: x=0 and x_0=1");return Et!==Re&&(ye=d(-ye)),E.fromAffine({x:ye,y:ae})}static fromPrivateKey(A){return N(A).point}toRawBytes(){let{x:A,y:U}=this.toAffine(),H=gB(U,r.BYTES);return H[H.length-1]|=A&wi?128:0,H}toHex(){return PB(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,wi,d(t.Gx*t.Gy)),E.ZERO=new E(kc,wi,wi,kc);let{BASE:S,ZERO:_}=E,O=R7e(E,a*8);function D(C){return eo(C,n)}function M(C){return D(TC(C))}function N(C){let A=r.BYTES;C=pf("private key",C,A);let U=pf("hashed private key",s(C),2*A),H=h(U.slice(0,A)),k=U.slice(A,2*A),F=M(H),j=S.multiply(F),W=j.toRawBytes();return{head:H,prefix:k,scalar:F,point:j,pointBytes:W}}function L(C){return N(C).pointBytes}function P(C=new Uint8Array,...A){let U=RY(...A);return M(s(y(U,pf("context",C),!!o)))}function R(C,A,U={}){C=pf("message",C),o&&(C=o(C));let{prefix:H,scalar:k,pointBytes:F}=N(A),j=P(U.context,H,C),W=S.multiply(j).toRawBytes(),ae=P(U.context,W,F,C),te=D(j+ae*k);B8("signature.s",te,kc,n);let X=RY(W,gB(te,r.BYTES));return pf("result",X,r.BYTES*2)}let I=U7e;function B(C,A,U,H=I){let{context:k,zip215:F}=H,j=r.BYTES;C=pf("signature",C,2*j),A=pf("message",A),U=pf("publicKey",U,j),F!==void 0&&sB("zip215",F),o&&(A=o(A));let W=TC(C.slice(j,2*j)),ae,te,X;try{ae=E.fromHex(U,F),te=E.fromHex(C.slice(0,j),F),X=S.multiplyUnsafe(W)}catch{return!1}if(!F&&ae.isSmallOrder())return!1;let pe=P(k,te.toRawBytes(),ae.toRawBytes(),A);return te.add(ae.multiplyUnsafe(pe)).subtract(X).clearCofactor().equals(E.ZERO)}return S._setWindowSize(8),{CURVE:t,getPublicKey:L,sign:R,verify:B,ExtendedPoint:E,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(r.BYTES),precompute(C=8,A=E.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}}}}function F7e(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=RB,i=e*e%s*e%s,a=Ml(i,MY,s)*i%s,c=Ml(a,M7e,s)*e%s,u=Ml(c,H7e,s)*c%s,d=Ml(u,t,s)*u%s,f=Ml(d,r,s)*d%s,p=Ml(f,n,s)*f%s,h=Ml(p,o,s)*p%s,y=Ml(h,o,s)*p%s,w=Ml(y,t,s)*u%s;return{pow_p_5_8:Ml(w,MY,s)*e%s,b2:i}}function z7e(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function V7e(e,t){let r=RB,n=eo(t*t*t,r),o=eo(n*n*t,r),s=F7e(e*o).pow_p_5_8,i=eo(e*n*s,r),a=eo(t*i*i,r),c=i,u=eo(i*LY,r),d=a===e,f=a===eo(-e,r),p=a===eo(-e*LY,r);return d&&(i=c),(f||p)&&(i=u),C7e(i,r)&&(i=eo(-i,r)),{isValid:d||f,value:i}}function OB(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function lJ(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?OB(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function uJ(e,t){t||(t=e.reduce((o,s)=>o+s.length,0));let r=lJ(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return OB(r)}function ePe(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}function FPe(e){return e.reduce((t,r)=>(t+=HPe[r],t),"")}function zPe(e){let t=[];for(let r of e){let n=$Pe[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}function hJ(e,t,r){t=t||[],r=r||0;for(var n=r;e>=ZPe;)t[r++]=e&255|$Y,e/=128;for(;e&KPe;)t[r++]=e&255|$Y,e>>>=7;return t[r]=e|0,hJ.bytes=r-n+1,t}function EB(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw EB.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&FY)<=YPe);return EB.bytes=s-n,r}function xJ(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}function OC(e,t="utf8"){let r=vJ[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}function Y2(e,t="utf8"){let r=vJ[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?OB(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function WY(e){return Fs(OC(Y2(e,NC),aJ))}function PC(e){return OC(Y2(yi(e),aJ),NC)}function U8(e){let t=Y2(Q7e,HY),r=J7e+OC(uJ([t,e]),HY);return[G7e,Y7e,r].join(Z7e)}function mNe(e){return OC(e,NC)}function gNe(e){return Y2(e,NC)}function yNe(e){return Y2([PC(e.header),PC(e.payload)].join(_C),cJ)}function wNe(e){return[PC(e.header),PC(e.payload),mNe(e.signature)].join(_C)}function Hl(e){let t=e.split(_C),r=WY(t[0]),n=WY(t[1]),o=gNe(t[2]),s=Y2(t.slice(0,2).join(_C),cJ);return{header:r,payload:n,signature:o,data:s}}function J2(e=YY(X7e)){let t=iJ.getPublicKey(e);return{secretKey:uJ([e,t]),publicKey:t}}async function BC(e,t,r,n,o=(0,KY.fromMiliseconds)(Date.now())){let s={alg:W7e,typ:K7e},i=U8(n.publicKey),a=o+r,c={iss:i,sub:e,aud:t,iat:o,exp:a},u=yNe({header:s,payload:c}),d=iJ.sign(u,n.secretKey.slice(0,32));return wNe({header:s,payload:c,signature:d})}var KY,G2,oB,fB,pB,CC,hB,j_e,q_e,W_e,K_e,Z_e,G_e,Y_e,J_e,Q_e,X_e,e7e,t7e,r7e,o7e,s7e,i7e,a7e,c7e,l7e,Ct,u7e,d7e,ah,ch,mB,f7e,IB,QY,p7e,h7e,ff,iB,w7e,b7e,go,Sn,O1,x7e,yB,BY,kY,C7e,S7e,DY,SC,lB,sJ,kc,wi,IC,k7e,U7e,RB,LY,M7e,MY,H7e,$7e,j7e,q7e,iJ,W7e,K7e,_C,NC,aJ,cJ,Z7e,G7e,Y7e,HY,J7e,Q7e,X7e,tPe,rPe,dJ,nPe,oPe,wB,bB,xB,fJ,vB,RC,k8,sPe,iPe,Mo,aPe,cPe,lPe,uPe,dPe,fPe,pPe,hPe,mPe,gPe,yPe,wPe,bPe,xPe,vPe,EPe,APe,CPe,SPe,IPe,TPe,_Pe,PPe,NPe,RPe,OPe,BPe,kPe,UPe,DPe,LPe,MPe,pJ,HPe,$Pe,VPe,jPe,qPe,$Y,WPe,KPe,ZPe,GPe,YPe,FY,JPe,QPe,XPe,eNe,tNe,rNe,nNe,oNe,sNe,iNe,aNe,mJ,zY,VY,AB,CB,gJ,SB,yJ,cNe,lNe,uNe,wJ,dNe,bJ,fNe,pNe,hNe,jY,qY,dB,vJ,B1=b(()=>{l();KY=Ht(jd());R1();G2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;oB=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);fB=class{clone(){return this._cloneInto()}};pB=class extends fB{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=oB(this.buffer)}update(t){PY(this);let{view:r,buffer:n,blockLen:o}=this;t=GY(t);let s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fBigInt(e>>>0)<>>0),q_e=(e,t,r)=>e>>>r,W_e=(e,t,r)=>e<<32-r|t>>>r,K_e=(e,t,r)=>e>>>r|t<<32-r,Z_e=(e,t,r)=>e<<32-r|t>>>r,G_e=(e,t,r)=>e<<64-r|t>>>r-32,Y_e=(e,t,r)=>e>>>r-32|t<<64-r,J_e=(e,t)=>t,Q_e=(e,t)=>e,X_e=(e,t,r)=>e<>>32-r,e7e=(e,t,r)=>t<>>32-r,t7e=(e,t,r)=>t<>>64-r,r7e=(e,t,r)=>e<>>64-r;o7e=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),s7e=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,i7e=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),a7e=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,c7e=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),l7e=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,Ct={fromBig:JY,split:V_e,toBig:j_e,shrSH:q_e,shrSL:W_e,rotrSH:K_e,rotrSL:Z_e,rotrBH:G_e,rotrBL:Y_e,rotr32H:J_e,rotr32L:Q_e,rotlSH:X_e,rotlSL:e7e,rotlBH:t7e,rotlBL:r7e,add:n7e,add3L:o7e,add3H:s7e,add4L:i7e,add4H:a7e,add5H:l7e,add5L:c7e},[u7e,d7e]=Ct.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),ah=new Uint32Array(80),ch=new Uint32Array(80),mB=class extends pB{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)ah[E]=t.getUint32(r),ch[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=ah[E-15]|0,_=ch[E-15]|0,O=Ct.rotrSH(S,_,1)^Ct.rotrSH(S,_,8)^Ct.shrSH(S,_,7),D=Ct.rotrSL(S,_,1)^Ct.rotrSL(S,_,8)^Ct.shrSL(S,_,7),M=ah[E-2]|0,N=ch[E-2]|0,L=Ct.rotrSH(M,N,19)^Ct.rotrBH(M,N,61)^Ct.shrSH(M,N,6),P=Ct.rotrSL(M,N,19)^Ct.rotrBL(M,N,61)^Ct.shrSL(M,N,6),R=Ct.add4L(D,P,ch[E-7],ch[E-16]),I=Ct.add4H(R,O,L,ah[E-7],ah[E-16]);ah[E]=I|0,ch[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Ct.rotrSH(f,p,14)^Ct.rotrSH(f,p,18)^Ct.rotrBH(f,p,41),_=Ct.rotrSL(f,p,14)^Ct.rotrSL(f,p,18)^Ct.rotrBL(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=Ct.add5L(T,_,D,d7e[E],ch[E]),N=Ct.add5H(M,v,S,O,u7e[E],ah[E]),L=M|0,P=Ct.rotrSH(n,o,28)^Ct.rotrBH(n,o,34)^Ct.rotrBH(n,o,39),R=Ct.rotrSL(n,o,28)^Ct.rotrBL(n,o,34)^Ct.rotrBL(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=Ct.add(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Ct.add3L(L,R,B);n=Ct.add3H(C,N,P,I),o=C|0}({h:n,l:o}=Ct.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ct.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ct.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=Ct.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=Ct.add(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=Ct.add(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=Ct.add(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=Ct.add(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){ah.fill(0),ch.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},f7e=F_e(()=>new mB);IB=BigInt(0),QY=BigInt(1),p7e=BigInt(2);h7e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));ff={_0:48,_9:57,A:65,F:70,a:97,f:102};iB=e=>typeof e=="bigint"&&IB<=e;w7e=e=>(p7e<typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||TB(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};go=BigInt(0),Sn=BigInt(1),O1=BigInt(2),x7e=BigInt(3),yB=BigInt(4),BY=BigInt(5),kY=BigInt(8);C7e=(e,t)=>(eo(e,t)&Sn)===Sn,S7e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];DY=BigInt(0),SC=BigInt(1);lB=new WeakMap,sJ=new WeakMap;kc=BigInt(0),wi=BigInt(1),IC=BigInt(2),k7e=BigInt(8),U7e={zip215:!0};BigInt(0),BigInt(1);RB=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),LY=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);M7e=BigInt(1),MY=BigInt(2);BigInt(3);H7e=BigInt(5),$7e=BigInt(8);j7e=nJ(RB,void 0,!0),q7e={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:j7e,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$7e,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:f7e,randomBytes:YY,adjustScalarBytes:z7e,uvRatio:V7e},iJ=L7e(q7e),W7e="EdDSA",K7e="JWT",_C=".",NC="base64url",aJ="utf8",cJ="utf8",Z7e=":",G7e="did",Y7e="key",HY="base58btc",J7e="z",Q7e="K36",X7e=32;tPe=ePe,rPe=tPe,dJ=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},nPe=e=>new TextEncoder().encode(e),oPe=e=>new TextDecoder().decode(e),wB=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},bB=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return fJ(this,t)}},xB=class{constructor(t){this.decoders=t}or(t){return fJ(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},fJ=(e,t)=>new xB({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),vB=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new wB(t,r,n),this.decoder=new bB(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},RC=({name:e,prefix:t,encode:r,decode:n})=>new vB(e,t,r,n),k8=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=rPe(r,t);return RC({prefix:e,name:t,encode:n,decode:s=>dJ(o(s))})},sPe=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},iPe=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<RC({prefix:t,name:e,encode(o){return iPe(o,n,r)},decode(o){return sPe(o,n,r,e)}}),aPe=RC({prefix:"\0",name:"identity",encode:e=>oPe(e),decode:e=>nPe(e)}),cPe=Object.freeze({__proto__:null,identity:aPe}),lPe=Mo({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),uPe=Object.freeze({__proto__:null,base2:lPe}),dPe=Mo({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fPe=Object.freeze({__proto__:null,base8:dPe}),pPe=k8({prefix:"9",name:"base10",alphabet:"0123456789"}),hPe=Object.freeze({__proto__:null,base10:pPe}),mPe=Mo({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gPe=Mo({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),yPe=Object.freeze({__proto__:null,base16:mPe,base16upper:gPe}),wPe=Mo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bPe=Mo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xPe=Mo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vPe=Mo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EPe=Mo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),APe=Mo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CPe=Mo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SPe=Mo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IPe=Mo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),TPe=Object.freeze({__proto__:null,base32:wPe,base32upper:bPe,base32pad:xPe,base32padupper:vPe,base32hex:EPe,base32hexupper:APe,base32hexpad:CPe,base32hexpadupper:SPe,base32z:IPe}),_Pe=k8({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),PPe=k8({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),NPe=Object.freeze({__proto__:null,base36:_Pe,base36upper:PPe}),RPe=k8({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OPe=k8({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),BPe=Object.freeze({__proto__:null,base58btc:RPe,base58flickr:OPe}),kPe=Mo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),UPe=Mo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),DPe=Mo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),LPe=Mo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),MPe=Object.freeze({__proto__:null,base64:kPe,base64pad:UPe,base64url:DPe,base64urlpad:LPe}),pJ=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),HPe=pJ.reduce((e,t,r)=>(e[r]=t,e),[]),$Pe=pJ.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);VPe=RC({prefix:"\u{1F680}",name:"base256emoji",encode:FPe,decode:zPe}),jPe=Object.freeze({__proto__:null,base256emoji:VPe}),qPe=hJ,$Y=128,WPe=127,KPe=~WPe,ZPe=Math.pow(2,31);GPe=EB,YPe=128,FY=127;JPe=Math.pow(2,7),QPe=Math.pow(2,14),XPe=Math.pow(2,21),eNe=Math.pow(2,28),tNe=Math.pow(2,35),rNe=Math.pow(2,42),nNe=Math.pow(2,49),oNe=Math.pow(2,56),sNe=Math.pow(2,63),iNe=function(e){return e(mJ.encode(e,t,r),t),VY=e=>mJ.encodingLength(e),AB=(e,t)=>{let r=t.byteLength,n=VY(e),o=n+VY(r),s=new Uint8Array(o+r);return zY(e,s,0),zY(r,s,n),s.set(t,o),new CB(e,r,t,s)},CB=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}},gJ=({name:e,code:t,encode:r})=>new SB(e,t,r),SB=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?AB(this.code,r):r.then(n=>AB(this.code,n))}else throw Error("Unknown type, must be binary type")}},yJ=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cNe=gJ({name:"sha2-256",code:18,encode:yJ("SHA-256")}),lNe=gJ({name:"sha2-512",code:19,encode:yJ("SHA-512")}),uNe=Object.freeze({__proto__:null,sha256:cNe,sha512:lNe}),wJ=0,dNe="identity",bJ=dJ,fNe=e=>AB(wJ,bJ(e)),pNe={code:wJ,name:dNe,encode:bJ,digest:fNe},hNe=Object.freeze({__proto__:null,identity:pNe});new TextEncoder,new TextDecoder;jY={...cPe,...uPe,...fPe,...hPe,...yPe,...TPe,...NPe,...BPe,...MPe,...jPe};({...uNe,...hNe});qY=xJ("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),dB=xJ("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=lJ(e.length);for(let r=0;r{l();kC={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var kB=_e((Ift,AJ)=>{l();var bNe="Input must be an string, Buffer or Uint8Array";function xNe(e){let t;if(e instanceof Uint8Array)t=e;else if(typeof e=="string")t=new TextEncoder().encode(e);else throw new Error(bNe);return t}function vNe(e){return Array.prototype.map.call(e,function(t){return(t<16?"0":"")+t.toString(16)}).join("")}function UC(e){return(4294967296+e).toString(16).substring(1)}function ENe(e,t,r){let n=` +`+e+" = ";for(let o=0;o{l();var LC=kB();function DC(e,t,r){let n=e[t]+e[r],o=e[t+1]+e[r+1];n>=4294967296&&o++,e[t]=n,e[t+1]=o}function CJ(e,t,r,n){let o=e[t]+r;r<0&&(o+=4294967296);let s=e[t+1]+n;o>=4294967296&&s++,e[t]=o,e[t+1]=s}function SJ(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function lh(e,t,r,n,o,s){let i=D8[o],a=D8[o+1],c=D8[s],u=D8[s+1];DC(vt,e,t),CJ(vt,e,i,a);let d=vt[n]^vt[e],f=vt[n+1]^vt[e+1];vt[n]=f,vt[n+1]=d,DC(vt,r,n),d=vt[t]^vt[r],f=vt[t+1]^vt[r+1],vt[t]=d>>>24^f<<8,vt[t+1]=f>>>24^d<<8,DC(vt,e,t),CJ(vt,e,c,u),d=vt[n]^vt[e],f=vt[n+1]^vt[e+1],vt[n]=d>>>16^f<<16,vt[n+1]=f>>>16^d<<16,DC(vt,r,n),d=vt[t]^vt[r],f=vt[t+1]^vt[r+1],vt[t]=f>>>31^d<<1,vt[t+1]=d>>>31^f<<1}var IJ=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),CNe=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],os=new Uint8Array(CNe.map(function(e){return e*2})),vt=new Uint32Array(32),D8=new Uint32Array(32);function TJ(e,t){let r=0;for(r=0;r<16;r++)vt[r]=e.h[r],vt[r+16]=IJ[r];for(vt[24]=vt[24]^e.t,vt[25]=vt[25]^e.t/4294967296,t&&(vt[28]=~vt[28],vt[29]=~vt[29]),r=0;r<32;r++)D8[r]=SJ(e.b,4*r);for(r=0;r<12;r++)lh(0,8,16,24,os[r*16+0],os[r*16+1]),lh(2,10,18,26,os[r*16+2],os[r*16+3]),lh(4,12,20,28,os[r*16+4],os[r*16+5]),lh(6,14,22,30,os[r*16+6],os[r*16+7]),lh(0,10,20,30,os[r*16+8],os[r*16+9]),lh(2,12,22,24,os[r*16+10],os[r*16+11]),lh(4,14,16,26,os[r*16+12],os[r*16+13]),lh(6,8,18,28,os[r*16+14],os[r*16+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^vt[r]^vt[r+16]}var uh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function _J(e,t,r,n){if(e===0||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(n&&n.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");let o={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};uh.fill(0),uh[0]=e,t&&(uh[1]=t.length),uh[2]=1,uh[3]=1,r&&uh.set(r,32),n&&uh.set(n,48);for(let s=0;s<16;s++)o.h[s]=IJ[s]^SJ(uh,s*4);return t&&(UB(o,t),o.c=128),o}function UB(e,t){for(let r=0;r>2]>>8*(r&3);return t}function NJ(e,t,r,n,o){r=r||64,e=LC.normalizeInput(e),n&&(n=LC.normalizeInput(n)),o&&(o=LC.normalizeInput(o));let s=_J(r,t,n,o);return UB(s,e),PJ(s)}function SNe(e,t,r,n,o){let s=NJ(e,t,r,n,o);return LC.toHex(s)}RJ.exports={blake2b:NJ,blake2bHex:SNe,blake2bInit:_J,blake2bUpdate:UB,blake2bFinal:PJ}});var $J=_e((Nft,HJ)=>{l();var BJ=kB();function INe(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function dh(e,t,r,n,o,s){Xt[e]=Xt[e]+Xt[t]+o,Xt[n]=MC(Xt[n]^Xt[e],16),Xt[r]=Xt[r]+Xt[n],Xt[t]=MC(Xt[t]^Xt[r],12),Xt[e]=Xt[e]+Xt[t]+s,Xt[n]=MC(Xt[n]^Xt[e],8),Xt[r]=Xt[r]+Xt[n],Xt[t]=MC(Xt[t]^Xt[r],7)}function MC(e,t){return e>>>t^e<<32-t}var kJ=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ss=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),Xt=new Uint32Array(16),Ho=new Uint32Array(16);function UJ(e,t){let r=0;for(r=0;r<8;r++)Xt[r]=e.h[r],Xt[r+8]=kJ[r];for(Xt[12]^=e.t,Xt[13]^=e.t/4294967296,t&&(Xt[14]=~Xt[14]),r=0;r<16;r++)Ho[r]=INe(e.b,4*r);for(r=0;r<10;r++)dh(0,4,8,12,Ho[ss[r*16+0]],Ho[ss[r*16+1]]),dh(1,5,9,13,Ho[ss[r*16+2]],Ho[ss[r*16+3]]),dh(2,6,10,14,Ho[ss[r*16+4]],Ho[ss[r*16+5]]),dh(3,7,11,15,Ho[ss[r*16+6]],Ho[ss[r*16+7]]),dh(0,5,10,15,Ho[ss[r*16+8]],Ho[ss[r*16+9]]),dh(1,6,11,12,Ho[ss[r*16+10]],Ho[ss[r*16+11]]),dh(2,7,8,13,Ho[ss[r*16+12]],Ho[ss[r*16+13]]),dh(3,4,9,14,Ho[ss[r*16+14]],Ho[ss[r*16+15]]);for(r=0;r<8;r++)e.h[r]^=Xt[r]^Xt[r+8]}function DJ(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");let r=t?t.length:0;if(t&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");let n={h:new Uint32Array(kJ),b:new Uint8Array(64),c:0,t:0,outlen:e};return n.h[0]^=16842752^r<<8^e,r>0&&(DB(n,t),n.c=64),n}function DB(e,t){for(let r=0;r>2]>>8*(r&3)&255;return t}function MJ(e,t,r){r=r||32,e=BJ.normalizeInput(e);let n=DJ(r,t);return DB(n,e),LJ(n)}function TNe(e,t,r){let n=MJ(e,t,r);return BJ.toHex(n)}HJ.exports={blake2s:MJ,blake2sHex:TNe,blake2sInit:DJ,blake2sUpdate:DB,blake2sFinal:LJ}});var LB=_e((Oft,FJ)=>{l();var L8=OJ(),M8=$J();FJ.exports={blake2b:L8.blake2b,blake2bHex:L8.blake2bHex,blake2bInit:L8.blake2bInit,blake2bUpdate:L8.blake2bUpdate,blake2bFinal:L8.blake2bFinal,blake2s:M8.blake2s,blake2sHex:M8.blake2sHex,blake2sInit:M8.blake2sInit,blake2sUpdate:M8.blake2sUpdate,blake2sFinal:M8.blake2sFinal}});function _Ne(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}function NNe(e,t,r){var n=r&&r.stringify||_Ne,o=1;if(typeof e=="object"&&e!==null){var s=t.length+o;if(s===1)return e;var i=new Array(s);i[0]=n(e);for(var a=1;a-1?f:0,e.charCodeAt(h+1)){case 100:case 102:if(d>=c||t[d]==null)break;f=c||t[d]==null)break;f=c||t[d]===void 0)break;f",f=h+2,h++;break}u+=n(t[d]),f=h+2,h++;break;case 115:if(d>=c)break;f{n[o]=r[o]?r[o]:H8[o]||H8[ONe[o]||"log"]||Q2}),e[jB]=n}function kNe(e,t){return Array.isArray(e)?e.filter(function(r){return r!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function hf(e){e=e||{},e.browser=e.browser||{};let t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");let r=e.browser.write||H8;e.browser.write&&(e.browser.asObject=!0);let n=e.serializers||{},o=kNe(e.browser.serialize,n),s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let i=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(i);typeof r=="function"&&a.forEach(function(w){r[w]=r}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");let c=e.level||"info",u=Object.create(r);u.log||(u.log=Q2),BNe(u,a,r),VJ({},u),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:p,set:h});let d={transmit:t,serialize:o,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:zNe(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Q2};u.levels=UNe(e),u.level=c,u.isLevelEnabled=function(w){return this.levels.values[w]?this.levels.values[w]>=this.levels.values[this.level]:!1},u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=Q2,u.serializers=n,u._serialize=o,u._stdErrSerialize=s,u.child=function(...w){return y.call(this,d,...w)},t&&(u._logEvent=$B());function f(){return ph(this.level,this)}function p(){return this._level}function h(w){if(w!=="silent"&&!this.levels.values[w])throw Error("unknown level "+w);this._level=w,k1(this,d,u,"error"),k1(this,d,u,"fatal"),k1(this,d,u,"warn"),k1(this,d,u,"info"),k1(this,d,u,"debug"),k1(this,d,u,"trace"),i.forEach(x=>{k1(this,d,u,x)})}function y(w,x,v){if(!x)throw new Error("missing bindings for child Pino");v=v||{},o&&x.serializers&&(v.serializers=x.serializers);let T=v.serializers;if(o&&T){var E=Object.assign({},n,T),S=e.browser.serialize===!0?Object.keys(E):o;delete x.serializers,qB([x],S,E,this._stdErrSerialize)}function _(D){this._childLevel=(D._childLevel|0)+1,this.bindings=x,E&&(this.serializers=E,this._serialize=S),t&&(this._logEvent=$B([].concat(D._logEvent.bindings,x)))}_.prototype=this;let O=new _(this);return VJ(this,O),O.child=function(...D){return y.call(this,w,...D)},O.level=v.level||this.level,w.onChild(O),O}return u}function UNe(e){let t=e.customLevels||{},r=Object.assign({},hf.levels.values,t),n=Object.assign({},hf.levels.labels,DNe(t));return{values:r,labels:n}}function DNe(e){let t={};return Object.keys(e).forEach(function(r){t[e[r]]=r}),t}function LNe(e){let t=[];e.bindings&&t.push(e.bindings);let r=e[HB];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}function k1(e,t,r,n){if(Object.defineProperty(e,n,{value:ph(e.level,r)>ph(n,r)?Q2:r[jB][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===Q2){if(!t.transmit)return;let s=t.transmit.level||e.level,i=ph(s,r);if(ph(n,r)f}=o.formatters||{},a=r.slice(),c=a[0],u={},d=(e._childLevel|0)+1;if(d<1&&(d=1),n&&(u.time=n),s){let f=s(t,e.levels.values[t]);Object.assign(u,f)}else u.level=e.levels.values[t];if(o.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;d--&&typeof a[0]=="object";)Object.assign(u,a.shift());return[i(u),...a]}else{if(c!==null&&typeof c=="object"){for(;d--&&typeof a[0]=="object";)Object.assign(u,a.shift());c=a.length?zJ(a.shift(),a):void 0}else typeof c=="string"&&(c=zJ(a.shift(),a));return c!==void 0&&(u[o.messageKey]=c),[i(u)]}}function qB(e,t,r,n){for(let o in e)if(n&&e[o]instanceof Error)e[o]=hf.stdSerializers.err(e[o]);else if(typeof e[o]=="object"&&!Array.isArray(e[o])&&t)for(let s in e[o])t.indexOf(s)>-1&&s in r&&(e[o][s]=r[s](e[o][s]))}function FNe(e,t,r,n=!1){let o=t.send,s=t.ts,i=t.methodLevel,a=t.methodValue,c=t.val,u=e._logEvent.bindings;n||qB(r,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=r.filter(function(d){return u.indexOf(d)===-1}),e._logEvent.level.label=i,e._logEvent.level.value=a,o(i,e._logEvent,c),e._logEvent=$B(u)}function $B(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function jJ(e){let t={type:e.constructor.name,msg:e.message,stack:e.stack};for(let r in e)t[r]===void 0&&(t[r]=e[r]);return t}function zNe(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?ZJ:GJ}function HC(){return{}}function MB(e){return e}function Q2(){}function ZJ(){return!1}function GJ(){return Date.now()}function VNe(){return Math.round(Date.now()/1e3)}function jNe(){return new Date(Date.now()).toISOString()}function qNe(){function e(t){return typeof t<"u"&&t}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}function qJ(e){return typeof e=="string"?e:GNe(e)||""}function X2(e){return mh(hh({},e),{level:e?.level||WNe.level})}function lRe(e,t,r=VC){return e[r]=t,e}function sr(e,t=VC){return e[t]||""}function uRe(e,t,r=VC){let n=sr(e,r);return n.trim()?`${n}/${t}`:t}function Cr(e,t,r=VC){let n=uRe(e,t,r),o=e.child({context:n});return lRe(o,n,r)}function dRe(e){var t,r;let n=new zB((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:$l.exports(mh(hh({},e.opts),{level:"trace",browser:mh(hh({},(r=e.opts)==null?void 0:r.browser),{write:o=>n.write(o)})})),chunkLoggerController:n}}function fRe(e){var t,r;let n=new VB((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:$l.exports(mh(hh({},e.opts),{level:"trace",browser:mh(hh({},(r=e.opts)==null?void 0:r.browser),{write:o=>n.write(o)})}),n),chunkLoggerController:n}}function Fl(e){var t;if(typeof e.loggerOverride<"u"&&typeof e.loggerOverride!="string")return{logger:e.loggerOverride,chunkLoggerController:null};let r=mh(hh({},e.opts),{level:typeof e.loggerOverride=="string"?e.loggerOverride:(t=e.opts)==null?void 0:t.level});return typeof window<"u"?dRe(mh(hh({},e),{opts:r})):fRe(mh(hh({},e),{opts:r}))}var $l,PNe,zJ,H8,RNe,jB,HB,ONe,kft,WNe,VC,WB,KNe,ZNe,fh,FB,FC,GNe,YNe,JNe,$C,zC,QNe,XNe,eRe,zB,tRe,rRe,nRe,VB,oRe,sRe,iRe,WJ,aRe,cRe,KJ,hh,mh,gh=b(()=>{l();$l={exports:{}};PNe=NNe;zJ=PNe;$l.exports=hf;H8=qNe().console||{},RNe={mapHttpRequest:HC,mapHttpResponse:HC,wrapRequestSerializer:MB,wrapResponseSerializer:MB,wrapErrorSerializer:MB,req:HC,res:HC,err:jJ,errWithCause:jJ};jB=Symbol("pino.logFuncs"),HB=Symbol("pino.hierarchy"),ONe={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};hf.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},hf.stdSerializers=RNe,hf.stdTimeFunctions=Object.assign({},{nullTime:ZJ,epochTime:GJ,unixTime:VNe,isoTime:jNe});$l.exports.default=hf;kft=$l.exports.pino=hf,WNe={level:"info"},VC="custom_context",WB=1e3*1024,KNe=Object.defineProperty,ZNe=(e,t,r)=>t in e?KNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,fh=(e,t,r)=>ZNe(e,typeof t!="symbol"?t+"":t,r),FB=class{constructor(t){fh(this,"nodeValue"),fh(this,"sizeInBytes"),fh(this,"next"),this.nodeValue=t,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},FC=class{constructor(t){fh(this,"lengthInNodes"),fh(this,"sizeInBytes"),fh(this,"head"),fh(this,"tail"),fh(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=t,this.sizeInBytes=0}append(t){let r=new FB(t);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${t} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let t=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=t.size}toArray(){let t=[],r=this.head;for(;r!==null;)t.push(r.value),r=r.next;return t}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let t=this.head;return{next:()=>{if(!t)return{done:!0,value:null};let r=t.value;return t=t.next,{done:!1,value:r}}}}},GNe=e=>JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString()+"n":r);YNe=Object.defineProperty,JNe=(e,t,r)=>t in e?YNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$C=(e,t,r)=>JNe(e,typeof t!="symbol"?t+"":t,r),zC=class{constructor(t,r=WB){$C(this,"logs"),$C(this,"level"),$C(this,"levelValue"),$C(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=t??"error",this.levelValue=$l.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new FC(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(t,r){r===$l.exports.levels.values.error?console.error(t):r===$l.exports.levels.values.warn?console.warn(t):r===$l.exports.levels.values.debug?console.debug(t):r===$l.exports.levels.values.trace?console.trace(t):console.log(t)}appendToLogs(t){this.logs.append(qJ({timestamp:new Date().toISOString(),log:t}));let r=typeof t=="string"?JSON.parse(t).level:t.level;r>=this.levelValue&&this.forwardToConsole(t,r)}getLogs(){return this.logs}clearLogs(){this.logs=new FC(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(t){let r=this.getLogArray();return r.push(qJ({extraMetadata:t})),new Blob(r,{type:"application/json"})}},QNe=Object.defineProperty,XNe=(e,t,r)=>t in e?QNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,eRe=(e,t,r)=>XNe(e,typeof t!="symbol"?t+"":t,r),zB=class{constructor(t,r=WB){eRe(this,"baseChunkLogger"),this.baseChunkLogger=new zC(t,r)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}downloadLogsBlobInBrowser(t){let r=URL.createObjectURL(this.logsToBlob(t)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},tRe=Object.defineProperty,rRe=(e,t,r)=>t in e?tRe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,nRe=(e,t,r)=>rRe(e,typeof t!="symbol"?t+"":t,r),VB=class{constructor(t,r=WB){nRe(this,"baseChunkLogger"),this.baseChunkLogger=new zC(t,r)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}},oRe=Object.defineProperty,sRe=Object.defineProperties,iRe=Object.getOwnPropertyDescriptors,WJ=Object.getOwnPropertySymbols,aRe=Object.prototype.hasOwnProperty,cRe=Object.prototype.propertyIsEnumerable,KJ=(e,t,r)=>t in e?oRe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,hh=(e,t)=>{for(var r in t||(t={}))aRe.call(t,r)&&KJ(e,r,t[r]);if(WJ)for(var r of WJ(t))cRe.call(t,r)&&KJ(e,r,t[r]);return e},mh=(e,t)=>sRe(e,iRe(t))});var yo,oX=b(()=>{l();yo=class{}});var tS=b(()=>{l();oX()});var iX,rS,xk,sX,Vs,iw,vk=b(()=>{l();iX=Ht(ks()),rS=Ht(jd());tS();xk=class extends yo{constructor(t){super()}},sX=rS.FIVE_SECONDS,Vs={pulse:"heartbeat_pulse"},iw=class e extends xk{constructor(t){super(t),this.events=new iX.EventEmitter,this.interval=sX,this.interval=t?.interval||sX}static async init(t){let r=new e(t);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),(0,rS.toMiliseconds)(this.interval))}pulse(){this.events.emit(Vs.pulse)}}});function vOe(e,t){if(e==="__proto__"||e==="constructor"&&t&&typeof t=="object"&&"prototype"in t){EOe(e);return}return t}function EOe(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}function J8(e,t={}){if(typeof e!="string")return e;if(e[0]==='"'&&e[e.length-1]==='"'&&e.indexOf("\\")===-1)return e.slice(1,-1);let r=e.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!xOe.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(wOe.test(e)||bOe.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,vOe)}return JSON.parse(e)}catch(n){if(t.strict)throw n;return e}}var wOe,bOe,xOe,aX=b(()=>{l();wOe=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,bOe=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,xOe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function AOe(e){return!e||typeof e.then!="function"?Promise.resolve(e):e}function ro(e,...t){try{return AOe(e(...t))}catch(r){return Promise.reject(r)}}function COe(e){let t=typeof e;return e===null||t!=="object"&&t!=="function"}function SOe(e){let t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}function Q8(e){if(COe(e))return String(e);if(SOe(e)||Array.isArray(e))return JSON.stringify(e);if(typeof e.toJSON=="function")return Q8(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function cX(e){return typeof e=="string"?e:Ek+TOe(e)}function lX(e){return typeof e!="string"||!e.startsWith(Ek)?e:IOe(e.slice(Ek.length))}function IOe(e){return globalThis.Buffer?Buffer.from(e,"base64"):Uint8Array.from(globalThis.atob(e),t=>t.codePointAt(0))}function TOe(e){return globalThis.Buffer?Buffer.from(e).toString("base64"):globalThis.btoa(String.fromCodePoint(...e))}function bh(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Ak(e){return e.split(":").some(t=>t==="."||t==="..")}function uX(...e){return bh(e.join(":"))}function Ck(e){return e=bh(e),e?e+":":""}function dX(e,t){if(t===void 0)return!0;let r=0,n=e.indexOf(":");for(;n>-1;)r++,n=e.indexOf(":",n+1);return r<=t}function fX(e,t){return t?e.startsWith(t)&&e[e.length-1]!=="$":e[e.length-1]!=="$"}var Ek,pX=b(()=>{l();Ek="base64:"});function gX(e={}){let t={mounts:{"":e.driver||POe()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=f=>{let p=bh(f);if(!p||Ak(p))throw new Error(`[unstorage] Invalid key: ${JSON.stringify(f)}`);return p},n=f=>{let p=Ck(f);if(Ak(p))throw new Error(`[unstorage] Invalid base: ${JSON.stringify(f)}`);return p},o=f=>{for(let p of t.mountpoints)if(f.startsWith(p))return{base:p,relativeKey:f.slice(p.length),driver:t.mounts[p]};return{base:"",relativeKey:f,driver:t.mounts[""]}},s=(f,p)=>t.mountpoints.filter(h=>h.startsWith(f)||p&&f.startsWith(h)).map(h=>({relativeBase:f.length>h.length?f.slice(h.length):void 0,mountpoint:h,driver:t.mounts[h]})),i=(f,p)=>{if(t.watching){p=bh(p);for(let h of t.watchListeners)h(f,p)}},a=async()=>{if(!t.watching){t.watching=!0;for(let f in t.mounts)t.unwatch[f]=await hX(t.mounts[f],i,f)}},c=async()=>{if(t.watching){for(let f in t.unwatch)await t.unwatch[f]();t.unwatch={},t.watching=!1}},u=(f,p,h)=>{let y=new Map,w=x=>{let v=y.get(x.base);return v||(v={driver:x.driver,base:x.base,items:[]},y.set(x.base,v)),v};for(let x of f){let v=typeof x=="string",T=r(v?x:x.key),E=v?void 0:x.value,S=v||!x.options?p:{...p,...x.options},_=o(T);w(_).items.push({key:T,value:E,relativeKey:_.relativeKey,options:S})}return Promise.all([...y.values()].map(x=>h(x))).then(x=>x.flat())},d={async hasItem(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return ro(y.hasItem,h,p)},async getItem(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return ro(y.getItem,h,p).then(w=>J8(w))},async getItems(f,p={}){return u(f,p,h=>h.driver.getItems?ro(h.driver.getItems,h.items.map(y=>({key:y.relativeKey,options:y.options})),p).then(y=>y.map(w=>({key:uX(h.base,w.key),value:J8(w.value)}))):Promise.all(h.items.map(y=>ro(h.driver.getItem,y.relativeKey,y.options).then(w=>({key:y.key,value:J8(w)})))))},async getItemRaw(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return y.getItemRaw?ro(y.getItemRaw,h,p):ro(y.getItem,h,p).then(w=>lX(w))},async setItem(f,p,h={}){if(p===void 0)return d.removeItem(f);f=r(f);let{relativeKey:y,driver:w}=o(f);w.setItem&&(await ro(w.setItem,y,Q8(p),h),w.watch||i("update",f))},async setItems(f,p){await u(f,p,async h=>{if(h.driver.setItems)return ro(h.driver.setItems,h.items.map(y=>({key:y.relativeKey,value:Q8(y.value),options:y.options})),p);h.driver.setItem&&await Promise.all(h.items.map(y=>ro(h.driver.setItem,y.relativeKey,Q8(y.value),y.options)))})},async setItemRaw(f,p,h={}){if(p===void 0)return d.removeItem(f,h);f=r(f);let{relativeKey:y,driver:w}=o(f);if(w.setItemRaw)await ro(w.setItemRaw,y,p,h);else if(w.setItem)await ro(w.setItem,y,cX(p),h);else return;w.watch||i("update",f)},async removeItem(f,p={}){typeof p=="boolean"&&(p={removeMeta:p}),f=r(f);let{relativeKey:h,driver:y}=o(f);y.removeItem&&(await ro(y.removeItem,h,p),(p.removeMeta||p.removeMata)&&await ro(y.removeItem,h+"$",p),y.watch||i("remove",f))},async getMeta(f,p={}){typeof p=="boolean"&&(p={nativeOnly:p}),f=r(f);let{relativeKey:h,driver:y}=o(f),w=Object.create(null);if(y.getMeta&&Object.assign(w,await ro(y.getMeta,h,p)),!p.nativeOnly){let x=await ro(y.getItem,h+"$",p).then(v=>J8(v));x&&typeof x=="object"&&(typeof x.atime=="string"&&(x.atime=new Date(x.atime)),typeof x.mtime=="string"&&(x.mtime=new Date(x.mtime)),Object.assign(w,x))}return w},async setMeta(f,p,h={}){return this.setItem(r(f)+"$",p,h)},async removeMeta(f,p={}){return this.removeItem(r(f)+"$",p)},async getKeys(f,p={}){f=n(f);let h=s(f,!0),y=[],w=[],x=!0;for(let T of h){T.driver.flags?.maxDepth||(x=!1);let E=await ro(T.driver.getKeys,T.relativeBase,p);for(let S of E){let _=T.mountpoint+bh(S);y.some(O=>_.startsWith(O))||w.push(_)}y=[T.mountpoint,...y.filter(S=>!S.startsWith(T.mountpoint))]}let v=p.maxDepth!==void 0&&!x;return w.filter(T=>(!v||dX(T,p.maxDepth))&&fX(T,f))},async clear(f,p={}){f=n(f),await Promise.all(s(f,!1).map(async h=>{if(h.driver.clear)return ro(h.driver.clear,h.relativeBase,p);if(h.driver.removeItem){let y=await h.driver.getKeys(h.relativeBase||"",p);return Promise.all(y.map(w=>h.driver.removeItem(w,p)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(f=>mX(f)))},async watch(f){return await a(),t.watchListeners.push(f),async()=>{t.watchListeners=t.watchListeners.filter(p=>p!==f),t.watchListeners.length===0&&await c()}},async unwatch(){t.watchListeners=[],await c()},mount(f,p){if(f=n(f),f&&t.mounts[f])throw new Error(`already mounted at ${f}`);return f&&(t.mountpoints.push(f),t.mountpoints.sort((h,y)=>y.length-h.length)),t.mounts[f]=p,t.watching&&Promise.resolve(hX(p,i,f)).then(h=>{t.unwatch[f]=h}).catch(console.error),d},async unmount(f,p=!0){f=Ck(f),!(!f||!t.mounts[f])&&(t.watching&&f in t.unwatch&&(t.unwatch[f]?.(),delete t.unwatch[f]),p&&await mX(t.mounts[f]),t.mountpoints=t.mountpoints.filter(h=>h!==f),delete t.mounts[f])},getMount(f=""){f=bh(f)+":";let p=o(f);return{driver:p.driver,base:p.base}},getMounts(f="",p={}){return f=bh(f),s(f,p.parents).map(y=>({driver:y.driver,base:y.mountpoint}))},keys:(f,p={})=>d.getKeys(f,p),get:(f,p={})=>d.getItem(f,p),set:(f,p,h={})=>d.setItem(f,p,h),has:(f,p={})=>d.hasItem(f,p),del:(f,p={})=>d.removeItem(f,p),remove:(f,p={})=>d.removeItem(f,p)};return d}function hX(e,t,r){return e.watch?e.watch((n,o)=>t(n,r+o)):()=>{}}async function mX(e){typeof e.dispose=="function"&&await ro(e.dispose)}var _Oe,POe,yX=b(()=>{l();aX();pX();_Oe="memory",POe=()=>{let e=new Map;return{name:_Oe,getInstance:()=>e,hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,r){e.set(t,r)},setItemRaw(t,r){e.set(t,r)},removeItem(t){e.delete(t)},getKeys(){return[...e.keys()]},clear(){e.clear()},dispose(){e.clear()}}}});function $1(e){return new Promise((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})}function Ik(e,t){let r=indexedDB.open(e);r.onupgradeneeded=()=>r.result.createObjectStore(t);let n=$1(r);return(o,s)=>n.then(i=>s(i.transaction(t,o).objectStore(t)))}function X8(){return Sk||(Sk=Ik("keyval-store","keyval")),Sk}function Tk(e,t=X8()){return t("readonly",r=>$1(r.get(e)))}function wX(e,t,r=X8()){return r("readwrite",n=>(n.put(t,e),$1(n.transaction)))}function bX(e,t=X8()){return t("readwrite",r=>(r.delete(e),$1(r.transaction)))}function xX(e=X8()){return e("readwrite",t=>(t.clear(),$1(t.transaction)))}function NOe(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},$1(e.transaction)}function vX(e=X8()){return e("readonly",t=>{if(t.getAllKeys)return $1(t.getAllKeys());let r=[];return NOe(t,n=>r.push(n.key)).then(()=>r)})}var Sk,EX=b(()=>{l()});function UOe(e){var t;return[e[0],Fs((t=e[1])!=null?t:"")]}var ROe,OOe,BOe,kOe,Pk,_k,nS,Nk,DOe,AX,LOe,MOe,aw,Rk=b(()=>{l();yX();EX();R1();ROe="idb-keyval",OOe=(e={})=>{let t=e.base&&e.base.length>0?`${e.base}:`:"",r=o=>t+o,n;return e.dbName&&e.storeName&&(n=Ik(e.dbName,e.storeName)),{name:ROe,options:e,async hasItem(o){return!(typeof await Tk(r(o),n)>"u")},async getItem(o){return await Tk(r(o),n)??null},setItem(o,s){return wX(r(o),s,n)},removeItem(o){return bX(r(o),n)},getKeys(){return vX(n)},clear(){return xX(n)}}},BOe="WALLET_CONNECT_V2_INDEXED_DB",kOe="keyvaluestorage",Pk=class{constructor(){this.indexedDb=gX({driver:OOe({dbName:BOe,storeName:kOe})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(t=>[t.key,t.value])}async getItem(t){let r=await this.indexedDb.getItem(t);if(r!==null)return r}async setItem(t,r){await this.indexedDb.setItem(t,yi(r))}async removeItem(t){await this.indexedDb.removeItem(t)}},_k=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},nS={exports:{}};(function(){let e;function t(){}e=t,e.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},e.prototype.setItem=function(r,n){this[r]=String(n)},e.prototype.removeItem=function(r){delete this[r]},e.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},e.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},e.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof _k<"u"&&_k.localStorage?nS.exports=_k.localStorage:typeof window<"u"&&window.localStorage?nS.exports=window.localStorage:nS.exports=new t})();Nk=class{constructor(){this.localStorage=nS.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(UOe)}async getItem(t){let r=this.localStorage.getItem(t);if(r!==null)return Fs(r)}async setItem(t,r){this.localStorage.setItem(t,yi(r))}async removeItem(t){this.localStorage.removeItem(t)}},DOe="wc_storage_version",AX=1,LOe=async(e,t,r)=>{let n=DOe,o=await t.getItem(n);if(o&&o>=AX){r(t);return}let s=await e.getKeys();if(!s.length){r(t);return}let i=[];for(;s.length;){let a=s.shift();if(!a)continue;let c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){let u=await e.getItem(a);await t.setItem(a,u),i.push(a)}}await t.setItem(n,AX),r(t),MOe(e,i)},MOe=async(e,t)=>{t.length&&t.forEach(async r=>{await e.removeItem(r)})},aw=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let t=new Nk;this.storage=t;try{let r=new Pk;LOe(t,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(t){return await this.initialize(),this.storage.getItem(t)}async setItem(t,r){return await this.initialize(),this.storage.setItem(t,r)}async removeItem(t){return await this.initialize(),this.storage.removeItem(t)}async initialize(){this.initialized||await new Promise(t=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),t())},20)})}}});var SX,IX,TX,_X,yS,e4,Ok,wS,xh,t4,bS=b(()=>{l();SX="PARSE_ERROR",IX="INVALID_REQUEST",TX="METHOD_NOT_FOUND",_X="INVALID_PARAMS",yS="INTERNAL_ERROR",e4="SERVER_ERROR",Ok=[-32700,-32600,-32601,-32602,-32603],wS=[-32e3,-32099],xh={[SX]:{code:-32700,message:"Parse error"},[IX]:{code:-32600,message:"Invalid Request"},[TX]:{code:-32601,message:"Method not found"},[_X]:{code:-32602,message:"Invalid params"},[yS]:{code:-32603,message:"Internal error"},[e4]:{code:-32e3,message:"Server error"}},t4=e4});function HOe(e){return e<=wS[0]&&e>=wS[1]}function xS(e){return Ok.includes(e)}function PX(e){return typeof e=="number"}function vS(e){return Object.keys(xh).includes(e)?xh[e]:xh[t4]}function ES(e){let t=Object.values(xh).find(r=>r.code===e);return t||xh[t4]}function $Oe(e){if(typeof e.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof e.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!PX(e.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${e.error.code}`};if(xS(e.error.code)){let t=ES(e.error.code);if(t.message!==xh[t4].message&&e.error.message===t.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${e.error.code}`}}return{valid:!0}}function r4(e,t,r){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${t}`):e}var Bk=b(()=>{l();bS()});var RX=_e(vh=>{"use strict";l();Object.defineProperty(vh,"__esModule",{value:!0});vh.isBrowserCryptoAvailable=vh.getSubtleCrypto=vh.getBrowerCrypto=void 0;function kk(){return(global==null?void 0:global.crypto)||(global==null?void 0:global.msCrypto)||{}}vh.getBrowerCrypto=kk;function NX(){let e=kk();return e.subtle||e.webkitSubtle}vh.getSubtleCrypto=NX;function FOe(){return!!kk()&&!!NX()}vh.isBrowserCryptoAvailable=FOe});var kX=_e(Eh=>{"use strict";l();Object.defineProperty(Eh,"__esModule",{value:!0});Eh.isBrowser=Eh.isNode=Eh.isReactNative=void 0;function OX(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Eh.isReactNative=OX;function BX(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Eh.isNode=BX;function zOe(){return!OX()&&!BX()}Eh.isBrowser=zOe});var Uk=_e(AS=>{"use strict";l();Object.defineProperty(AS,"__esModule",{value:!0});var UX=(b2(),Yx(w2));UX.__exportStar(RX(),AS);UX.__exportStar(kX(),AS)});var wo={};Te(wo,{isNodeJs:()=>LX});var DX,LX,MX=b(()=>{l();DX=Ht(Uk());Bo(wo,Ht(Uk()));LX=DX.isNode});function Tn(e=3){let t=Date.now()*Math.pow(10,e),r=Math.floor(Math.random()*Math.pow(10,e));return t+r}function _n(e=6){return BigInt(Tn(e))}function dr(e,t,r){return{id:r||Tn(),jsonrpc:"2.0",method:e,params:t}}function bo(e,t){return{id:e,jsonrpc:"2.0",result:t}}function la(e,t,r){return{id:e,jsonrpc:"2.0",error:HX(t,r)}}function HX(e,t){return typeof e>"u"?vS(yS):(typeof e=="string"&&(e=Object.assign(Object.assign({},vS(e4)),{message:e})),typeof t<"u"&&(e.data=t),xS(e.code)&&(e=ES(e.code)),e)}var $X=b(()=>{l();Bk();bS()});function VOe(e){return e.includes("*")?SS(e):!/\W/g.test(e)}function CS(e){return e==="*"}function SS(e){return CS(e)?!0:!(!e.includes("*")||e.split("*").length!==2||e.split("*").filter(t=>t.trim()==="").length!==1)}function jOe(e){return!CS(e)&&SS(e)&&!e.split("*")[0].trim()}function qOe(e){return!CS(e)&&SS(e)&&!e.split("*")[1].trim()}var FX=b(()=>{l()});var n4,Dk,IS,o4,zX=b(()=>{l();n4=class{},Dk=class extends n4{constructor(t){super()}},IS=class extends n4{constructor(){super()}},o4=class extends IS{constructor(t){super()}}});var VX=b(()=>{l();zX()});function ZOe(e){let t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function jX(e,t){let r=ZOe(e);return typeof r>"u"?!1:new RegExp(t).test(r)}function TS(e){return jX(e,WOe)}function _S(e){return jX(e,KOe)}function Lk(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}var WOe,KOe,qX=b(()=>{l();WOe="^https?:",KOe="^wss?:"});function Mk(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function Hc(e){return Mk(e)&&"method"in e}function ua(e){return Mk(e)&&(Jr(e)||Ir(e))}function Jr(e){return"result"in e}function Ir(e){return"error"in e}function GOe(e){return"error"in e&&e.valid===!1}var WX=b(()=>{l()});var vi={};Te(vi,{DEFAULT_ERROR:()=>t4,IBaseJsonRpcProvider:()=>IS,IEvents:()=>n4,IJsonRpcConnection:()=>Dk,IJsonRpcProvider:()=>o4,INTERNAL_ERROR:()=>yS,INVALID_PARAMS:()=>_X,INVALID_REQUEST:()=>IX,METHOD_NOT_FOUND:()=>TX,PARSE_ERROR:()=>SX,RESERVED_ERROR_CODES:()=>Ok,SERVER_ERROR:()=>e4,SERVER_ERROR_CODE_RANGE:()=>wS,STANDARD_ERROR_MAP:()=>xh,formatErrorMessage:()=>HX,formatJsonRpcError:()=>la,formatJsonRpcRequest:()=>dr,formatJsonRpcResult:()=>bo,getBigIntRpcId:()=>_n,getError:()=>vS,getErrorByCode:()=>ES,isHttpUrl:()=>TS,isJsonRpcError:()=>Ir,isJsonRpcPayload:()=>Mk,isJsonRpcRequest:()=>Hc,isJsonRpcResponse:()=>ua,isJsonRpcResult:()=>Jr,isJsonRpcValidationInvalid:()=>GOe,isLocalhostUrl:()=>Lk,isNodeJs:()=>LX,isReservedErrorCode:()=>xS,isServerErrorCode:()=>HOe,isValidDefaultRoute:()=>CS,isValidErrorCode:()=>PX,isValidLeadingWildcardRoute:()=>jOe,isValidRoute:()=>VOe,isValidTrailingWildcardRoute:()=>qOe,isValidWildcardRoute:()=>SS,isWsUrl:()=>_S,parseConnectionError:()=>r4,payloadId:()=>Tn,validateJsonRpcError:()=>$Oe});var $c=b(()=>{l();bS();Bk();MX();Bo(vi,wo);$X();FX();VX();qX();WX()});var KX,da,cw=b(()=>{l();KX=Ht(ks());$c();da=class extends o4{constructor(t){super(t),this.events=new KX.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async request(t,r){return this.requestStrict(dr(t.method,t.params||[],t.id||_n().toString()),r)}async requestStrict(t,r){return new Promise(async(n,o)=>{if(!this.connection.connected)try{await this.open()}catch(s){o(s)}this.events.on(`${t.id}`,s=>{Ir(s)?o(s.error):n(s.result)});try{await this.connection.send(t,r)}catch(s){o(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),ua(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}});var GX=_e((hht,ZX)=>{"use strict";l();ZX.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var QX,YOe,JOe,YX,JX,QOe,lw,Hk=b(()=>{l();QX=Ht(ks());R1();$c();YOe=()=>typeof m<"u"?m:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:GX(),JOe=()=>typeof m<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",YX=e=>e.split("?")[0],JX=10,QOe=YOe(),lw=class{constructor(t){if(this.url=t,this.events=new QX.EventEmitter,this.registering=!1,!_S(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(yi(t))}catch(r){this.onError(t.id,r)}}register(t=this.url){if(!_S(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,o)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),o(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return o(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=t,this.registering=!0,new Promise((r,n)=>{let o=(0,vi.isReactNative)()?void 0:{rejectUnauthorized:!Lk(t)},s=new QOe(t,[],o);JOe()?s.onerror=i=>{let a=i;n(this.emitError(a.error))}:s.on("error",i=>{n(this.emitError(i))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(t){t.onmessage=r=>this.onPayload(r),t.onclose=r=>this.onClose(r),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;let r=typeof t.data=="string"?Fs(t.data):t.data;this.events.emit("payload",r)}onError(t,r){let n=this.parseError(r),o=n.message||n.toString(),s=la(t,o);this.events.emit("payload",s)}parseError(t,r=this.url){return r4(t,YX(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>JX&&this.events.setMaxListeners(JX)}emitError(t){let r=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${YX(this.url)}`));return this.events.emit("register_error",r),r}}});var Nee=_e((_h,Pee)=>{l();var eI=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,tI=(function(){function e(){this.fetch=!1,this.DOMException=eI.DOMException}return e.prototype=eI,new e})();(function(e){var t=(function(r){var n=typeof e<"u"&&e||typeof self<"u"&&self||typeof global<"u"&&global||{},o={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function s(P){return P&&DataView.prototype.isPrototypeOf(P)}if(o.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=ArrayBuffer.isView||function(P){return P&&i.indexOf(Object.prototype.toString.call(P))>-1};function c(P){if(typeof P!="string"&&(P=String(P)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(P)||P==="")throw new TypeError('Invalid character in header field name: "'+P+'"');return P.toLowerCase()}function u(P){return typeof P!="string"&&(P=String(P)),P}function d(P){var R={next:function(){var I=P.shift();return{done:I===void 0,value:I}}};return o.iterable&&(R[Symbol.iterator]=function(){return R}),R}function f(P){this.map={},P instanceof f?P.forEach(function(R,I){this.append(I,R)},this):Array.isArray(P)?P.forEach(function(R){if(R.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+R.length);this.append(R[0],R[1])},this):P&&Object.getOwnPropertyNames(P).forEach(function(R){this.append(R,P[R])},this)}f.prototype.append=function(P,R){P=c(P),R=u(R);var I=this.map[P];this.map[P]=I?I+", "+R:R},f.prototype.delete=function(P){delete this.map[c(P)]},f.prototype.get=function(P){return P=c(P),this.has(P)?this.map[P]:null},f.prototype.has=function(P){return this.map.hasOwnProperty(c(P))},f.prototype.set=function(P,R){this.map[c(P)]=u(R)},f.prototype.forEach=function(P,R){for(var I in this.map)this.map.hasOwnProperty(I)&&P.call(R,this.map[I],I,this)},f.prototype.keys=function(){var P=[];return this.forEach(function(R,I){P.push(I)}),d(P)},f.prototype.values=function(){var P=[];return this.forEach(function(R){P.push(R)}),d(P)},f.prototype.entries=function(){var P=[];return this.forEach(function(R,I){P.push([I,R])}),d(P)},o.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);function p(P){if(!P._noBody){if(P.bodyUsed)return Promise.reject(new TypeError("Already read"));P.bodyUsed=!0}}function h(P){return new Promise(function(R,I){P.onload=function(){R(P.result)},P.onerror=function(){I(P.error)}})}function y(P){var R=new FileReader,I=h(R);return R.readAsArrayBuffer(P),I}function w(P){var R=new FileReader,I=h(R),B=/charset=([A-Za-z0-9_-]+)/.exec(P.type),C=B?B[1]:"utf-8";return R.readAsText(P,C),I}function x(P){for(var R=new Uint8Array(P),I=new Array(R.length),B=0;B-1?R:P}function _(P,R){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');R=R||{};var I=R.body;if(P instanceof _){if(P.bodyUsed)throw new TypeError("Already read");this.url=P.url,this.credentials=P.credentials,R.headers||(this.headers=new f(P.headers)),this.method=P.method,this.mode=P.mode,this.signal=P.signal,!I&&P._bodyInit!=null&&(I=P._bodyInit,P.bodyUsed=!0)}else this.url=String(P);if(this.credentials=R.credentials||this.credentials||"same-origin",(R.headers||!this.headers)&&(this.headers=new f(R.headers)),this.method=S(R.method||this.method||"GET"),this.mode=R.mode||this.mode||null,this.signal=R.signal||this.signal||(function(){if("AbortController"in n){var A=new AbortController;return A.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(R.cache==="no-store"||R.cache==="no-cache")){var B=/([?&])_=[^&]*/;if(B.test(this.url))this.url=this.url.replace(B,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function O(P){var R=new FormData;return P.trim().split("&").forEach(function(I){if(I){var B=I.split("="),C=B.shift().replace(/\+/g," "),A=B.join("=").replace(/\+/g," ");R.append(decodeURIComponent(C),decodeURIComponent(A))}}),R}function D(P){var R=new f,I=P.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(B){return B.indexOf(` +`)===0?B.substr(1,B.length):B}).forEach(function(B){var C=B.split(":"),A=C.shift().trim();if(A){var U=C.join(":").trim();try{R.append(A,U)}catch(H){console.warn("Response "+H.message)}}}),R}T.call(_.prototype);function M(P,R){if(!(this instanceof M))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(R||(R={}),this.type="default",this.status=R.status===void 0?200:R.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=R.statusText===void 0?"":""+R.statusText,this.headers=new f(R.headers),this.url=R.url||"",this._initBody(P)}T.call(M.prototype),M.prototype.clone=function(){return new M(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},M.error=function(){var P=new M(null,{status:200,statusText:""});return P.ok=!1,P.status=0,P.type="error",P};var N=[301,302,303,307,308];M.redirect=function(P,R){if(N.indexOf(R)===-1)throw new RangeError("Invalid status code");return new M(null,{status:R,headers:{location:P}})},r.DOMException=n.DOMException;try{new r.DOMException}catch{r.DOMException=function(R,I){this.message=R,this.name=I;var B=Error(R);this.stack=B.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function L(P,R){return new Promise(function(I,B){var C=new _(P,R);if(C.signal&&C.signal.aborted)return B(new r.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function U(){A.abort()}A.onload=function(){var F={statusText:A.statusText,headers:D(A.getAllResponseHeaders()||"")};C.url.indexOf("file://")===0&&(A.status<200||A.status>599)?F.status=200:F.status=A.status,F.url="responseURL"in A?A.responseURL:F.headers.get("X-Request-URL");var j="response"in A?A.response:A.responseText;setTimeout(function(){I(new M(j,F))},0)},A.onerror=function(){setTimeout(function(){B(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){B(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){B(new r.DOMException("Aborted","AbortError"))},0)};function H(F){try{return F===""&&n.location.href?n.location.href:F}catch{return F}}if(A.open(C.method,H(C.url),!0),C.credentials==="include"?A.withCredentials=!0:C.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(o.blob?A.responseType="blob":o.arrayBuffer&&(A.responseType="arraybuffer")),R&&typeof R.headers=="object"&&!(R.headers instanceof f||n.Headers&&R.headers instanceof n.Headers)){var k=[];Object.getOwnPropertyNames(R.headers).forEach(function(F){k.push(c(F)),A.setRequestHeader(F,u(R.headers[F]))}),C.headers.forEach(function(F,j){k.indexOf(j)===-1&&A.setRequestHeader(j,F)})}else C.headers.forEach(function(F,j){A.setRequestHeader(j,F)});C.signal&&(C.signal.addEventListener("abort",U),A.onreadystatechange=function(){A.readyState===4&&C.signal.removeEventListener("abort",U)}),A.send(typeof C._bodyInit>"u"?null:C._bodyInit)})}return L.polyfill=!0,n.fetch||(n.fetch=L,n.Headers=f,n.Request=_,n.Response=M),r.Headers=f,r.Request=_,r.Response=M,r.fetch=L,Object.defineProperty(r,"__esModule",{value:!0}),r})({})})(tI);tI.fetch.ponyfill=!0;delete tI.fetch.polyfill;var bw=eI.fetch?eI:tI;_h=bw.fetch;_h.default=bw.fetch;_h.fetch=bw.fetch;_h.Headers=bw.Headers;_h.Request=bw.Request;_h.Response=bw.Response;Pee.exports=_h});var Lee,yU,KBe,ZBe,GBe,Ree,YBe,JBe,Oee,Bee,kee,QBe,XBe,Uee,Dee,Ja,rI=b(()=>{l();Lee=Ht(ks()),yU=Ht(Nee());R1();$c();KBe=Object.defineProperty,ZBe=Object.defineProperties,GBe=Object.getOwnPropertyDescriptors,Ree=Object.getOwnPropertySymbols,YBe=Object.prototype.hasOwnProperty,JBe=Object.prototype.propertyIsEnumerable,Oee=(e,t,r)=>t in e?KBe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Bee=(e,t)=>{for(var r in t||(t={}))YBe.call(t,r)&&Oee(e,r,t[r]);if(Ree)for(var r of Ree(t))JBe.call(t,r)&&Oee(e,r,t[r]);return e},kee=(e,t)=>ZBe(e,GBe(t)),QBe={Accept:"application/json","Content-Type":"application/json"},XBe="POST",Uee={headers:QBe,method:XBe},Dee=10,Ja=class{constructor(t,r=!1){if(this.url=t,this.disableProviderPing=r,this.events=new Lee.EventEmitter,this.isAvailable=!1,this.registering=!1,!TS(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{let r=yi(t),n=await(await(0,yU.default)(this.url,kee(Bee({},Uee),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(t.id,r)}}async register(t=this.url){if(!TS(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,o)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),o(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return o(new Error("HTTP connection is missing or invalid"));n()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){let r=yi({id:1,jsonrpc:"2.0",method:"test",params:[]});await(0,yU.default)(t,kee(Bee({},Uee),{body:r}))}this.onOpen()}catch(r){let n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;let r=typeof t.data=="string"?Fs(t.data):t.data;this.events.emit("payload",r)}onError(t,r){let n=this.parseError(r),o=n.message||n.toString(),s=la(t,o);this.events.emit("payload",s)}parseError(t,r=this.url){return r4(t,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Dee&&this.events.setMaxListeners(Dee)}}});var l4,ete=b(()=>{l();l4={isLowerCaseMatch(e,t){return e?.toLowerCase()===t?.toLowerCase()}}});var Z,u4=b(()=>{l();Z={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:typeof process<"u"&&!1,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"}});var V1,sI,tte=b(()=>{l();u4();V1={caipNetworkIdToNumber(e){return e?Number(e.split(":")[1]):void 0},parseEvmChainId(e){return typeof e=="string"?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace(e,t){return e?.filter(r=>r.chainNamespace===t)||[]},getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;let r=e.find(o=>o.caipNetworkId===t);if(r)return r.name;let[n]=t.split(":");return Z.CHAIN_NAME_MAP?.[n]||void 0}},sI=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"]});function ote(){function e(t){var r=this;if(!(r instanceof e))return t===Wl?ote():new e(t);if(t instanceof e)r.s=t.s,r.e=t.e,r.c=t.c.slice();else{if(typeof t!="string"){if(e.strict===!0&&typeof t!="bigint")throw TypeError(q1+"value");t=t===0&&1/t<0?"-0":String(t)}Cke(r,t)}r.constructor=e}return e.prototype=yr,e.DP=yke,e.RM=wke,e.NE=bke,e.PE=xke,e.strict=vke,e.roundDown=0,e.roundHalfUp=1,e.roundHalfEven=2,e.roundUp=3,e}function Cke(e,t){var r,n,o;if(!Ake.test(t))throw Error(q1+"number");for(e.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),o=t.length,n=0;n0&&t.charAt(--o)=="0";);for(e.e=r-n-1,e.c=[],r=0;n<=o;)e.c[r++]=+t.charAt(n++)}return e}function W1(e,t,r,n){var o=e.c;if(r===Wl&&(r=e.constructor.RM),r!==0&&r!==1&&r!==2&&r!==3)throw Error(Eke);if(t<1)n=r===3&&(n||!!o[0])||t===0&&(r===1&&o[0]>=5||r===2&&(o[0]>5||o[0]===5&&(n||o[1]!==Wl))),o.length=1,n?(e.e=e.e-t+1,o[0]=1):o[0]=e.e=0;else if(t=5||r===2&&(o[t]>5||o[t]===5&&(n||o[t+1]!==Wl||o[t-1]&1))||r===3&&(n||!!o[0]),o.length=t,n){for(;++o[--t]>9;)if(o[t]=0,t===0){++e.e,o.unshift(1);break}}for(t=o.length;!o[--t];)o.pop()}return e}function K1(e,t,r){var n=e.e,o=e.c.join(""),s=o.length;if(t)o=o.charAt(0)+(s>1?"."+o.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)o="0"+o;o="0."+o}else if(n>0)if(++n>s)for(n-=s;n--;)o+="0";else n1&&(o=o.charAt(0)+"."+o.slice(1));return e.s<0&&r?"-"+o:o}var yke,wke,j1,rte,bke,xke,vke,d4,q1,iI,Eke,nte,yr,Wl,Ake,Ske,Vc,ste=b(()=>{l();yke=20,wke=1,j1=1e6,rte=1e6,bke=-7,xke=21,vke=!1,d4="[big.js] ",q1=d4+"Invalid ",iI=q1+"decimal places",Eke=q1+"rounding mode",nte=d4+"Division by zero",yr={},Wl=void 0,Ake=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;yr.abs=function(){var e=new this.constructor(this);return e.s=1,e};yr.cmp=function(e){var t,r=this,n=r.c,o=(e=new r.constructor(e)).c,s=r.s,i=e.s,a=r.e,c=e.e;if(!n[0]||!o[0])return n[0]?s:o[0]?-i:0;if(s!=i)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(i=(a=n.length)<(c=o.length)?a:c,s=-1;++so[s]^t?1:-1;return a==c?0:a>c^t?1:-1};yr.div=function(e){var t=this,r=t.constructor,n=t.c,o=(e=new r(e)).c,s=t.s==e.s?1:-1,i=r.DP;if(i!==~~i||i<0||i>j1)throw Error(iI);if(!o[0])throw Error(nte);if(!n[0])return e.s=s,e.c=[e.e=0],e;var a,c,u,d,f,p=o.slice(),h=a=o.length,y=n.length,w=n.slice(0,a),x=w.length,v=e,T=v.c=[],E=0,S=i+(v.e=t.e-e.e)+1;for(v.s=s,s=S<0?0:S,p.unshift(0);x++x?1:-1;else for(f=-1,d=0;++fw[f]?1:-1;break}if(d<0){for(c=x==a?o:p;x;){if(w[--x]S&&W1(v,S,r.RM,w[0]!==Wl),v};yr.eq=function(e){return this.cmp(e)===0};yr.gt=function(e){return this.cmp(e)>0};yr.gte=function(e){return this.cmp(e)>-1};yr.lt=function(e){return this.cmp(e)<0};yr.lte=function(e){return this.cmp(e)<1};yr.minus=yr.sub=function(e){var t,r,n,o,s=this,i=s.constructor,a=s.s,c=(e=new i(e)).s;if(a!=c)return e.s=-c,s.plus(e);var u=s.c.slice(),d=s.e,f=e.c,p=e.e;if(!u[0]||!f[0])return f[0]?e.s=-c:u[0]?e=new i(s):e.s=1,e;if(a=d-p){for((o=a<0)?(a=-a,n=u):(p=d,n=f),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(r=((o=u.length0)for(;c--;)u[t++]=0;for(c=t;r>a;){if(u[--r]0?(c=i,n=u):(t=-t,n=a),n.reverse();t--;)n.push(0);n.reverse()}for(a.length-u.length<0&&(n=u,u=a,a=n),t=u.length,r=0;t;a[t]%=10)r=(a[--t]=a[t]+u[t]+r)/10|0;for(r&&(a.unshift(r),++c),t=a.length;a[--t]===0;)a.pop();return e.c=a,e.e=c,e};yr.pow=function(e){var t=this,r=new t.constructor("1"),n=r,o=e<0;if(e!==~~e||e<-rte||e>rte)throw Error(q1+"exponent");for(o&&(e=-e);e&1&&(n=n.times(t)),e>>=1,!!e;)t=t.times(t);return o?r.div(n):n};yr.prec=function(e,t){if(e!==~~e||e<1||e>j1)throw Error(q1+"precision");return W1(new this.constructor(this),e,t)};yr.round=function(e,t){if(e===Wl)e=0;else if(e!==~~e||e<-j1||e>j1)throw Error(iI);return W1(new this.constructor(this),e+this.e+1,t)};yr.sqrt=function(){var e,t,r,n=this,o=n.constructor,s=n.s,i=n.e,a=new o("0.5");if(!n.c[0])return new o(n);if(s<0)throw Error(d4+"No square root");s=Math.sqrt(+K1(n,!0,!0)),s===0||s===1/0?(t=n.c.join(""),t.length+i&1||(t+="0"),s=Math.sqrt(t),i=((i+1)/2|0)-(i<0||i&1),e=new o((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+i)):e=new o(s+""),i=e.e+(o.DP+=4);do r=e,e=a.times(r.plus(n.div(r)));while(r.c.slice(0,i).join("")!==e.c.slice(0,i).join(""));return W1(e,(o.DP-=4)+e.e+1,o.RM)};yr.times=yr.mul=function(e){var t,r=this,n=r.constructor,o=r.c,s=(e=new n(e)).c,i=o.length,a=s.length,c=r.e,u=e.e;if(e.s=r.s==e.s?1:-1,!o[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+u,ic;)a=t[u]+s[c]*o[u-c-1]+a,t[u--]=a%10,a=a/10|0;t[u]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e};yr.toExponential=function(e,t){var r=this,n=r.c[0];if(e!==Wl){if(e!==~~e||e<0||e>j1)throw Error(iI);for(r=W1(new r.constructor(r),++e,t);r.c.lengthj1)throw Error(iI);for(r=W1(new r.constructor(r),e+r.e+1,t),e=e+r.e+1;r.c.length=t.PE,!!e.c[0])};yr.toNumber=function(){var e=+K1(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(e.toString()))throw Error(d4+"Imprecise conversion");return e};yr.toPrecision=function(e,t){var r=this,n=r.constructor,o=r.c[0];if(e!==Wl){if(e!==~~e||e<1||e>j1)throw Error(q1+"precision");for(r=W1(new n(r),e,t);r.c.length=n.PE,!!o)};yr.valueOf=function(){var e=this,t=e.constructor;if(t.strict===!0)throw Error(d4+"valueOf disallowed");return K1(e,e.e<=t.NE||e.e>=t.PE,!0)};Ske=ote(),Vc=Ske});var ht,ite=b(()=>{l();ste();ht={bigNumber(e,t={safe:!1}){try{return e?new Vc(e):new Vc(0)}catch(r){if(t.safe)return new Vc(0);throw r}},formatNumber(e,t){let{decimals:r,round:n=8,safe:o=!0}=t;return ht.bigNumber(e,{safe:o}).div(new Vc(10).pow(r)).round(n)},multiply(e,t){if(e===void 0||t===void 0)return new Vc(0);let r=new Vc(e),n=new Vc(t);return r.times(n)},toFixed(e,t=2){return e===void 0||e===""?new Vc(0).toFixed(t):new Vc(e).toFixed(t)},formatNumberToLocalString(e,t=2){return e===void 0||e===""?"0.00":typeof e=="number"?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"})},parseLocalStringToNumber(e){if(e===void 0||e==="")return 0;let t=e.replace(/,/gu,"");return new Vc(t).toNumber()}}});var ate,cte=b(()=>{l();ate=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]});var lte,ute=b(()=>{l();lte=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]});var dte,fte=b(()=>{l();dte=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]});var f4,pte=b(()=>{l();cte();ute();fte();u4();f4={getERC20Abi:e=>Z.USDT_CONTRACT_ADDRESSES.includes(e)?dte:ate,getSwapAbi:()=>lte}});var Ph,hte=b(()=>{l();u4();Ph={ConnectorExplorerIds:{[Z.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[Z.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[Z.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Z.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Z.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Z.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Z.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Z.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Z.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Z.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Z.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Z.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Z.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Z.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Z.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Z.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"},ConnectorImageIds:{[Z.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[Z.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[Z.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[Z.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[Z.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[Z.CONNECTOR_ID.INJECTED]:"Browser Wallet",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[Z.CONNECTOR_ID.COINBASE]:"Coinbase",[Z.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[Z.CONNECTOR_ID.LEDGER]:"Ledger",[Z.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[Z.CONNECTOR_ID.INJECTED]:"INJECTED",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[Z.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[Z.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]}});var lt,mte=b(()=>{l();lt={validateCaipAddress(e){if(e.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){let t=e.split(":");if(t.length!==3)throw new Error(`Invalid CAIP-10 address: ${e}`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:r,chainId:n,address:o}},parseCaipNetworkId(e){let t=e.split(":");if(t.length!==2)throw new Error(`Invalid CAIP-2 network id: ${e}`);let[r,n]=t;if(!r||!n)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:r,chainId:n}}}});var js,IU,Z1,gte=b(()=>{l();js={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if(typeof e=="object"&&e!==null){let t=e,r=typeof t.message=="string",n=typeof t.code=="number";return r&&n}return!1}catch{return!1}},isUserRejectedMessage(e){return e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled")},isUserRejectedRequestError(e){if(js.isRpcProviderError(e)){let t=e.code===js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,r=e.code===js.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||r||js.isUserRejectedMessage(e.message)}return e instanceof Error?js.isUserRejectedMessage(e.message):!1}},IU=class extends Error{constructor(t,r){super(r.message,{cause:t}),this.name=js.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=r.code}},Z1=class extends IU{constructor(t){super(t,{code:js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}});function p4(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}function G1(){return typeof window<"u"&&typeof localStorage<"u"}var Fe,Le,yte=b(()=>{l();Fe={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};Le={setItem(e,t){G1()&&t!==void 0&&localStorage.setItem(e,t)},getItem(e){if(G1())return localStorage.getItem(e)||void 0},removeItem(e){G1()&&localStorage.removeItem(e)},clear(){G1()&&localStorage.clear()}}});function Y1(e,t){let r=e?.["--apkt-accent"]??e?.["--w3m-accent"];return t==="light"?{"--w3m-accent":r||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":r||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}var wte=b(()=>{l()});var ut=b(()=>{l();ete();tte();ite();pte();u4();hte();mte();gte();yte();wte()});var Ike,bte,TU,Tke,xte,_U,vte=b(()=>{l();Ike=Symbol(),bte=Object.getPrototypeOf,TU=new WeakMap,Tke=e=>e&&(TU.has(e)?TU.get(e):bte(e)===Object.prototype||bte(e)===Array.prototype),xte=e=>Tke(e)&&e[Ike]||null,_U=(e,t=!0)=>{TU.set(e,t)}});function rt(e={}){if(!NU(e))throw new Error("object required");let t=h4.get(e);if(t)return t;let r=aI[0],n=new Set,o=(x,v=++aI[0])=>{r!==v&&(s=r=v,n.forEach(T=>T(x,v)))},s=r,i=(x=aI[0])=>(s!==x&&(s=x,c.forEach(([v])=>{let T=v[1](x);T>r&&(r=T)})),r),a=x=>(v,T)=>{let E=[...v];E[1]=[x,...E[1]],o(E,T)},c=new Map,u=(x,v)=>{let T=!m4.has(v)&&Nh.get(v);if(T){if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&c.has(x))throw new Error("prop listener already exists");if(n.size){let E=T[2](a(x));c.set(x,[T,E])}else c.set(x,[T])}},d=x=>{var v;let T=c.get(x);T&&(c.delete(x),(v=T[1])==null||v.call(T))},f=x=>(n.add(x),n.size===1&&c.forEach(([T,E],S)=>{if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&E)throw new Error("remove already exists");let _=T[2](a(S));c.set(S,[T,_])}),()=>{n.delete(x),n.size===0&&c.forEach(([T,E],S)=>{E&&(E(),c.set(S,[T]))})}),p=!0,h=Bke(()=>p,u,d,o),y=Nke(e,h);h4.set(e,y);let w=[e,i,f];return Nh.set(y,w),Reflect.ownKeys(e).forEach(x=>{let v=Object.getOwnPropertyDescriptor(e,x);"value"in v&&v.writable&&(y[x]=e[x])}),p=!1,y}function Dt(e,t,r){let n=Nh.get(e);(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!n&&console.warn("Please use proxy object");let o,s=[],i=n[2],a=!1,u=i(d=>{if(s.push(d),r){t(s.splice(0));return}o||(o=Promise.resolve().then(()=>{o=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,u()}}function Kl(e){let t=Nh.get(e);(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!t&&console.warn("Please use proxy object");let[r,n]=t;return Oke(r,n())}function vf(e){return m4.add(e),e}function RU(){return{proxyStateMap:Nh,refSet:m4,snapCache:PU,versionHolder:aI,proxyCache:h4}}var NU,_ke,Ate,Pke,Nh,m4,PU,aI,h4,Ete,Nke,Rke,Oke,Bke,Lr=b(()=>{l();vte();NU=e=>typeof e=="object"&&e!==null,_ke=e=>NU(e)&&!m4.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),Ate=(e,t)=>{let r=PU.get(e);if(r?.[0]===t)return r[1];let n=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return _U(n,!0),PU.set(e,[t,n]),Reflect.ownKeys(e).forEach(o=>{if(Object.getOwnPropertyDescriptor(n,o))return;let s=Reflect.get(e,o),{enumerable:i}=Reflect.getOwnPropertyDescriptor(e,o),a={value:s,enumerable:i,configurable:!0};if(m4.has(s))_U(s,!1);else if(Nh.has(s)){let[c,u]=Nh.get(s);a.value=Ate(c,u())}Object.defineProperty(n,o,a)}),Object.preventExtensions(n)},Pke=(e,t,r,n)=>({deleteProperty(o,s){let i=Reflect.get(o,s);r(s);let a=Reflect.deleteProperty(o,s);return a&&n(["delete",[s],i]),a},set(o,s,i,a){let c=!e()&&Reflect.has(o,s),u=Reflect.get(o,s,a);if(c&&(Ete(u,i)||h4.has(i)&&Ete(u,h4.get(i))))return!0;r(s),NU(i)&&(i=xte(i)||i);let d=!Nh.has(i)&&Rke(i)?rt(i):i;return t(s,d),Reflect.set(o,s,d,a),n(["set",[s],i,u]),!0}}),Nh=new WeakMap,m4=new WeakSet,PU=new WeakMap,aI=[1],h4=new WeakMap,Ete=Object.is,Nke=(e,t)=>new Proxy(e,t),Rke=_ke,Oke=Ate,Bke=Pke});function Tt(e,t,r,n){let o=e[t];return Dt(e,()=>{let s=e[t];Object.is(o,s)||r(o=s)},n)}function Cte(e){let t=[],r=0,n=new Map,o=new WeakMap,s=()=>{let u=Uke.get(a),d=u?.[1];if(d&&!o.has(d)){let f=new Map(n);o.set(d,f)}},i=u=>o.get(u)||n;if(e){if(typeof e[Symbol.iterator]!="function")throw new TypeError(`proxyMap: + initial state must be iterable + tip: structure should be [[key, value]]`);for(let[u,d]of e)n.set(u,r),t[r++]=d}let a={data:t,index:r,epoch:0,get size(){return cI(this)||s(),i(this).size},get(u){let f=i(this).get(u);if(f===void 0){this.epoch;return}return this.data[f]},has(u){let d=i(this);return this.epoch,d.has(u)},set(u,d){if(!cI(this))throw new Error("Cannot perform mutations on a snapshot");let f=n.get(u);return f===void 0?(n.set(u,this.index),this.data[this.index++]=d):this.data[f]=d,this.epoch++,this},delete(u){if(!cI(this))throw new Error("Cannot perform mutations on a snapshot");let d=n.get(u);return d===void 0?!1:(delete this.data[d],n.delete(u),this.epoch++,!0)},clear(){if(!cI(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(u){this.epoch,i(this).forEach((f,p)=>{u(this.data[f],p,this)})},*entries(){this.epoch;let u=i(this);for(let[d,f]of u)yield[d,this.data[f]]},*keys(){this.epoch;let u=i(this);for(let d of u.keys())yield d},*values(){this.epoch;let u=i(this);for(let d of u.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=rt(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}var kke,Uke,cI,U1t,D1t,Hn=b(()=>{l();Lr();({proxyStateMap:kke,snapCache:Uke}=RU()),cI=e=>kke.has(e);({proxyStateMap:U1t,snapCache:D1t}=RU())});var OU,BU,Ste,Ye,ha=b(()=>{l();ut();OU=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",BU=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Ste="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ye={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:OU,SECURE_SITE_DASHBOARD:`${OU}/dashboard`,SECURE_SITE_FAVICON:`${OU}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD\u20AE0"]},BALANCE_SUPPORTED_CHAINS:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[Z.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[Z.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[Ph.ConnectorExplorerIds[Z.CONNECTOR_ID.COINBASE],Ph.ConnectorExplorerIds[Z.CONNECTOR_ID.COINBASE_SDK],Ph.ConnectorExplorerIds[Z.CONNECTOR_ID.BASE_ACCOUNT],Ph.ConnectorExplorerIds[Z.SOLFLARE_CONNECTOR_NAME],Ph.ConnectorExplorerIds[Z.PHANTOM_CONNECTOR_NAME],Ph.ConnectorExplorerIds[Z.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]}});var de,ma=b(()=>{l();ut();de={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired(e,t){return Date.now()-e>t},getActiveNetworkProps(){let e=de.getActiveNamespace(),t=de.getActiveCaipNetworkId(),r=t?t.split(":")[1]:void 0,n=r?isNaN(Number(r))?r:Number(r):void 0;return{namespace:e,caipNetworkId:t,chainId:n}},setWalletConnectDeepLink({name:e,href:t}){try{Le.setItem(Fe.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{let e=Le.getItem(Fe.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Le.removeItem(Fe.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{Le.setItem(Fe.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{Le.setItem(Fe.ACTIVE_CAIP_NETWORK_ID,e),de.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Le.getItem(Fe.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Le.removeItem(Fe.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{let t=p4(e);Le.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{let t=de.getRecentWallets();t.find(n=>n.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Le.setItem(Fe.RECENT_WALLETS,JSON.stringify(t)),Le.setItem(Fe.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{let e=Le.getItem(Fe.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{let e=Le.getItem(Fe.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Le.removeItem(Fe.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{let r=p4(e);Le.setItem(r,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Le.getItem(Fe.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{let t=p4(e);return Le.getItem(t)}catch{console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{Le.setItem(Fe.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Le.getItem(Fe.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Le.removeItem(Fe.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Le.getItem(Fe.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Le.getItem(Fe.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(e){try{Le.setItem(Fe.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Le.getItem(Fe.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{let e=Le.getItem(Fe.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{let t=Array.from(new Set(e));Le.setItem(Fe.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{let t=de.getConnectedNamespaces();t.includes(e)||(t.push(e),de.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{let t=de.getConnectedNamespaces(),r=t.indexOf(e);r>-1&&(t.splice(r,1),de.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Le.getItem(Fe.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{Le.setItem(Fe.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Le.removeItem(Fe.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{let t=Le.getItem(Fe.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{let t=de.getBalanceCache();Le.setItem(Fe.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{let r=de.getBalanceCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.portfolio))return r.balance;de.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{let t=de.getBalanceCache();t[e.caipAddress]=e,Le.setItem(Fe.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{let t=Le.getItem(Fe.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{let t=de.getBalanceCache();Le.setItem(Fe.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{let r=de.getNativeBalanceCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.nativeBalance))return r;console.info("Discarding cache for address",e),de.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{let t=de.getNativeBalanceCache();t[e.caipAddress]=e,Le.setItem(Fe.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{let t=Le.getItem(Fe.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{let r=de.getEnsCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.ens))return r.ens;de.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{let t=de.getEnsCache();t[e.address]=e,Le.setItem(Fe.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{let t=de.getEnsCache();Le.setItem(Fe.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{let t=Le.getItem(Fe.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{let r=de.getIdentityCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.identity))return r.identity;de.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{let t=de.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Le.setItem(Fe.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{let t=de.getIdentityCache();Le.setItem(Fe.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{let e=Le.getItem(Fe.TON_WALLETS_CACHE),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;de.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{let t=de.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=new Date().getTime(),t.wallets=e,Le.setItem(Fe.TON_WALLETS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{Le.removeItem(Fe.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{Le.removeItem(Fe.PORTFOLIO_CACHE),Le.removeItem(Fe.NATIVE_BALANCE_CACHE),Le.removeItem(Fe.ENS_CACHE),Le.removeItem(Fe.IDENTITY_CACHE),Le.removeItem(Fe.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{Le.setItem(Fe.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{let e=Le.getItem(Fe.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{let r=de.getConnections(),n=r[t]??[],o=new Map;for(let i of n)o.set(i.connectorId,{...i});for(let i of e){let a=o.get(i.connectorId),c=i.connectorId===Z.CONNECTOR_ID.AUTH;if(a&&!c){let u=new Set(a.accounts.map(f=>f.address.toLowerCase())),d=i.accounts.filter(f=>!u.has(f.address.toLowerCase()));a.accounts.push(...d)}else o.set(i.connectorId,{...i})}let s={...r,[t]:Array.from(o.values())};Le.setItem(Fe.CONNECTIONS,JSON.stringify(s))}catch(r){console.error("Unable to sync connections to storage",r)}},getConnections(){try{let e=Le.getItem(Fe.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:r}){try{let n=de.getConnections(),o=n[r]??[],s=new Map(o.map(a=>[a.connectorId,a])),i=s.get(e);i&&(i.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase()).length===0?s.delete(e):s.set(e,{...i,accounts:i.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase())})),Le.setItem(Fe.CONNECTIONS,JSON.stringify({...n,[r]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${r}"`)}},getDisconnectedConnectorIds(){try{let e=Le.getItem(Fe.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{let r=de.getDisconnectedConnectorIds(),n=r[t]??[];n.push(e),Le.setItem(Fe.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...r,[t]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{let r=de.getDisconnectedConnectorIds(),n=r[t]??[];n=n.filter(o=>o.toLowerCase()!==e.toLowerCase()),Le.setItem(Fe.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...r,[t]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{return(de.getDisconnectedConnectorIds()[t]??[]).some(o=>o.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{let e=Le.getItem(Fe.HISTORY_TRANSACTIONS_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{let n=de.getTransactionsCache()[e]?.[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.transactionsHistory))return n.transactions;de.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:r,transactions:n}){try{let o=de.getTransactionsCache();o[e]={...o[e],[t]:{timestamp:r,transactions:n}},Le.setItem(Fe.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(o))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:r,transactions:n})}},removeTransactionsCache({address:e,chainId:t}){try{let r=de.getTransactionsCache(),n=r?.[e]||{},{[t]:o,...s}=n;Le.setItem(Fe.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...r,[e]:s}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{let e=Le.getItem(Fe.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{let r=de.getTokenPriceCache()[e.join(",")];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.tokenPrice))return r.tokenPrice;de.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{let t=de.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},Le.setItem(Fe.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{let t=de.getTokenPriceCache();Le.setItem(Fe.TOKEN_PRICE_CACHE,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{let e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{let e=Le.getItem(Fe.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{let t=de.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,Le.setItem(Fe.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}}});var se,$n=b(()=>{l();ut();ha();ma();se={getWindow(){if(!(typeof window>"u"))return window},isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(e,t=""){return e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;let e=window?.navigator.userAgent.toLowerCase();return se.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;let e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(e){return e?e-Date.now()<=Ye.TEN_SEC_MS:!0},isAllowedRetry(e,t=Ye.ONE_SEC_MS){return Date.now()-e>=t},copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(se.isClient()&&window.self!==window.top)try{let e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){let r=new URL(e),n=new URL(t);return r.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ye.FOUR_MINUTES_MS},getNetworkId(e){return e?.split(":")[1]},getPlainAddress(e){return e?.split(":")[2]},async wait(e){return new Promise(t=>{setTimeout(t,e)})},debounce(e,t=500){let r;return(...n)=>{function o(){e(...n)}r&&clearTimeout(r),r=setTimeout(o,t)}},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},formatNativeUrl(e,t,r=null){if(se.isHttpUrl(e))return this.formatUniversalUrl(e,t);let n=e,o=r;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),o&&!o?.endsWith("/")&&(o=`${o}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));let s=encodeURIComponent(t);return{redirect:`${n}wc?uri=${s}`,redirectUniversalLink:o?`${o}wc?uri=${s}`:void 0,href:n}},formatUniversalUrl(e,t){if(!se.isHttpUrl(e))return this.formatNativeUrl(e,t);let r=e;r.endsWith("/")||(r=`${r}/`);let n=encodeURIComponent(t);return{redirect:`${r}wc?uri=${n}`,href:r}},getOpenTargetForPlatform(e){return e==="popupWindow"?e:this.isTelegram()?de.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,r){window?.open(e,this.getOpenTargetForPlatform(t),r||"noreferrer noopener")},returnOpenHref(e,t,r){return window?.open(e,this.getOpenTargetForPlatform(t),r||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;let e=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,t=window?.navigator?.standalone;return!!(e||t)},async preloadImage(e){let t=new Promise((r,n)=>{let o=new Image;o.onload=r,o.onerror=n,o.crossOrigin="anonymous",o.src=e});return Promise.race([t,se.wait(2e3)])},parseBalance(e,t){let r="0.000";if(typeof e=="string"){let c=Number(e);if(!isNaN(c)){let u=(Math.floor(c*1e3)/1e3).toFixed(3);u&&(r=u)}}let[n,o]=r.split("."),s=n||"0",i=o||"000";return{formattedText:`${s}.${i}${t?` ${t}`:""}`,value:s,decimals:i,symbol:t}},getApiUrl(){return Z.W3M_API_URL},getBlockchainApiUrl(){return Z.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return Z.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},parseError(e){return typeof e=="string"?e:typeof e?.issues?.[0]?.message=="string"?e.issues[0].message:e instanceof Error?e.message:"Unknown error"},sortRequestedNetworks(e,t=[]){let r={};return t&&e&&(e.forEach((n,o)=>{r[n]=o}),t.sort((n,o)=>{let s=r[n.id],i=r[o.id];return s!==void 0&&i!==void 0?s-i:s!==void 0?-1:i!==void 0?1:0})),t},calculateBalance(e){let t=0;for(let r of e)t+=r.value??0;return t},formatTokenBalance(e){let t=e.toFixed(2),[r,n]=t.split(".");return{dollars:r,pennies:n}},isAddress(e,t="eip155"){switch(t){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)||/^(?:0x)?[0-9A-F]{40}$/iu.test(e))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);case"bip122":{let r=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),n=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),o=/^bc1[a-z0-9]{39,87}$/u.test(e),s=/^bc1p[a-z0-9]{58}$/u.test(e);return r||n||o||s}default:return!1}},uniqueBy(e,t){let r=new Set;return e.filter(n=>{let o=n[t];return r.has(o)?!1:(r.add(o),!0)})},generateSdkVersion(e,t,r){let o=e.length===0?Ye.ADAPTER_TYPES.UNIVERSAL:e.map(s=>s.adapterType).join(",");return`${t}-${o}-${r}`},createAccount(e,t,r,n,o){return{namespace:e,address:t,type:r,publicKey:n,path:o}},isCaipAddress(e){if(typeof e!="string")return!1;let t=e.split(":"),r=t[0];return t.filter(Boolean).length===3&&r in Z.CHAIN_NAME_MAP},getAccount(e){return e?typeof e=="string"?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0}},isMac(){let e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){let t=`--${encodeURIComponent(window?.location.href)}`,r="state=";if(new URL(e).host==="auth.magic.link"){let o="provider_authorization_url=",s=e.substring(e.indexOf(o)+o.length),i=this.injectIntoUrl(decodeURIComponent(s),r,t);return e.replace(s,encodeURIComponent(i))}return this.injectIntoUrl(e,r,t)},injectIntoUrl(e,t,r){let n=e.indexOf(t);if(n===-1)throw new Error(`${t} parameter not found in the URL: ${e}`);let o=e.indexOf("&",n),s=t.length,i=o!==-1?o:e.length,a=e.substring(0,n+s),c=e.substring(n+s,i),u=e.substring(o),d=c+r;return a+d+u},isNumber(e){return typeof e!="number"&&typeof e!="string"?!1:!isNaN(Number(e))}}});var Dke,Y1t,J1t,Q1t,Qa,Kr,g4=b(()=>{l();Dke="https://secure.walletconnect.org/sdk",Y1t=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL:void 0)||Dke,J1t=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL:void 0)||"error",Q1t=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION:void 0)||"4",Qa={APP_EVENT_KEY:"@w3m-app/",FRAME_EVENT_KEY:"@w3m-frame/",RPC_METHOD_KEY:"RPC_",STORAGE_KEY:"@appkit-wallet/",SESSION_TOKEN_KEY:"SESSION_TOKEN_KEY",EMAIL_LOGIN_USED_KEY:"EMAIL_LOGIN_USED_KEY",LAST_USED_CHAIN_KEY:"LAST_USED_CHAIN_KEY",LAST_EMAIL_LOGIN_TIME:"LAST_EMAIL_LOGIN_TIME",EMAIL:"EMAIL",PREFERRED_ACCOUNT_TYPE:"PREFERRED_ACCOUNT_TYPE",SMART_ACCOUNT_ENABLED:"SMART_ACCOUNT_ENABLED",SMART_ACCOUNT_ENABLED_NETWORKS:"SMART_ACCOUNT_ENABLED_NETWORKS",SOCIAL_USERNAME:"SOCIAL_USERNAME",APP_SWITCH_NETWORK:"@w3m-app/SWITCH_NETWORK",APP_CONNECT_EMAIL:"@w3m-app/CONNECT_EMAIL",APP_CONNECT_DEVICE:"@w3m-app/CONNECT_DEVICE",APP_CONNECT_OTP:"@w3m-app/CONNECT_OTP",APP_CONNECT_SOCIAL:"@w3m-app/CONNECT_SOCIAL",APP_GET_SOCIAL_REDIRECT_URI:"@w3m-app/GET_SOCIAL_REDIRECT_URI",APP_GET_USER:"@w3m-app/GET_USER",APP_SIGN_OUT:"@w3m-app/SIGN_OUT",APP_IS_CONNECTED:"@w3m-app/IS_CONNECTED",APP_GET_CHAIN_ID:"@w3m-app/GET_CHAIN_ID",APP_RPC_REQUEST:"@w3m-app/RPC_REQUEST",APP_UPDATE_EMAIL:"@w3m-app/UPDATE_EMAIL",APP_UPDATE_EMAIL_PRIMARY_OTP:"@w3m-app/UPDATE_EMAIL_PRIMARY_OTP",APP_UPDATE_EMAIL_SECONDARY_OTP:"@w3m-app/UPDATE_EMAIL_SECONDARY_OTP",APP_AWAIT_UPDATE_EMAIL:"@w3m-app/AWAIT_UPDATE_EMAIL",APP_SYNC_THEME:"@w3m-app/SYNC_THEME",APP_SYNC_DAPP_DATA:"@w3m-app/SYNC_DAPP_DATA",APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS:"@w3m-app/GET_SMART_ACCOUNT_ENABLED_NETWORKS",APP_INIT_SMART_ACCOUNT:"@w3m-app/INIT_SMART_ACCOUNT",APP_SET_PREFERRED_ACCOUNT:"@w3m-app/SET_PREFERRED_ACCOUNT",APP_CONNECT_FARCASTER:"@w3m-app/CONNECT_FARCASTER",APP_GET_FARCASTER_URI:"@w3m-app/GET_FARCASTER_URI",APP_RELOAD:"@w3m-app/RELOAD",APP_RPC_ABORT:"@w3m-app/RPC_ABORT",FRAME_SWITCH_NETWORK_ERROR:"@w3m-frame/SWITCH_NETWORK_ERROR",FRAME_SWITCH_NETWORK_SUCCESS:"@w3m-frame/SWITCH_NETWORK_SUCCESS",FRAME_CONNECT_EMAIL_ERROR:"@w3m-frame/CONNECT_EMAIL_ERROR",FRAME_CONNECT_EMAIL_SUCCESS:"@w3m-frame/CONNECT_EMAIL_SUCCESS",FRAME_CONNECT_DEVICE_ERROR:"@w3m-frame/CONNECT_DEVICE_ERROR",FRAME_CONNECT_DEVICE_SUCCESS:"@w3m-frame/CONNECT_DEVICE_SUCCESS",FRAME_CONNECT_OTP_SUCCESS:"@w3m-frame/CONNECT_OTP_SUCCESS",FRAME_CONNECT_OTP_ERROR:"@w3m-frame/CONNECT_OTP_ERROR",FRAME_CONNECT_SOCIAL_SUCCESS:"@w3m-frame/CONNECT_SOCIAL_SUCCESS",FRAME_CONNECT_SOCIAL_ERROR:"@w3m-frame/CONNECT_SOCIAL_ERROR",FRAME_CONNECT_FARCASTER_SUCCESS:"@w3m-frame/CONNECT_FARCASTER_SUCCESS",FRAME_CONNECT_FARCASTER_ERROR:"@w3m-frame/CONNECT_FARCASTER_ERROR",FRAME_GET_FARCASTER_URI_SUCCESS:"@w3m-frame/GET_FARCASTER_URI_SUCCESS",FRAME_GET_FARCASTER_URI_ERROR:"@w3m-frame/GET_FARCASTER_URI_ERROR",FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_SUCCESS",FRAME_GET_SOCIAL_REDIRECT_URI_ERROR:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_ERROR",FRAME_GET_USER_SUCCESS:"@w3m-frame/GET_USER_SUCCESS",FRAME_GET_USER_ERROR:"@w3m-frame/GET_USER_ERROR",FRAME_SIGN_OUT_SUCCESS:"@w3m-frame/SIGN_OUT_SUCCESS",FRAME_SIGN_OUT_ERROR:"@w3m-frame/SIGN_OUT_ERROR",FRAME_IS_CONNECTED_SUCCESS:"@w3m-frame/IS_CONNECTED_SUCCESS",FRAME_IS_CONNECTED_ERROR:"@w3m-frame/IS_CONNECTED_ERROR",FRAME_GET_CHAIN_ID_SUCCESS:"@w3m-frame/GET_CHAIN_ID_SUCCESS",FRAME_GET_CHAIN_ID_ERROR:"@w3m-frame/GET_CHAIN_ID_ERROR",FRAME_RPC_REQUEST_SUCCESS:"@w3m-frame/RPC_REQUEST_SUCCESS",FRAME_RPC_REQUEST_ERROR:"@w3m-frame/RPC_REQUEST_ERROR",FRAME_SESSION_UPDATE:"@w3m-frame/SESSION_UPDATE",FRAME_UPDATE_EMAIL_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SUCCESS",FRAME_UPDATE_EMAIL_ERROR:"@w3m-frame/UPDATE_EMAIL_ERROR",FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_ERROR",FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_ERROR",FRAME_SYNC_THEME_SUCCESS:"@w3m-frame/SYNC_THEME_SUCCESS",FRAME_SYNC_THEME_ERROR:"@w3m-frame/SYNC_THEME_ERROR",FRAME_SYNC_DAPP_DATA_SUCCESS:"@w3m-frame/SYNC_DAPP_DATA_SUCCESS",FRAME_SYNC_DAPP_DATA_ERROR:"@w3m-frame/SYNC_DAPP_DATA_ERROR",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR",FRAME_INIT_SMART_ACCOUNT_SUCCESS:"@w3m-frame/INIT_SMART_ACCOUNT_SUCCESS",FRAME_INIT_SMART_ACCOUNT_ERROR:"@w3m-frame/INIT_SMART_ACCOUNT_ERROR",FRAME_SET_PREFERRED_ACCOUNT_SUCCESS:"@w3m-frame/SET_PREFERRED_ACCOUNT_SUCCESS",FRAME_SET_PREFERRED_ACCOUNT_ERROR:"@w3m-frame/SET_PREFERRED_ACCOUNT_ERROR",FRAME_READY:"@w3m-frame/READY",FRAME_RELOAD_SUCCESS:"@w3m-frame/RELOAD_SUCCESS",FRAME_RELOAD_ERROR:"@w3m-frame/RELOAD_ERROR",FRAME_RPC_ABORT_SUCCESS:"@w3m-frame/RPC_ABORT_SUCCESS",FRAME_RPC_ABORT_ERROR:"@w3m-frame/RPC_ABORT_ERROR",RPC_RESPONSE_TYPE_ERROR:"RPC_RESPONSE_ERROR",RPC_RESPONSE_TYPE_TX:"RPC_RESPONSE_TRANSACTION_HASH",RPC_RESPONSE_TYPE_OBJECT:"RPC_RESPONSE_OBJECT"},Kr={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}}});var kU,Ite=b(()=>{l();kU={address:/^0x(?:[A-Fa-f0-9]{40})$/u,transactionHash:/^0x(?:[A-Fa-f0-9]{64})$/u,signedMessage:/^0x(?:[a-fA-F0-9]{62,})$/u}});var Ew,UU=b(()=>{l();g4();Tte();Ew={set(e,t){lI.isClient&&localStorage.setItem(`${Qa.STORAGE_KEY}${e}`,t)},get(e){return lI.isClient?localStorage.getItem(`${Qa.STORAGE_KEY}${e}`):null},delete(e,t){lI.isClient&&(t?localStorage.removeItem(e):localStorage.removeItem(`${Qa.STORAGE_KEY}${e}`))}}});var uI,lI,Tte=b(()=>{l();Ite();g4();UU();uI=30*1e3,lI={checkIfAllowedToTriggerEmail(){let e=Ew.get(Qa.LAST_EMAIL_LOGIN_TIME);if(e){let t=Date.now()-Number(e);if(t{l();g4();UU()});var Pte,Nte=b(()=>{l();Pte="1.2.3"});var wn,Aw=b(()=>{l();Nte();wn=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: https://abitype.dev${o}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Pte}`].join(` +`);super(s),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.shortMessage=t}}});function ga(e,t){return e.exec(t)?.groups}var DU,LU,dI,y4=b(()=>{l();DU=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,LU=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,dI=/^\(.+?\).*?$/});function fI(e){let t=e.type;if(Rte.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let o=0;o{l();y4();Rte=/^tuple(?(\[(\d*)\])*)$/});function Ef(e){let t="",r=e.length;for(let n=0;n{l();Ote()});function Af(e){return e.type==="function"?`function ${e.name}(${Ef(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Ef(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Ef(e.inputs)})`:e.type==="error"?`error ${e.name}(${Ef(e.inputs)})`:e.type==="constructor"?`constructor(${Ef(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var Bte=b(()=>{l();MU()});function Ute(e){return kte.test(e)}function Dte(e){return ga(kte,e)}function Mte(e){return Lte.test(e)}function Hte(e){return ga(Lte,e)}function Fte(e){return $te.test(e)}function zte(e){return ga($te,e)}function Zl(e){return Vte.test(e)}function jte(e){return ga(Vte,e)}function Wte(e){return qte.test(e)}function Kte(e){return ga(qte,e)}function Gte(e){return Zte.test(e)}function Yte(e){return ga(Zte,e)}function Jte(e){return Lke.test(e)}var kte,Lte,$te,Vte,qte,Zte,Lke,Cw,Qte,pI,J1=b(()=>{l();y4();kte=/^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;Lte=/^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;$te=/^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/;Vte=/^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/;qte=/^constructor\((?.*?)\)(?:\s(?payable{1}))?$/;Zte=/^fallback\(\) external(?:\s(?payable{1}))?$/;Lke=/^receive\(\) external payable$/;Cw=new Set(["memory","indexed","storage","calldata"]),Qte=new Set(["indexed"]),pI=new Set(["calldata","memory","storage"])});var Q1,X1,w4,b4=b(()=>{l();Aw();Q1=class extends wn{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}},X1=class extends wn{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},w4=class extends wn{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}});var eg,tg,rg,ng,og,sg,ig,Sw=b(()=>{l();Aw();eg=class extends wn{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}},tg=class extends wn{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}},rg=class extends wn{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},ng=class extends wn{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},og=class extends wn{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},sg=class extends wn{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},ig=class extends wn{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}});var ya,ag,cg,hI=b(()=>{l();Aw();ya=class extends wn{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},ag=class extends wn{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},cg=class extends wn{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}});var lg,HU=b(()=>{l();Aw();lg=class extends wn{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}});var ug,$U=b(()=>{l();Aw();ug=class extends wn{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}});function Xte(e,t,r){let n="";if(r)for(let o of Object.entries(r)){if(!o)continue;let s="";for(let i of o[1])s+=`[${i.type}${i.name?`:${i.name}`:""}]`;n+=`(${o[0]}{${s}})`}return t?`${t}:${e}${n}`:`${e}${n}`}var mI,ere=b(()=>{l();mI=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});function x4(e,t={}){if(Fte(e))return Mke(e,t);if(Mte(e))return Hke(e,t);if(Ute(e))return $ke(e,t);if(Wte(e))return Fke(e,t);if(Gte(e))return zke(e);if(Jte(e))return{type:"receive",stateMutability:"payable"};throw new ag({signature:e})}function Mke(e,t={}){let r=zte(e);if(!r)throw new ya({signature:e,type:"function"});let n=Ei(r.parameters),o=[],s=n.length;for(let a=0;a{l();y4();b4();Sw();hI();$U();ere();J1();Vke=/^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,jke=/^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,qke=/^u?int$/;Wke=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/});function Rh(e){let t={},r=e.length;for(let i=0;i{l();y4();b4();Sw();hI();HU();J1();dg();Gke=/^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/});function Iw(e){let t=Rh(e),r=[],n=e.length;for(let o=0;o{l();J1();v4();dg()});function Tw(e){let t;if(typeof e=="string")t=x4(e);else{let r=Rh(e),n=e.length;for(let o=0;o{l();b4();J1();v4();dg()});function zU(e){let t;if(typeof e=="string")t=Ai(e,{modifiers:Cw});else{let r=Rh(e),n=e.length;for(let o=0;o{l();Sw();J1();v4();dg()});function _w(e){let t=[];if(typeof e=="string"){let r=Ei(e),n=r.length;for(let o=0;o{l();Sw();J1();v4();dg();dg()});var fg=b(()=>{l();Bte();MU();rre();nre();ore();sre();b4();Sw();hI();$U();HU()});function ue(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let o=e[r];return typeof o=="function"?o:s=>t(e,s)}var _t=b(()=>{l()});function no(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Pw(e.type);return`${e.name}(${E4(e.inputs,{includeName:t})})`}function E4(e,{includeName:t=!1}={}){return e?e.map(r=>Yke(r,{includeName:t})).join(t?", ":","):""}function Yke(e,{includeName:t}){return e.type.startsWith("tuple")?`(${E4(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}var Cf=b(()=>{l();Qr()});function We(e,{even:t=!1,strict:r=!0}={}){return!e||typeof e!="string"||t&&e.length%2!==0?!1:r?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}var qs=b(()=>{l()});function gt(e){return We(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var Fo=b(()=>{l();qs()});var VU,are=b(()=>{l();VU="2.57.19"});function cre(e){gI=e}function lre(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?lre(e.cause,t):t?null:e}var gI,G,nt=b(()=>{l();are();gI={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${VU}`};G=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=gI.getDocsUrl?.({...r,docsPath:o}),i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...gI.version?[`Version: ${gI.version}`]:[]].join(` +`);super(i,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=VU}walk(t){return lre(this,t)}}});var Oh,Gl,yI,Bh,Ci,Nw,Rw,kh,Ow,pg,Uh,Yl,Jl,hg,wa,Dh,Bw,wI,Lh,jc,Ql,kw,Uw,Mh,Pw,Dw,Qr=b(()=>{l();Cf();Fo();nt();Oh=class extends G{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(` +`),{docsPath:t,name:"AbiConstructorNotFoundError"})}},Gl=class extends G{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(` +`),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}},yI=class extends G{constructor({data:t,size:r}){super([`Data size of ${r} bytes is invalid.`,"Size must be in increments of 32 bytes (size % 32 === 0)."].join(` +`),{metaMessages:[`Data: ${t} (${r} bytes)`],name:"AbiDecodingDataSizeInvalidError"})}},Bh=class extends G{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(` +`),{metaMessages:[`Params: (${E4(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}},Ci=class extends G{constructor({cause:t}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:t})}},Nw=class extends G{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(` +`),{name:"AbiEncodingArrayLengthMismatchError"})}},Rw=class extends G{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${gt(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}},kh=class extends G{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(` +`),{name:"AbiEncodingLengthMismatchError"})}},Ow=class extends G{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(` +`),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}},pg=class extends G{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(` +`),{docsPath:r,name:"AbiErrorNotFoundError"})}},Uh=class extends G{constructor(t,{docsPath:r,cause:n}){super([`Encoded error signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${t}.`].join(` +`),{docsPath:r,name:"AbiErrorSignatureNotFoundError",cause:n}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}},Yl=class extends G{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}},Jl=class extends G{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(` +`),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}},hg=class extends G{constructor(t,{docsPath:r}={}){super([`Event ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it."].join(` +`),{docsPath:r,name:"AbiEventNotFoundError"})}},wa=class extends G{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(` +`),{docsPath:r,name:"AbiFunctionNotFoundError"})}},Dh=class extends G{constructor(t,{docsPath:r}){super([`Function "${t}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(` +`),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}},Bw=class extends G{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(` +`),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}},wI=class extends G{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${no(t.abiItem)}\`, and`,`\`${r.type}\` in \`${no(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}},Lh=class extends G{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}},jc=class extends G{constructor({abiItem:t,data:r,params:n,size:o}){super([`Data size of ${o} bytes is too small for non-indexed event parameters.`].join(` +`),{metaMessages:[`Params: (${E4(n,{includeName:!0})})`,`Data: ${r} (${o} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t,this.data=r,this.params=n,this.size=o}},Ql=class extends G{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${no(t,{includeName:!0})}".`].join(` +`),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}},kw=class extends G{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(` +`),{docsPath:r,name:"InvalidAbiEncodingType"})}},Uw=class extends G{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(` +`),{docsPath:r,name:"InvalidAbiDecodingType"})}},Mh=class extends G{constructor(t){super([`Value "${t}" is not a valid array.`].join(` +`),{name:"InvalidArrayError"})}},Pw=class extends G{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(` +`),{name:"InvalidDefinitionTypeError"})}},Dw=class extends G{constructor(t){super(`Type "${t}" is not supported for packed encoding.`,{name:"UnsupportedPackedAbiType"})}}});var Lw,jU=b(()=>{l();nt();Lw=class extends G{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}});var mg,gg,A4,C4=b(()=>{l();nt();mg=class extends G{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},gg=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}},A4=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}});function Zr(e,{dir:t,size:r=32}={}){return typeof e=="string"?cs(e,{dir:t,size:r}):qU(e,{dir:t,size:r})}function cs(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new gg({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function qU(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new gg({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let o=0;o{l();C4()});var Xl,Mw,Hw,$w,Fw,zw,Vw,jw,yg=b(()=>{l();nt();Xl=class extends G{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number "${s}" is not in safe ${o?`${o*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},Mw=class extends G{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}},Hw=class extends G{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}},$w=class extends G{constructor(t){super(`Hex value "${t}" is an odd length (${t.length}). It must be an even length.`,{name:"InvalidHexValueError"})}},Fw=class extends G{constructor({limit:t}){super(`RLP depth limit of \`${t}\` exceeded.`,{name:"RlpDepthLimitExceededError"})}},zw=class extends G{constructor({consumed:t,declared:r}){super(`RLP list items consumed \`${t}\` bytes but the list declared a length of \`${r}\`.`,{name:"RlpListBoundaryExceededError"})}},Vw=class extends G{constructor({count:t}){super(`RLP payload encodes a single item, but \`${t}\` trailing ${t===1?"byte remains":"bytes remain"}.`,{name:"RlpTrailingBytesError"})}},jw=class extends G{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}});function bn(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let o=0;o{l()});function Ws(e,{size:t}){if(gt(e)>t)throw new jw({givenSize:gt(e),maxSize:t})}function WU(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?wt(e,r):n==="bigint"?dt(e,r):n==="string"?bI(e,r):n==="boolean"?qw(e,r):qt(e,r)}function dt(e,t={}){let{signed:r}=t;t.size&&Ws(e,{size:t.size});let n=BigInt(e);if(!r)return n;let o=Math.ceil((e.length-2)/2),s=(1n<{l();yg();Fo();Hh();Pr()});function wr(e,t={}){return typeof e=="number"||typeof e=="bigint"?oe(e,t):typeof e=="string"?ec(e,t):typeof e=="boolean"?wg(e,t):yt(e,t)}function wg(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Ws(r,{size:t.size}),Zr(r,{size:t.size})):r}function yt(e,t={}){let r="";for(let o=0;os||o{l();yg();Xa();Xr();Jke=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Qke=new TextEncoder});function un(e,t={}){return typeof e=="number"||typeof e=="bigint"?ZU(e,t):typeof e=="boolean"?KU(e,t):We(e)?qt(e,t):zo(e,t)}function KU(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Ws(r,{size:t.size}),Zr(r,{size:t.size})):r}function ure(e){if(e>=Sf.zero&&e<=Sf.nine)return e-Sf.zero;if(e>=Sf.A&&e<=Sf.F)return e-(Sf.A-10);if(e>=Sf.a&&e<=Sf.f)return e-(Sf.a-10)}function qt(e,t={}){let r=e.slice(2);r.length%2&&(r=`0${r}`),t.size&&(Ws(e,{size:t.size}),r=r.padEnd(t.size*2,"0"));let n=r.length/2,o=new Uint8Array(n);for(let s=0,i=0;s{l();nt();qs();Xa();Xr();qe();Xke=new TextEncoder;Sf={zero:48,nine:57,A:65,F:70,a:97,f:102}});function eUe(e,t=!1){return t?{h:Number(e&xI),l:Number(e>>dre&xI)}:{h:Number(e>>dre&xI)|0,l:Number(e&xI)|0}}function fre(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s{l();xI=BigInt(4294967295),dre=BigInt(32);pre=(e,t,r)=>e<>>32-r,hre=(e,t,r)=>t<>>32-r,mre=(e,t,r)=>t<>>64-r,gre=(e,t,r)=>e<>>64-r});var bg,wre=b(()=>{l();bg=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function tUe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function xg(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function eu(e,...t){if(!tUe(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function bre(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xg(e.outputLen),xg(e.blockLen)}function If(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function vI(e,t){eu(e);let r=t.outputLen;if(e.length>>t}function S4(e,t){return e<>>32-t>>>0}function nUe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function oUe(e){for(let t=0;te().update(vg(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function AI(e=32){if(bg&&typeof bg.getRandomValues=="function")return bg.getRandomValues(new Uint8Array(e));if(bg&&typeof bg.randomBytes=="function")return Uint8Array.from(bg.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var rUe,GU,$h,Tf=b(()=>{l();wre();rUe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;GU=rUe?e=>e:oUe;$h=class{}});function pUe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=Ere(u,d,1)^r[a],p=Are(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=Sre[i],c=Ere(o,s,a),u=Are(o,s,a),d=Cre[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=dUe[n],e[1]^=fUe[n]}ba(r)}var iUe,I4,aUe,cUe,lUe,uUe,Cre,Sre,Ire,Tre,dUe,fUe,Ere,Are,YU,hUe,CI,JU=b(()=>{l();yre();Tf();iUe=BigInt(0),I4=BigInt(1),aUe=BigInt(2),cUe=BigInt(7),lUe=BigInt(256),uUe=BigInt(113),Cre=[],Sre=[],Ire=[];for(let e=0,t=I4,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Cre.push(2*(5*n+r)),Sre.push((e+1)*(e+2)/2%64);let o=iUe;for(let s=0;s<7;s++)t=(t<>cUe)*uUe)%lUe,t&aUe&&(o^=I4<<(I4<r>32?mre(e,t,r):pre(e,t,r),Are=(e,t,r)=>r>32?gre(e,t,r):hre(e,t,r);YU=class e extends $h{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,xg(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return xg(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(vI(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ba(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},hUe=(e,t,r)=>Ww(()=>new YU(t,e,r)),CI=hUe(1,136,256/8)});function Pt(e,t){let r=t||"hex",n=CI(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var Ks=b(()=>{l();JU();qs();Pr();qe()});var xo,_f=b(()=>{l();xo=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&(super.delete(t),super.set(t,r)),r}set(t,r){if(super.has(t)&&super.delete(t),super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=super.keys().next().value;n!==void 0&&super.delete(n)}return this}}});function _re(e){return mUe(e)}var mUe,Pre=b(()=>{l();Pr();Ks();mUe=e=>Pt(un(e))});function Nre(e){let t=!0,r="",n=0,o="",s=!1;for(let i=0;i{l();nt()});var Pf,SI=b(()=>{l();fg();Rre();Pf=e=>{let t=typeof e=="string"?e:Af(e);return Nre(t)}});function Nf(e){let t=typeof e=="string"?e:Af(e),r=Ore.get(t);if(r)return r;let n=_re(Pf(t));return Ore.set(t,n),n}var Ore,T4=b(()=>{l();fg();_f();Pre();SI();Ore=new xo(8192)});var Wc,Kw=b(()=>{l();T4();Wc=Nf});var br,tc=b(()=>{l();nt();br=class extends G{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}});function Kc(e,t){if(QU.has(`${e}.${t}`))return QU.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=Pt(zo(r),"bytes"),o=(t?r.substring(`${t}0x`.length):r).split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&o[i]&&(o[i]=o[i].toUpperCase()),(n[i>>1]&15)>=8&&o[i+1]&&(o[i+1]=o[i+1].toUpperCase());let s=`0x${o.join("")}`;return QU.set(`${e}.${t}`,s),s}function Gr(e,t){if(!Ft(e,{strict:!1}))throw new br({address:e});return Kc(e,t)}var QU,Zs=b(()=>{l();tc();Pr();Ks();_f();Gs();QU=new xo(8192)});function Ft(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(XU.has(n))return XU.get(n);let o=gUe.test(e)?e.toLowerCase()===e?!0:r?Kc(e)===e:!0:!1;return XU.set(n,o),o}var gUe,XU,Gs=b(()=>{l();_f();Zs();gUe=/^0x[a-fA-F0-9]{40}$/,XU=new xo(8192)});function en(e){return typeof e[0]=="string"?fr(e):eD(e)}function eD(e){let t=0;for(let o of e)t+=o.length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function fr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}var Fn=b(()=>{l()});function vo(e,t,r,{strict:n}={}){return We(e,{strict:!1})?xa(e,t,r,{strict:n}):_4(e,t,r,{strict:n})}function Bre(e,t){if(typeof t=="number"&&t>0&&t>gt(e)-1)throw new mg({offset:t,position:"start",size:gt(e)})}function kre(e,t,r){if(typeof t=="number"&&typeof r=="number"&>(e)!==r-t)throw new mg({offset:r,position:"end",size:gt(e)})}function _4(e,t,r,{strict:n}={}){Bre(e,t);let o=e.slice(t,r);return n&&kre(o,t,r),o}function xa(e,t,r,{strict:n}={}){Bre(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&kre(o,t,r),o}var Si=b(()=>{l();C4();qs();Fo()});var Ure,Eg,Rf,P4=b(()=>{l();Ure=/^(.*)\[([0-9]*)\]$/,Eg=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Rf=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/});function oo(e,t){if(e.length!==t.length)throw new kh({expectedLength:e.length,givenLength:t.length});let r=yUe({params:e,values:t});return nD(r)}function yUe({params:e,values:t}){let r=[];for(let n=0;ni))}}function xUe(e,{param:t}){let[,r]=t.type.split("bytes"),n=e.length%2?`0x0${e.slice(2)}`:e,o=gt(n);if(!r){let s=n;return o%32!==0&&(s=cs(s,{dir:"right",size:Math.ceil(o/32)*32})),{dynamic:!0,encoded:fr([cs(oe(o,{size:32})),s])}}if(o!==Number.parseInt(r,10))throw new Rw({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:cs(n,{dir:"right"})}}function vUe(e){if(typeof e!="boolean")throw new G(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(wg(e))}}function EUe(e,{signed:t,size:r=256}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||eo))}}function Of(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function tD(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components.some(tD);let r=Of(t);return r?tD({...e,type:r[1]}):!1}var rc=b(()=>{l();Qr();tc();nt();yg();Gs();Fn();Xa();Fo();Si();qe();P4()});var va,Ag=b(()=>{l();Si();T4();va=e=>vo(Nf(e),0,4)});function ls(e){let{abi:t,args:r=[],name:n}=e,o=We(n,{strict:!1}),s=t.filter(a=>o?a.type==="function"?va(a)===n:a.type==="event"?Wc(a)===n:!1:"name"in a&&a.name===n);if(s.length===0)return;if(s.length===1)return s[0];let i;for(let a of s){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,d)=>{let f="inputs"in a&&a.inputs[d];return f?oD(u,f):!1})){if(i&&"inputs"in i&&i.inputs){let u=sD(a.inputs,i.inputs,r);if(u)throw new wI({abiItem:a,type:u[0]},{abiItem:i,type:u[1]})}i=a}}return i||s[0]}function oD(e,t){let r=typeof e,n=t.type;switch(n){case"address":return Ft(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((s,i)=>r==="object"&&oD(Dre(e,s,i),s));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)){if(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&!Number.isInteger(e))return!1;let s=n.startsWith("int"),i=Number.parseInt(n.replace(/^u?int/,"")||"256",10),a=2n**(BigInt(i)-(s?1n:0n))-1n,c=s?-a-1n:0n;return e>=c&&e<=a}if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)){if(typeof e!="string"&&!(e instanceof Uint8Array))return!1;let s=n.slice(5);return s?typeof e=="string"&&!We(e)?!1:gt(e)===Number.parseInt(s,10):e instanceof Uint8Array||We(e)}let o=Of(n);if(o){let[s,i]=o;return Array.isArray(e)&&(s===null||e.length===s)&&e.every(a=>oD(a,{...t,type:i}))}return!1}}}function sD(e,t,r){for(let n in e){let o=e[n],s=t[n];if(!s)continue;if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s){let f=r[n],p=sD(o.components,s.components,o.components.map((h,y)=>Dre(f,h,y)));if(p)return p;continue}let i=Of(o.type),a=Of(s.type);if(i&&a){let f=sD([{...o,type:i[1]}],[{...s,type:a[1]}],[r[n]?.[0]]);if(f)return f;if(i[1]===a[1]&&o.type!==s.type)return[o.type,s.type];continue}let c=[o.type,s.type],u=r[n];if(c.includes("address")&&(c.includes("string")||c.includes("bytes"))?u===void 0||Ft(u,{strict:!1}):o.type!==s.type)return c}}function Dre(e,t,r){return Array.isArray(e)?e[r]:e?.[t.name]}var Bf=b(()=>{l();Qr();qs();Gs();Fo();Kw();Ag();rc()});function nc(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=ls({abi:t,name:r});if(!c)throw new hg(r,{docsPath:Lre});o=c}if(o.type!=="event")throw new hg(void 0,{docsPath:Lre});let s=[];if(n&&"inputs"in o){let c=o.inputs?.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?c?.map(d=>n[d.name])??[]:[];u.length>0&&(s=c?.map((d,f)=>Array.isArray(u[f])?u[f].map((p,h)=>Mre({param:d,value:u[f][h]})):typeof u[f]<"u"&&u[f]!==null?Mre({param:d,value:u[f]}):null)??[])}if(o.anonymous)return s;let i=no(o);return[Wc(i),...s]}function Mre({param:e,value:t}){if(e.type==="string")return Pt(zo(t));if(e.type==="bytes")return Pt(un(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Lw(e.type);return oo([e],[t])}var Lre,Cg=b(()=>{l();Qr();jU();Pr();Ks();Kw();rc();Cf();Bf();Lre="/docs/contract/encodeEventTopics"});function Fh(e,{method:t}){let r={};return e.transport.type==="fallback"&&e.transport.onResponse?.(({method:n,response:o,status:s,transport:i})=>{s==="success"&&t===n&&(r[o]=i.request)}),(n=>r[n]||e.request)}var N4=b(()=>{l()});async function Zw(e,t){let{address:r,abi:n,args:o,eventName:s,fromBlock:i,strict:a,toBlock:c}=t,u=Fh(e,{method:"eth_newFilter"}),d=s?nc({abi:n,args:o,eventName:s}):void 0,f=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof i=="bigint"?oe(i):i,toBlock:typeof c=="bigint"?oe(c):c,topics:d}]});return{abi:n,args:o,eventName:s,id:f,request:u(f),strict:!!a,type:"event"}}var II=b(()=>{l();Cg();qe();N4()});function ft(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}var tn=b(()=>{l()});function TI(e){let{abi:t,args:r,functionName:n}=e,o=t[0];if(n){let s=ls({abi:t,args:r,name:n});if(!s)throw new wa(n,{docsPath:Hre});o=s}if(o.type!=="function")throw new wa(void 0,{docsPath:Hre});return{abi:[o],functionName:va(no(o))}}var Hre,iD=b(()=>{l();Qr();Ag();Cf();Bf();Hre="/docs/contract/encodeFunctionData"});function Wt(e){let{args:t}=e,{abi:r,functionName:n}=e.abi.length===1&&e.functionName?.startsWith("0x")?e:TI(e),o=r[0],s=n,i="inputs"in o&&o.inputs?oo(o.inputs,t??[]):void 0;return fr([s,i??"0x"])}var us=b(()=>{l();Fn();rc();iD()});var $re,Gw,Fre,R4=b(()=>{l();$re={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},Gw={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Fre={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"}});var O4,Yw,_I,aD=b(()=>{l();nt();O4=class extends G{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},Yw=class extends G{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},_I=class extends G{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}});function Zc(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(SUe);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var SUe,Jw=b(()=>{l();aD();SUe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new _I({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new Yw({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new O4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new O4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}}});function zre(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?Ea(e,r):n==="bigint"?B4(e,r):n==="boolean"?k4(e,r):n==="string"?U4(e,r):yt(e,r)}function B4(e,t={}){typeof t.size<"u"&&Ws(e,{size:t.size});let r=yt(e);return dt(r,t)}function k4(e,t={}){let r=e;if(typeof t.size<"u"&&(Ws(r,{size:t.size}),r=bn(r)),r.length>1||r[0]>1)throw new Mw(r);return!!r[0]}function Ea(e,t={}){typeof t.size<"u"&&Ws(e,{size:t.size});let r=yt(e);return wt(r,t)}function U4(e,t={}){let r=e;return typeof t.size<"u"&&(Ws(r,{size:t.size}),r=bn(r,{dir:"right"})),new TextDecoder().decode(r)}var cD=b(()=>{l();yg();Hh();Xr();qe()});function Ys(e,t){let r=typeof t=="string"?qt(t):t,n=Zc(r);if(gt(r)===0&&e.length>0)throw new Ci;if(gt(t)&>(t)<32)throw new Bh({data:typeof t=="string"?t:yt(t),params:e,size:gt(t)});let o={limit:r.length*32,used:0},s=0,i=[];for(let a=0;ar.limit)throw new Xw({limit:r.limit});return e.setPosition(n+32),[yt(u),32]}return[yt(e.readBytes(Number.parseInt(s,10),32)),32]}function NUe(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?B4(o,{signed:r}):Ea(o,{signed:r}),32]}function RUe(e,t,{budget:r,staticPosition:n}){let o=t.components.length===0||t.components.some(({name:a})=>!a),s=o?[]:{},i=0;if(D4(t)){let a=Ea(e.readBytes(lD)),c=n+a;for(let u=0;ut.limit)throw new Xw({limit:t.limit});let a=U4(i);return e.setPosition(r+32),[a,32]}function D4(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(D4);let r=Of(e.type);return!!(r&&D4({...e,type:r[1]}))}var Vre,lD,Xw,zh=b(()=>{l();Qr();nt();Zs();Jw();Fo();Si();cD();Pr();qe();rc();Vre=32,lD=32;Xw=class extends G{constructor({limit:t}){super(`Decoded \`bytes\` and \`string\` values exceed the size limit of ${t} bytes.`,{name:"AbiDecodingSizeLimitExceededError"})}}});function Vh(e){let{abi:t,data:r,cause:n}=e,o=vo(r,0,4);if(o==="0x")throw new Ci({cause:n});let i=[...t||[],Gw,Fre].find(a=>a.type==="error"&&o===va(no(a)));if(!i)throw new Uh(o,{docsPath:"/docs/contract/decodeErrorResult",cause:n});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Ys(i.inputs,vo(r,4)):void 0,errorName:i.name}}var L4=b(()=>{l();R4();Qr();Si();Ag();zh();Cf()});var bt,so=b(()=>{l();bt=(e,t,r)=>JSON.stringify(e,(n,o)=>{let s=typeof o=="bigint"?o.toString():o;return typeof t=="function"?t(n,s):s},r)});function uD({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((o,s)=>`${n&&o.name?`${o.name}: `:""}${typeof t[s]=="object"?bt(t[s]):t[s]}`).join(", ")})`}var jre=b(()=>{l();so()});function NI(e,t=0){if(!Number.isInteger(t)||t<0)throw new PI({decimals:t});let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[o,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${o||"0"}${s?`.${s}`:""}`}function qre(e,t="wei"){return NI(e,jh.ether-jh[t])}function Wre(e,t="wei"){return NI(e,jh.gwei-jh[t])}function RI(e,t=0){if(!Number.isInteger(t)||t<0)throw new PI({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new dD({value:e});let[r="",n="0"]=e.split("."),o=r.startsWith("-");if(o&&(r=r.slice(1)),r===""&&(r="0"),n=n.replace(/(0+)$/,""),t===0)n.length>0&&Number.parseInt(n[0],10)>=5&&(r=`${BigInt(r)+1n}`),n="";else if(n.length>t){let s=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){let a=BUe(s);a.length>t?(n=a.slice(1),r=`${BigInt(r)+1n}`):n=a}else n=s}else n=n.padEnd(t,"0");return BigInt(`${o?"-":""}${r}${n}`)}function BUe(e){let t=e.split(""),r=t.length-1;for(;r>=0;){let n=Number.parseInt(t[r],10)+1;if(n<10)return t[r]=String(n),t.join("");t[r]="0",r--}return`1${t.join("")}`}function Kre(e,t="wei"){return RI(e,jh.ether-jh[t])}function Zre(e,t="wei"){return RI(e,jh.gwei-jh[t])}var jh,dD,PI,Sg=b(()=>{l();jh={wei:0,gwei:9,szabo:12,finney:15,ether:18};dD=class extends Error{constructor({value:t}){super(`Value \`${t}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}},PI=class extends Error{constructor({decimals:t}){super(`\`decimals\` must be a non-negative integer. Got \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}});function qh(e,t="wei"){return qre(e,t)}var M4=b(()=>{l();Sg()});function Pn(e,t="wei"){return Wre(e,t)}var Ig=b(()=>{l();Sg()});function Gre(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n} +`,"")}function Yre(e){return e.reduce((t,{address:r,...n})=>{let o=`${t} ${r}: +`;return n.nonce&&(o+=` nonce: ${n.nonce} +`),n.balance&&(o+=` balance: ${n.balance} +`),n.code&&(o+=` code: ${n.code} +`),n.state&&(o+=` state: +`,o+=Gre(n.state)),n.stateDiff&&(o+=` stateDiff: +`,o+=Gre(n.stateDiff)),o},` State Override: +`).slice(0,-1)}var tb,rb,OI=b(()=>{l();nt();tb=class extends G{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}},rb=class extends G{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}});function Tg(e){let t=Object.entries(e).map(([n,o])=>o===void 0||o===!1?null:[n,o]).filter(Boolean),r=t.reduce((n,[o])=>Math.max(n,o.length),0);return t.map(([n,o])=>` ${`${n}:`.padEnd(r+1)} ${o}`).join(` +`)}var BI,Wh,Kh,tu,nb,ob,ru,sb,ib,Gc,nu,Zh,Gh,zn=b(()=>{l();M4();Ig();nt();BI=class extends G{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(` +`),{name:"FeeConflictError"})}},Wh=class extends G{constructor({filledNonce:t,requestedNonce:r}){super("The filled transaction nonce does not match the requested nonce.",{metaMessages:[`Requested Nonce: ${r}`,`Filled Nonce: ${t}`],name:"FeePayerNonceMismatchError"})}},Kh=class extends G{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}},tu=class extends G{constructor({yParity:t}){super(`Invalid \`yParity\` value "${t}". Expected 0 or 1.`,{name:"InvalidYParityError"})}},nb=class extends G{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Tg(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}},ob=class extends G{constructor({serializedType:t}){super(`Serialized transaction type "${t}" is invalid.`,{name:"InvalidSerializedTransactionType"}),Object.defineProperty(this,"serializedType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedType=t}},ru=class extends G{constructor({attributes:t,serializedTransaction:r,type:n}){let o=Object.entries(t).map(([s,i])=>typeof i>"u"?s:void 0).filter(Boolean);super(`Invalid serialized transaction of type "${n}" was provided.`,{metaMessages:[`Serialized Transaction: "${r}"`,o.length>0?`Missing Attributes: ${o.join(", ")}`:""].filter(Boolean),name:"InvalidSerializedTransactionError"}),Object.defineProperty(this,"serializedTransaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedTransaction=r,this.type=n}},sb=class extends G{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}},ib=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p}){let h=Tg({chain:o&&`${o?.name} (id: ${o?.id})`,from:r?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",h].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},Gc=class extends G{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:o,index:s}){let i="Transaction";n&&s!==void 0&&(i=`Transaction at block time "${n}" at index "${s}"`),t&&s!==void 0&&(i=`Transaction at block hash "${t}" at index "${s}"`),r&&s!==void 0&&(i=`Transaction at block number "${r}" at index "${s}"`),o&&(i=`Transaction with hash "${o}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}},nu=class extends G{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}},Zh=class extends G{constructor({receipt:t}){super(`Transaction with hash "${t.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=t}},Gh=class extends G{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}});function Nn(e){if(e?.reason)return e.reason;if(typeof DOMException=="function")return new DOMException("This operation was aborted","AbortError");let t=new Error("This operation was aborted");return t.name="AbortError",t}function Ii(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var Jre,kf,oc=b(()=>{l();Jre=e=>e;kf=e=>{try{let t=new URL(e);return!t.username&&!t.password?e:(t.username="",t.password="",t.toString())}catch{return e}}});var Yc,ab,Uf,cb,lb,sc,ou=b(()=>{l();tn();R4();L4();Cf();jre();Bf();M4();Ig();Qr();nt();OI();zn();oc();Yc=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p,stateOverride:h}){let y=r?ft(r):void 0,w=Tg({from:y?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});h&&(w+=` +${Yre(h)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",w].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},ab=class extends G{constructor(t,{abi:r,args:n,contractAddress:o,docsPath:s,functionName:i,sender:a}){let c=ls({abi:r,args:n,name:i}),u=c?uD({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,d=c?no(c,{includeName:!0}):void 0,f=Tg({address:o&&Jre(o),function:d,args:u&&u!=="()"&&`${[...Array(i?.length??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${i}".`,{cause:t,docsPath:s,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=o,this.functionName=i,this.sender=a}},Uf=class extends G{constructor({abi:t,data:r,functionName:n,message:o,cause:s}){let i,a,c,u;if(r&&r!=="0x")try{a=Vh({abi:t,data:r,cause:s});let{abiItem:f,errorName:p,args:h}=a;if(p==="Error")u=h[0];else if(p==="Panic"){let[y]=h;u=$re[y]}else{let y=f?no(f,{includeName:!0}):void 0,w=f&&h?uD({abiItem:f,args:h,includeFunctionName:!1,includeName:!1}):void 0;c=[y?`Error: ${y}`:"",w&&w!=="()"?` ${[...Array(p?.length??0).keys()].map(()=>" ").join("")}${w}`:""]}}catch(f){i=f}else o&&(u=o);let d;i instanceof Uh&&(d=i.signature,c=[`Unable to decode signature "${d}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${d}.`]),super(u&&u!=="execution reverted"||d?[`The contract function "${n}" reverted with the following ${d?"signature":"reason"}:`,u||d].join(` +`):`The contract function "${n}" reverted.`,{cause:i??s,metaMessages:c,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=u,this.signature=d}},cb=class extends G{constructor({functionName:t,cause:r}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:r})}},lb=class extends G{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}},sc=class extends G{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}}});var Nr,ic,_g,Rn,su,ds,fs=b(()=>{l();so();nt();oc();Nr=class extends G{constructor({body:t,cause:r,details:n,headers:o,status:s,url:i}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[s&&`Status: ${s}`,`URL: ${kf(i)}`,t&&`Request body: ${bt(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=o,this.status=s,this.url=i}},ic=class extends G{constructor({maxSize:t,size:r}){super("HTTP response body exceeded the size limit.",{metaMessages:[`Max: ${t} bytes`,`Received: ${r} bytes`],name:"ResponseBodyTooLargeError"}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t,this.size=r}},_g=class extends G{constructor({body:t,cause:r,details:n,url:o}){super("WebSocket request failed.",{cause:r,details:n,metaMessages:[`URL: ${kf(o)}`,t&&`Request body: ${bt(t)}`].filter(Boolean),name:"WebSocketRequestError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=o}},Rn=class extends G{constructor({body:t,error:r,headers:n,status:o,url:s}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[o&&`Status: ${o}`,`URL: ${kf(s)}`,`Request body: ${bt(t)}`].filter(Boolean),name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.headers=n,this.status=o,this.url=s}},su=class extends G{constructor({url:t}={}){super("The socket has been closed.",{metaMessages:[t&&`URL: ${kf(t)}`].filter(Boolean),name:"SocketClosedError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}},ds=class extends G{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${kf(r)}`,`Request body: ${bt(t)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}});var kUe,Eo,Ao,Yh,Jh,Jc,Qh,Qc,Ti,Xh,e0,iu,Aa,Df,t0,Xc,r0,n0,o0,s0,i0,au,a0,c0,l0,u0,d0,cu,f0,ub,Lf=b(()=>{l();nt();fs();kUe=-1,Eo=class extends G{constructor(t,{code:r,docsPath:n,metaMessages:o,name:s,shortMessage:i}){super(i,{cause:t,docsPath:n,metaMessages:o||t?.metaMessages,name:s||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s||t.name,this.code=t instanceof Rn?t.code:r??kUe}},Ao=class extends Eo{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}},Yh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};Object.defineProperty(Yh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});Jh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};Object.defineProperty(Jh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});Jc=class e extends Eo{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}};Object.defineProperty(Jc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Qh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(` +`)})}};Object.defineProperty(Qh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});Qc=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};Object.defineProperty(Qc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Ti=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(` +`)})}};Object.defineProperty(Ti,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});Xh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(Xh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});e0=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(e0,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});iu=class e extends Eo{constructor(t){super(t,{code:e.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(iu,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});Aa=class e extends Eo{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}};Object.defineProperty(Aa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});Df=class e extends Eo{constructor(t){super(t,{code:e.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty(Df,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});t0=class e extends Eo{constructor(t){super(t,{code:e.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(t0,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Xc=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Xc,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});r0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(r0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});n0=class e extends Ao{constructor(t,{method:r}={}){super(t,{code:e.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}};Object.defineProperty(n0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});o0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(o0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});s0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(s0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});i0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty(i0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});au=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(au,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});a0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(a0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});c0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(c0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});l0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(l0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});u0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(u0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});d0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(d0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});cu=class e extends Ao{constructor(t){super(t,{code:e.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(cu,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});f0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(f0,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});ub=class extends Eo{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});function Js(e,{abi:t,address:r,args:n,docsPath:o,functionName:s,sender:i}){let a=e instanceof sc?e:e instanceof G?e.walk(y=>typeof y=="object"&&y!==null&&"data"in y)||e.walk():{},{code:c,data:u,details:d,message:f,shortMessage:p}=a,h=e instanceof Ci?new cb({functionName:s,cause:e}):[UUe,Qc.code].includes(c)&&(u||d||f||p)||c===Ti.code&&d==="execution reverted"&&u?new Uf({abi:t,data:typeof u=="object"?u.data:u,functionName:s,message:a instanceof Rn?d:p??f,cause:e}):e;return new ab(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:s,sender:i})}var UUe,p0=b(()=>{l();Qr();nt();ou();fs();Lf();UUe=3});function Qre(e){let t=Pt(`0x${e.substring(4)}`).substring(26);return Kc(`0x${t}`)}var Xre=b(()=>{l();Zs();Ks()});function DUe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function fD(e,t,r){return e&t^~e&r}function pD(e,t,r){return e&t^e&r^t&r}var db,Mf,hD=b(()=>{l();Tf();db=class extends $h{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=EI(this.buffer)}update(t){If(this),t=vg(t),eu(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f{l();hD();Tf();LUe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),h0=new Uint32Array(64),kI=class extends db{constructor(t=32){super(64,t,8,!1),this.A=Mf[0]|0,this.B=Mf[1]|0,this.C=Mf[2]|0,this.D=Mf[3]|0,this.E=Mf[4]|0,this.F=Mf[5]|0,this.G=Mf[6]|0,this.H=Mf[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)h0[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=h0[f-15],h=h0[f-2],y=qc(p,7)^qc(p,18)^p>>>3,w=qc(h,17)^qc(h,19)^h>>>10;h0[f]=w+h0[f-7]+y+h0[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=qc(a,6)^qc(a,11)^qc(a,25),h=d+p+fD(a,c,u)+LUe[f]+h0[f]|0,w=(qc(n,2)^qc(n,13)^qc(n,22))+pD(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){ba(h0)}destroy(){this.set(0,0,0,0,0,0,0,0),ba(this.buffer)}},Pg=Ww(()=>new kI)});var UI,gD,ene=b(()=>{l();Tf();UI=class extends $h{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,bre(t);let n=vg(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew UI(e,t).update(r).digest();gD.create=(e,t)=>new UI(e,t)});function fb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function $f(e){if(!fb(e))throw new Error("Uint8Array expected")}function pb(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function H4(e){let t=e.toString(16);return t.length&1?"0"+t:t}function nne(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?xD:BigInt("0x"+e)}function hb(e){if($f(e),one)return e.toHex();let t="";for(let r=0;r=Hf._0&&e<=Hf._9)return e-Hf._0;if(e>=Hf.A&&e<=Hf.F)return e-(Hf.A-10);if(e>=Hf.a&&e<=Hf.f)return e-(Hf.a-10)}function $4(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(one)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oxD;e>>=bD,t+=1);return t}function ine(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=wD(e),o=wD(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=wD(0))=>{o=a(rne([0]),f),n=a(),f.length!==0&&(o=a(rne([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}function zf(e,t,r={}){let n=(o,s,i)=>{let a=HUe[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function AD(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var xD,bD,one,MUe,Hf,yD,Rg,wD,rne,HUe,mb=b(()=>{l();xD=BigInt(0),bD=BigInt(1);one=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",MUe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Hf={_0:48,_9:57,A:65,F:70,a:97,f:102};yD=e=>typeof e=="bigint"&&xD<=e;Rg=e=>(bD<new Uint8Array(e),rne=e=>Uint8Array.from(e);HUe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||fb(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function On(e,t){let r=e%t;return r>=Xs?r:t+r}function Ca(e,t,r){let n=e;for(;t-- >Xs;)n*=n,n%=r;return n}function LI(e,t){if(e===Xs)throw new Error("invert: expected non-zero number");if(t<=Xs)throw new Error("invert: expected positive modulus, got "+t);let r=On(e,t),n=t,o=Xs,s=ps,i=ps,a=Xs;for(;r!==Xs;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ps)throw new Error("invert: does not exist");return On(o,t)}function dne(e,t){let r=(e.ORDER+ps)/cne,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function FUe(e,t){let r=(e.ORDER-lne)/une,n=e.mul(t,Og),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Og),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function zUe(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return dne;let s=o.pow(n,t),i=(t+ps)/Og;return function(c,u){if(c.is0(u))return u;if(ane(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ps<(n[o]="function",n),t);return zf(e,r)}function qUe(e,t,r){if(rXs;)r&ps&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ps;return n}function gb(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function ane(e,t){let r=(e.ORDER-ps)/Og,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function CD(e,t){t!==void 0&&xg(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function F4(e,t,r=!1,n={}){if(e<=Xs)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=CD(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:Rg(o),ZERO:Xs,ONE:ps,create:c=>On(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Xs<=c&&cc===Xs,isOdd:c=>(c&ps)===ps,neg:c=>On(-c,e),eql:(c,u)=>c===u,sqr:c=>On(c*c,e),add:(c,u)=>On(c+u,e),sub:(c,u)=>On(c-u,e),mul:(c,u)=>On(c*u,e),pow:(c,u)=>qUe(a,c,u),div:(c,u)=>On(c*LI(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>LI(c,e),sqrt:n.sqrt||(c=>(i||(i=VUe(e)),i(a,c))),toBytes:c=>r?ED(c,s):lu(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?vD(c):_i(c)},invertBatch:c=>gb(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function fne(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function SD(e){let t=fne(e);return t+Math.ceil(t/2)}function pne(e,t,r=!1){let n=e.length,o=fne(t),s=SD(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?vD(e):_i(e),a=On(i,t-ps)+ps;return r?ED(a,o):lu(a,o)}var Xs,ps,Og,$Ue,cne,lne,une,jUe,z4=b(()=>{l();Tf();mb();Xs=BigInt(0),ps=BigInt(1),Og=BigInt(2),$Ue=BigInt(3),cne=BigInt(4),lne=BigInt(5),une=BigInt(8);jUe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function ID(e,t){let r=t.negate();return e?r:t}function gne(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function TD(e,t){gne(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=Rg(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function mne(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=ND);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function WUe(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function KUe(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function PD(e){return yne.get(e)||1}function wne(e,t){return{constTimeNegate:ID,hasPrecomputes(r){return PD(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>hne;)n&ND&&(o=o.add(s)),s=s.double(),n>>=ND;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=TD(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Rg(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{l();z4();mb();hne=BigInt(0),ND=BigInt(1);_D=new WeakMap,yne=new WeakMap});function vne(e){e.lowS!==void 0&&pb("lowS",e.lowS),e.prehash!==void 0&&pb("prehash",e.prehash)}function ZUe(e){let t=RD(e);zf(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function OD(e,t){return hb(lu(e,t))}function GUe(e){let t=ZUe(e),{Fp:r}=t,n=F4(t.n,t.nBitLength),o=t.toBytes||((E,S,_)=>{let O=S.toAffine();return Qs(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,V4),kD),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return Ng(E,Tr,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(fb(E)&&(E=hb(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:_i(Vn("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=On(M,D)),Ff("private key",M,Tr,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=AD((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=AD(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=gb(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(Vn("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return bne(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,V4),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,V4),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;Ff("scalar",S,el,O);let D=w.ZERO;if(S===el)return D;if(this.is0()||S===Tr)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>el||P>el;)N&Tr&&(R=R.add(B)),P&Tr&&(I=I.add(B)),B=B.double(),N>>=Tr,P>>=Tr;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;Ff("scalar",S,Tr,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===el||P===Tr||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===Tr)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===Tr?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return pb("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return pb("isCompressed",S),hb(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=wne(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function YUe(e){let t=RD(e);return zf(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Ene(e){let t=YUe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return On(C,n)}function u(C){return LI(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=GUe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=Qs;return pb("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=_i(H);if(!Ng(k,Tr,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&Tr)===Tr;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>Tr;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>_i(C.slice(A,U));class v{constructor(A,U,H){Ff("r",A,Tr,n),Ff("s",U,Tr,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=Vn("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=Vf.toSig(Vn("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(Vn("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+OD(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return $4(this.toDERHex())}toDERHex(){return Vf.hexFromSig(this)}toCompactRawBytes(){return $4(this.toCompactHex())}toCompactHex(){let A=o;return OD(this.r,A)+OD(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=SD(t.n);return pne(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=Vn("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=_i(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=Rg(s);function N(C){return Ff("num < 2^"+s,C,el,M),lu(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=Vn("msgHash",C),vne(U),j&&(C=Vn("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(Vn("extraEntropy",ye))}let pe=Qs(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===el)return;let ur=c(Et*c(me+At*te));if(ur===el)return;let _r=(kt.x===At?0:2)|Number(kt.y&Tr),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return ine(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=Vn("msgHash",A),U=Vn("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(vne(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||fb(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof Vf.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}function JUe(e,t){let r=e.ORDER,n=el;for(let y=r-Tr;y%m0===el;y/=m0)n+=Tr;let o=n,s=m0<{let x=f,v=e.pow(w,u),T=e.sqr(v);T=e.mul(T,w);let E=e.mul(y,T);E=e.pow(E,c),E=e.mul(E,v),v=e.mul(E,w),T=e.mul(E,y);let S=e.mul(T,v);E=e.pow(S,d);let _=e.eql(E,e.ONE);v=e.mul(T,p),E=e.mul(S,x),T=e.cmov(v,T,_),S=e.cmov(E,S,_);for(let O=o;O>Tr;O--){let D=O-m0;D=m0<{let T=e.sqr(v),E=e.mul(x,v);T=e.mul(T,E);let S=e.pow(T,y);S=e.mul(S,E);let _=e.mul(S,w),O=e.mul(e.sqr(S),v),D=e.eql(O,x),M=e.cmov(_,S,D);return{isValid:D,value:M}}}return h}function Ane(e,t){if(MI(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");let r=JUe(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let o,s,i,a,c,u,d,f;o=e.sqr(n),o=e.mul(o,t.Z),s=e.sqr(o),s=e.add(s,o),i=e.add(s,e.ONE),i=e.mul(i,t.B),a=e.cmov(t.Z,e.neg(s),!e.eql(s,e.ZERO)),a=e.mul(a,t.A),s=e.sqr(i),u=e.sqr(a),c=e.mul(u,t.A),s=e.add(s,c),s=e.mul(s,i),u=e.mul(u,a),c=e.mul(u,t.B),s=e.add(s,c),d=e.mul(o,i);let{isValid:p,value:h}=r(s,u);f=e.mul(o,n),f=e.mul(f,h),d=e.cmov(d,i,p),f=e.cmov(f,h,p);let y=e.isOdd(n)===e.isOdd(f);f=e.cmov(e.neg(f),f,y);let w=gb(e,[a],!0)[0];return d=e.mul(d,w),{x:d,y:f}}}var BD,Vf,el,Tr,m0,V4,kD,UD=b(()=>{l();xne();z4();mb();BD=class extends Error{constructor(t=""){super(t)}},Vf={Err:BD,_tlv:{encode:(e,t)=>{let{Err:r}=Vf;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=H4(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?H4(o.length/2|128):"";return H4(e)+s+o+t},decode(e,t){let{Err:r}=Vf,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Vf;if(egD(e,t,vre(...r)),randomBytes:AI}}function Cne(e,t){let r=n=>Ene({...e,...QUe(n)});return{...r(t),create:r}}var Sne=b(()=>{l();ene();Tf();UD();});function g0(e,t){if(j4(e),j4(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function eDe(e,t){let r=new Uint8Array(e.length);for(let n=0;n255&&(t=n(Qs(DI("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Qs(t,g0(t.length,1)),c=g0(0,s),u=g0(r,2),d=new Array(i),f=n(Qs(c,e,u,g0(0,1),a));d[0]=n(Qs(f,g0(1,1),a));for(let h=1;h<=i;h++){let y=[eDe(f,d[h-1]),g0(h+1,1),a];d[h]=n(Qs(...y))}return Qs(...d).slice(0,r)}function rDe(e,t,r,n,o){if($f(e),$f(t),j4(r),t.length>255){let s=Math.ceil(2*n/8);t=o.create({dkLen:s}).update(DI("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(g0(r,2)).update(t).update(g0(t.length,1)).digest()}function Ine(e,t,r){zf(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;$f(e),j4(t);let u=typeof c=="string"?DI(c):c,d=n.toString(2).length,f=Math.ceil((d+o)/8),p=t*s*f,h;if(a==="xmd")h=tDe(e,u,p,i);else if(a==="xof")h=rDe(e,u,p,o,i);else if(a==="_internal_pass")h=e;else throw new Error('expand must be "xmd" or "xof"');let y=new Array(t);for(let w=0;wArray.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(f=>f.reduce((p,h)=>e.add(e.mul(p,n),h))),[u,d]=gb(e,[i,c],!0);return n=e.mul(s,u),o=e.mul(o,e.mul(a,d)),{x:n,y:o}}}function _ne(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(s){return e.fromAffine(t(s))}function o(s){let i=s.clearCofactor();return i.equals(e.ZERO)?e.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Ine(s,2,{...r,DST:r.DST,...i}),c=n(a[0]),u=n(a[1]);return o(c.add(u))},encodeToCurve(s,i){let a=Ine(s,1,{...r,DST:r.encodeDST,...i});return o(n(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))}}}var XUe,Pne=b(()=>{l();z4();mb();XUe=_i});var Dne={};Te(Dne,{encodeToCurve:()=>uDe,hashToCurve:()=>lDe,schnorr:()=>iDe,secp256k1:()=>ei,secp256k1_hasher:()=>zD});function One(e){let t=K4,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=Ca(d,r,t)*d%t,p=Ca(f,r,t)*d%t,h=Ca(p,$I,t)*u%t,y=Ca(h,o,t)*h%t,w=Ca(y,s,t)*y%t,x=Ca(w,a,t)*w%t,v=Ca(x,c,t)*x%t,T=Ca(v,a,t)*w%t,E=Ca(T,r,t)*d%t,S=Ca(E,i,t)*y%t,_=Ca(S,n,t)*u%t,O=Ca(_,$I,t);if(!y0.eql(y0.sqr(O),e))throw new Error("Cannot find square root");return O}function FI(e,...t){let r=Rne[e];if(r===void 0){let n=Pg(Uint8Array.from(e,o=>o.charCodeAt(0)));r=Qs(n,n),Rne[e]=r}return Pg(Qs(r,...t))}function MD(e){let t=ei.utils.normPrivateKeyToScalar(e),r=FD.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:W4(-t),bytes:$D(r)}}function Bne(e){Ff("x",e,q4,K4);let t=DD(e*e),r=DD(t*e+BigInt(7)),n=One(r);n%$I!==HD&&(n=DD(-n));let o=new FD(e,n,q4);return o.assertValidity(),o}function kne(...e){return W4(yb(FI("BIP0340/challenge",...e)))}function oDe(e){return MD(e).bytes}function sDe(e,t,r=AI(32)){let n=Vn("message",e),{bytes:o,scalar:s}=MD(t),i=Vn("auxRand",r,32),a=LD(s^yb(FI("BIP0340/aux",i))),c=FI("BIP0340/nonce",a,o,n),u=W4(yb(c));if(u===HD)throw new Error("sign failed: k is zero");let{bytes:d,scalar:f}=MD(u),p=kne(d,o,n),h=new Uint8Array(64);if(h.set(d,0),h.set(LD(W4(f+p*s)),32),!Une(h,n,o))throw new Error("sign: Invalid signature produced");return h}function Une(e,t,r){let n=Vn("signature",e,64),o=Vn("message",t),s=Vn("publicKey",r,32);try{let i=Bne(yb(s)),a=yb(n.subarray(0,32));if(!Ng(a,q4,K4))return!1;let c=yb(n.subarray(32,64));if(!Ng(c,q4,HI))return!1;let u=kne(LD(a),$D(i),o),d=nDe(i,c,W4(-u));return!(!d||!d.hasEvenY()||d.toAffine().x!==a)}catch{return!1}}var K4,HI,HD,q4,$I,Nne,y0,ei,Rne,$D,LD,DD,W4,FD,nDe,yb,iDe,aDe,cDe,zD,lDe,uDe,Bg=b(()=>{l();mD();Tf();Sne();Pne();z4();mb();UD();K4=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),HI=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),HD=BigInt(0),q4=BigInt(1),$I=BigInt(2),Nne=(e,t)=>(e+t/$I)/t;y0=F4(K4,void 0,void 0,{sqrt:One}),ei=Cne({a:HD,b:BigInt(7),Fp:y0,n:HI,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=HI,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-q4*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Nne(s*e,t),c=Nne(-n*e,t),u=On(e-a*r-c*o,t),d=On(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},Pg),Rne={};$D=e=>e.toRawBytes(!0).slice(1),LD=e=>lu(e,32),DD=e=>On(e,K4),W4=e=>On(e,HI),FD=ei.ProjectivePoint,nDe=(e,t,r)=>FD.BASE.multiplyAndAddUnsafe(e,t,r);yb=_i;iDe={getPublicKey:oDe,sign:sDe,verify:Une,utils:{randomPrivateKey:ei.utils.randomPrivateKey,lift_x:Bne,pointToBytes:$D,numberToBytesBE:lu,bytesToNumberBE:_i,taggedHash:FI,mod:On}},aDe=Tne(y0,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),cDe=Ane(y0,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:y0.create(BigInt("-11"))}),zD=_ne(ei.ProjectivePoint,e=>{let{x:t,y:r}=cDe(y0.create(e[0]));return aDe(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:y0.ORDER,m:1,k:128,expand:"xmd",hash:Pg}),lDe=zD.hashToCurve,uDe=zD.encodeToCurve});async function zI({hash:e,signature:t}){let r=We(e)?e:wr(e),{secp256k1:n}=await Promise.resolve().then(()=>(Bg(),Dne));return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){let{r:u,s:d,v:f,yParity:p}=t,h=p===void 0&&f!==void 0&&f>=35n?f%2n===0n?1:0:Lne(Number(p??f));return new n.Signature(dt(u),dt(d)).addRecoveryBit(h)}let i=We(t)?t:wr(t);if(gt(i)!==65)throw new Error("invalid signature length");let a=wt(`0x${i.slice(130)}`),c=Lne(a);return n.Signature.fromCompact(i.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Lne(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}var VD=b(()=>{l();qs();Fo();Xr();qe()});async function ti({hash:e,signature:t}){return Qre(await zI({hash:e,signature:t}))}var w0=b(()=>{l();Xre();VD()});function Vo(e,t="hex"){let r=$ne(e),n=Zc(new Uint8Array(r.length));return r.encode(n),t==="hex"?yt(n.bytes):n.bytes}function Mne(e,t="bytes"){return Vo(e,t)}function Hne(e,t="hex"){return Vo(e,t)}function $ne(e){return Array.isArray(e)?dDe(e.map(t=>$ne(t))):fDe(e)}function dDe(e){let t=e.reduce((o,s)=>o+s.length,0),r=Fne(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function fDe(e){let t=typeof e=="string"?qt(e):e,r=Fne(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function Fne(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new G("Length is too large.")}var wb=b(()=>{l();nt();Jw();Pr();qe()});function zne(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,s=Pt(fr(["0x05",Vo([t?oe(t):"0x",o,r?oe(r):"0x"])]));return n==="bytes"?qt(s):s}var Vne=b(()=>{l();Fn();Pr();qe();wb();Ks()});async function b0(e){let{authorization:t}=e,r=e.signature??t;if(typeof r=="object"&&typeof r.yParity=="number"&&r.yParity!==0&&r.yParity!==1)throw new tu({yParity:BigInt(r.yParity)});return ti({hash:zne(t),signature:r})}var Z4=b(()=>{l();zn();w0();Vne()});var bb,jD=b(()=>{l();M4();Ig();nt();zn();bb=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p}){let h=Tg({from:r?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",h].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}});var ri,Pi,x0,v0,E0,A0,C0,S0,I0,T0,ac,Ni,tl=b(()=>{l();Ig();nt();ri=class extends G{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};Object.defineProperty(ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ri,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Pi=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(Pi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});x0=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};Object.defineProperty(x0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});v0=class extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};Object.defineProperty(v0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});E0=class extends G{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` +`),{cause:t,name:"NonceTooLowError"})}};Object.defineProperty(E0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});A0=class extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}};Object.defineProperty(A0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});C0=class extends G{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(` +`),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(C0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance|outoffunds/});S0=class extends G{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(S0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});I0=class extends G{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(I0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});T0=class extends G{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(T0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});ac=class extends G{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${typeof n=="bigint"?` = ${Pn(n)} gwei`:""}).`].join(` +`),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(ac,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Ni=class extends G{constructor({cause:t}){super(`An error occurred while executing: ${t?.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}});function _0(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof G?e.walk(o=>o?.code===ri.code):e;return n instanceof G?new ri({cause:e,message:n.details}):ri.nodeMessage.test(r)?new ri({cause:e,message:e.details}):Pi.nodeMessage.test(r)?new Pi({cause:e,maxFeePerGas:t?.maxFeePerGas}):x0.nodeMessage.test(r)?new x0({cause:e,maxFeePerGas:t?.maxFeePerGas}):v0.nodeMessage.test(r)?new v0({cause:e,nonce:t?.nonce}):E0.nodeMessage.test(r)?new E0({cause:e,nonce:t?.nonce}):A0.nodeMessage.test(r)?new A0({cause:e,nonce:t?.nonce}):C0.nodeMessage.test(r)?new C0({cause:e}):S0.nodeMessage.test(r)?new S0({cause:e,gas:t?.gas}):I0.nodeMessage.test(r)?new I0({cause:e,gas:t?.gas}):T0.nodeMessage.test(r)?new T0({cause:e}):ac.nodeMessage.test(r)?new ac({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new Ni({cause:e})}var G4=b(()=>{l();nt();tl()});function jne(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ni?e:o})();return new bb(n,{docsPath:t,...r})}var qne=b(()=>{l();jD();tl();G4()});function Ri(e,{format:t}){if(!t)return{};let r={};function n(s){let i=Object.keys(s);for(let a of i)a in e&&(r[a]=e[a]),s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&n(s[a])}let o=t(e||{});return n(o),r}var P0=b(()=>{l()});function N0(e,t){return({exclude:r,format:n})=>({exclude:r,format:(o,s)=>{let i=t(o,s);if(r)for(let a of r)delete i[a];return{...i,...n(o,s)}},type:e})}var Y4=b(()=>{l()});function Bn(e,t){let r={};return typeof e.authorizationList<"u"&&(r.authorizationList=pDe(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>yt(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=oe(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=oe(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=oe(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=oe(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=oe(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=oe(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=qD[e.type]),typeof e.value<"u"&&(r.value=oe(e.value)),r}function pDe(e){return e.map(t=>({address:t.address,r:t.r?oe(BigInt(t.r)):t.r,s:t.s?oe(BigInt(t.s)):t.s,chainId:oe(t.chainId),nonce:oe(t.nonce),...typeof t.yParity<"u"?{yParity:oe(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:oe(t.v)}:{}}))}var qD,Wne,rl=b(()=>{l();qe();Y4();qD={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};Wne=N0("transactionRequest",Bn)});function Kne(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new A4({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new A4({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function hDe(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:s}=e,i={};if(s!==void 0&&(i.code=s),t!==void 0&&(i.balance=oe(t)),r!==void 0&&(i.nonce=oe(r)),n!==void 0&&(i.state=Kne(n)),o!==void 0){if(i.state)throw new rb;i.stateDiff=Kne(o)}return i}function xb(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!Ft(r,{strict:!1}))throw new br({address:r});if(t[r])throw new tb({address:r});t[r]=hDe(n)}return t}var VI=b(()=>{l();tc();C4();OI();Gs();qe()});var Zne,Gne,Yne,Jne,Qne,Xne,eoe,toe,roe,noe,ooe,soe,ioe,aoe,coe,loe,uoe,doe,foe,poe,hoe,moe,goe,yoe,woe,boe,xoe,voe,Eoe,Aoe,Coe,Soe,Ioe,Toe,_oe,Poe,Noe,Roe,Ooe,Boe,koe,Uoe,Doe,Loe,Moe,Hoe,$oe,Foe,zoe,Voe,joe,qoe,Woe,Koe,Zoe,Goe,Yoe,Joe,Qoe,Xoe,ese,tse,rse,nse,ose,sse,ise,ase,cse,lse,use,dse,fse,pse,hse,mse,gse,yse,wse,bse,xse,vse,Ese,Ase,Cse,Sse,Ise,Tse,_se,Pse,Nse,Rse,Ose,Bse,kse,R0,jI=b(()=>{l();Zne=2n**(8n-1n)-1n,Gne=2n**(16n-1n)-1n,Yne=2n**(24n-1n)-1n,Jne=2n**(32n-1n)-1n,Qne=2n**(40n-1n)-1n,Xne=2n**(48n-1n)-1n,eoe=2n**(56n-1n)-1n,toe=2n**(64n-1n)-1n,roe=2n**(72n-1n)-1n,noe=2n**(80n-1n)-1n,ooe=2n**(88n-1n)-1n,soe=2n**(96n-1n)-1n,ioe=2n**(104n-1n)-1n,aoe=2n**(112n-1n)-1n,coe=2n**(120n-1n)-1n,loe=2n**(128n-1n)-1n,uoe=2n**(136n-1n)-1n,doe=2n**(144n-1n)-1n,foe=2n**(152n-1n)-1n,poe=2n**(160n-1n)-1n,hoe=2n**(168n-1n)-1n,moe=2n**(176n-1n)-1n,goe=2n**(184n-1n)-1n,yoe=2n**(192n-1n)-1n,woe=2n**(200n-1n)-1n,boe=2n**(208n-1n)-1n,xoe=2n**(216n-1n)-1n,voe=2n**(224n-1n)-1n,Eoe=2n**(232n-1n)-1n,Aoe=2n**(240n-1n)-1n,Coe=2n**(248n-1n)-1n,Soe=2n**(256n-1n)-1n,Ioe=-(2n**(8n-1n)),Toe=-(2n**(16n-1n)),_oe=-(2n**(24n-1n)),Poe=-(2n**(32n-1n)),Noe=-(2n**(40n-1n)),Roe=-(2n**(48n-1n)),Ooe=-(2n**(56n-1n)),Boe=-(2n**(64n-1n)),koe=-(2n**(72n-1n)),Uoe=-(2n**(80n-1n)),Doe=-(2n**(88n-1n)),Loe=-(2n**(96n-1n)),Moe=-(2n**(104n-1n)),Hoe=-(2n**(112n-1n)),$oe=-(2n**(120n-1n)),Foe=-(2n**(128n-1n)),zoe=-(2n**(136n-1n)),Voe=-(2n**(144n-1n)),joe=-(2n**(152n-1n)),qoe=-(2n**(160n-1n)),Woe=-(2n**(168n-1n)),Koe=-(2n**(176n-1n)),Zoe=-(2n**(184n-1n)),Goe=-(2n**(192n-1n)),Yoe=-(2n**(200n-1n)),Joe=-(2n**(208n-1n)),Qoe=-(2n**(216n-1n)),Xoe=-(2n**(224n-1n)),ese=-(2n**(232n-1n)),tse=-(2n**(240n-1n)),rse=-(2n**(248n-1n)),nse=-(2n**(256n-1n)),ose=2n**8n-1n,sse=2n**16n-1n,ise=2n**24n-1n,ase=2n**32n-1n,cse=2n**40n-1n,lse=2n**48n-1n,use=2n**56n-1n,dse=2n**64n-1n,fse=2n**72n-1n,pse=2n**80n-1n,hse=2n**88n-1n,mse=2n**96n-1n,gse=2n**104n-1n,yse=2n**112n-1n,wse=2n**120n-1n,bse=2n**128n-1n,xse=2n**136n-1n,vse=2n**144n-1n,Ese=2n**152n-1n,Ase=2n**160n-1n,Cse=2n**168n-1n,Sse=2n**176n-1n,Ise=2n**184n-1n,Tse=2n**192n-1n,_se=2n**200n-1n,Pse=2n**208n-1n,Nse=2n**216n-1n,Rse=2n**224n-1n,Ose=2n**232n-1n,Bse=2n**240n-1n,kse=2n**248n-1n,R0=2n**256n-1n});function jn(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,s=t?ft(t):void 0;if(s&&!Ft(s.address))throw new br({address:s.address});if(o&&!Ft(o))throw new br({address:o});if(r&&r>R0)throw new Pi({maxFeePerGas:r});if(typeof n=="bigint"&&typeof r=="bigint"&&n>r)throw new ac({maxFeePerGas:r,maxPriorityFeePerGas:n})}var nl=b(()=>{l();tn();jI();tc();tl();Gs()});var O0,uu,vb,Eb=b(()=>{l();Ig();nt();O0=class extends G{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}},uu=class extends G{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}},vb=class extends G{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Pn(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}});var du,J4=b(()=>{l();nt();du=class extends G{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}});function jf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?wt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?wt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Q4[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=mDe(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}function mDe(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var Q4,Use,Ab=b(()=>{l();Xr();Y4();Q4={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};Use=N0("transaction",jf)});function qf(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:jf(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}var Dse,X4=b(()=>{l();Y4();Ab();Dse=N0("block",qf)});async function xn(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let s=o??!1,i=r!==void 0?oe(r):void 0,a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,s]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[i||n,s]},{dedupe:!!i}),!a)throw new du({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||qf)(a,"getBlock")}var fu=b(()=>{l();J4();qe();X4()});async function Cb(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}var qI=b(()=>{l()});async function Lse(e,t){return WD(e,t)}async function WD(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let s=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof s=="function"){let a=r||await ue(e,xn,"getBlock")({}),c=await s({block:a,client:e,request:o});if(c===null)throw new Error;return c}if(typeof s<"u")return s;let i=await e.request({method:"eth_maxPriorityFeePerGas"});return dt(i)}catch{let[s,i]=await Promise.all([r?Promise.resolve(r):ue(e,xn,"getBlock")({}),ue(e,Cb,"getGasPrice")({})]);if(typeof s.baseFeePerGas!="bigint")throw new uu;let a=i-s.baseFeePerGas;return a<0n?0n:a}}var KD=b(()=>{l();Eb();Xr();_t();fu();qI()});async function Mse(e,t){return WI(e,t)}async function WI(e,t){let{block:r,chain:n=e.chain,request:o,type:s="eip1559"}=t||{},i=await(async()=>typeof n?.fees?.baseFeeMultiplier=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:o}):n?.fees?.baseFeeMultiplier??1.2)();if(i<1)throw new O0;let c=10**(i.toString().split(".")[1]?.length??0),u=p=>p*BigInt(Math.round(i*c))/BigInt(c),d=r||await ue(e,xn,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas=="function"){let p=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:o,type:s});if(p!==null)return p}if(s==="eip1559"){if(typeof d.baseFeePerGas!="bigint")throw new uu;let p=typeof o?.maxPriorityFeePerGas=="bigint"?o.maxPriorityFeePerGas:await WD(e,{block:d,chain:n,request:o}),h=u(d.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+p,maxPriorityFeePerGas:p}}return{gasPrice:o?.gasPrice??u(await ue(e,Cb,"getGasPrice")({}))}}var ZD=b(()=>{l();Eb();_t();KD();fu();qI()});function ni(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new G("`requireCanonical` can only be provided when `blockHash` is set.");return t?o?{blockHash:t,requireCanonical:o}:{blockHash:t}:typeof r=="bigint"?oe(r):n??"latest"}var B0=b(()=>{l();nt();qe()});async function k0(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),a=await e.request({method:"eth_getTransactionCount",params:[t,i]},{dedupe:typeof n=="bigint"||r!==void 0});return wt(a)}var e3=b(()=>{l();B0();Xr()});var Wf,U0,Sb,kg,Kf,Ug=b(()=>{l();nt();Wf=class extends G{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}},U0=class extends G{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} \u2013 ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} \u2013 ${t.name}`],name:"ChainMismatchError"})}},Sb=class extends G{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(` +`),{name:"ChainNotFoundError"})}},kg=class extends G{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}},Kf=class extends G{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}});function D0(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>qt(s)):e.blobs,o=[];for(let s of n)o.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?o:o.map(s=>yt(s))}var t3=b(()=>{l();Pr();qe()});function L0(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>qt(i)):e.blobs,o=typeof e.commitments[0]=="string"?e.commitments.map(i=>qt(i)):e.commitments,s=[];for(let i=0;iyt(i))}var r3=b(()=>{l();Pr();qe()});var Hse,$se=b(()=>{l();mD();Hse=Pg});function KI(e,t){let r=t||"hex",n=Hse(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var GD=b(()=>{l();$se();qs();Pr();qe()});function Ib(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),o=KI(t,"bytes");return o.set([r],0),n==="bytes"?o:yt(o)}var ZI=b(()=>{l();qe();GD()});function Tb(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),o=[];for(let s of t)o.push(Ib({commitment:s,to:n,version:r}));return o}var GI=b(()=>{l();ZI()});var YI,_b,JI,QI,YD=b(()=>{l();nt();YI=class extends G{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}},_b=class extends G{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}},JI=class extends G{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}},QI=class extends G{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}});function XI(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?qt(e.data):e.data,n=gt(r);if(!n)throw new _b;if(n>761855)throw new YI({maxSize:761855,size:n});let o=[],s=!0,i=0;for(;s;){let a=Zc(new Uint8Array(131072)),c=0;for(;c<4096;){let u=r.slice(i,i+31);if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),s=!1;break}c++,i+=31}o.push(a)}return t==="bytes"?o.map(a=>a.bytes):o.map(a=>yt(a.bytes))}var JD=b(()=>{l();YD();Jw();Fo();Pr();qe()});function M0(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??XI({data:t,to:n}),s=e.commitments??D0({blobs:o,kzg:r,to:n}),i=e.proofs??L0({blobs:o,commitments:s,kzg:r,to:n}),a=[];for(let c=0;c{l();t3();r3();JD()});function Pb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new nb({transaction:e})}var e9=b(()=>{l();zn()});function H0(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ni?e:o})();return new ib(n,{docsPath:t,...r})}var o3=b(()=>{l();tl();zn();G4()});async function hs(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return wt(t)}var Zf=b(()=>{l();Xr()});async function Nb(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:s=e.chain,blobVersionedHashes:i,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,nonceManager:w,to:x,type:v,value:T,...E}=t,S=await(async()=>{if(!r||!w||typeof y<"u")return y;let M=ft(r),N=s?s.id:await ue(e,hs,"getChainId")({});return await w.consume({address:M.address,chainId:N,client:e})})();jn(t);let _=s?.formatters?.transactionRequest?.format,D=(_||Bn)({...Ri(E,{format:_}),account:r?ft(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:i,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:S,to:x,type:v,value:T},"fillTransaction");try{let M=await e.request({method:"eth_fillTransaction",params:[D]}),L=(s?.formatters?.transaction?.format||jf)(M.tx);delete L.blockHash,delete L.blockNumber,delete L.r,delete L.s,delete L.transactionIndex,delete L.v,delete L.yParity,typeof L.maxFeePerGas<"u"&&delete L.gasPrice,L.data=L.input;let P=typeof L.feePayerSignature<"u"&&L.feePayerSignature!==null;if(P&&typeof S<"u"&&BigInt(L.nonce)!==BigInt(S))throw new Wh({filledNonce:L.nonce,requestedNonce:S});if(!P){L.gas&&(L.gas=t.gas??L.gas),L.gasPrice&&(L.gasPrice=t.gasPrice??L.gasPrice),L.maxFeePerBlobGas&&(L.maxFeePerBlobGas=t.maxFeePerBlobGas??L.maxFeePerBlobGas),L.maxFeePerGas&&(L.maxFeePerGas=t.maxFeePerGas??L.maxFeePerGas),L.maxPriorityFeePerGas&&(L.maxPriorityFeePerGas=t.maxPriorityFeePerGas??L.maxPriorityFeePerGas),typeof L.nonce<"u"&&typeof t.nonce<"u"&&(L.nonce=typeof L.nonce=="bigint"?BigInt(t.nonce):t.nonce);let R=await(async()=>{if(typeof s?.fees?.baseFeeMultiplier=="function"){let A=await ue(e,xn,"getBlock")({});return s.fees.baseFeeMultiplier({block:A,client:e,request:t})}return s?.fees?.baseFeeMultiplier??1.2})();if(R<1)throw new O0;let B=10**(R.toString().split(".")[1]?.length??0),C=A=>A*BigInt(Math.round(R*B))/BigInt(B);L.maxFeePerGas&&!t.maxFeePerGas&&(L.maxFeePerGas=C(L.maxFeePerGas)),L.gasPrice&&!t.gasPrice&&(L.gasPrice=C(L.gasPrice))}return{raw:M.raw,transaction:{from:D.from,...L},...M.capabilities?{capabilities:M.capabilities}:{}}}catch(M){throw H0(M,{...t,chain:e.chain})}}var t9=b(()=>{l();tn();Eb();zn();o3();P0();Ab();rl();_t();nl();fu();Zf()});async function pu(e,t){let r={...t};typeof r.account>"u"&&(r.account=e.account),r.parameters??=s3;let{account:n,chain:o=e.chain,nonceManager:s,parameters:i}=r,a=(()=>{if(typeof o?.prepareTransactionRequest=="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt}})(),c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:o?o.id:(c=await ue(e,hs,"getChainId")({}),c))}let d=n&&ft(n),f=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"})??r,f??=r.nonce;let D=r.account??r.from;d=D?ft(D):void 0}if(i.includes("nonce")&&typeof f>"u"&&d&&s){let D=await u();f=await s.consume({address:d.address,chainId:D,client:e})}let p=(i.includes("blobVersionedHashes")||i.includes("sidecars"))&&r.kzg&&r.blobs?!1:i.length>0&&"feePayer"in r&&r.feePayer&&!("feePayerSignature"in r&&r.feePayerSignature)?!0:QD.get(e.uid)===!1||!["fees","gas"].some(M=>i.includes(M))?!1:!!(i.includes("chainId")&&typeof r.chainId!="number"||i.includes("nonce")&&typeof f!="number"||i.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||i.includes("gas")&&typeof r.gas!="bigint"),h,y=D=>ue(e,Nb,"fillTransaction")({...D,nonce:f}).then(M=>{let{chainId:N,from:L,gas:P,gasPrice:R,nonce:I,maxFeePerBlobGas:B,maxFeePerGas:C,maxPriorityFeePerGas:A,type:U,...H}=M.transaction,k="feeToken"in H?H.feeToken:void 0,F="feePayerSignature"in H&&H.feePayerSignature!==null&&typeof H.feePayerSignature<"u",j=typeof k<"u"&&k!==null&&(!("feeToken"in D)||F);QD.set(e.uid,!0),h=N;let{feeToken:W,...ae}=D;return{...F?ae:D,...L?{from:L}:{},...U&&!D.type?{type:U}:{},...typeof P<"u"?{gas:P}:{},...typeof R<"u"?{gasPrice:R}:{},...typeof I<"u"?{nonce:I}:{},...typeof B<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxFeePerBlobGas:B}:{},...typeof C<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxFeePerGas:C}:{},...typeof A<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxPriorityFeePerGas:A}:{},..."nonceKey"in H&&typeof H.nonceKey<"u"?{nonceKey:H.nonceKey}:{},..."validBefore"in H&&H.validBefore!==null&&typeof H.validBefore<"u"?{validBefore:H.validBefore}:{},..."validAfter"in H&&H.validAfter!==null&&typeof H.validAfter<"u"?{validAfter:H.validAfter}:{},..."keyAuthorization"in H&&typeof H.keyAuthorization<"u"&&H.keyAuthorization!==null&&!("keyAuthorization"in D)?{keyAuthorization:H.keyAuthorization}:{},..."feePayerSignature"in H&&typeof H.feePayerSignature<"u"&&H.feePayerSignature!==null?{feePayerSignature:H.feePayerSignature}:{},...j?{feeToken:k}:{},...M.capabilities?{_capabilities:M.capabilities}:{}}}),w=(D,M)=>{let N=D;if(N.name!=="TransactionExecutionError")return M;if(N.walk?.(I=>I instanceof Wh)||N.walk?.(I=>I.name==="ExecutionRevertedError"))throw D;return N.walk?.(I=>{let B=I;return B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"||B.message?.includes("eth_fillTransaction is not available")})&&QD.set(e.uid,!1),M},x=p?await y(r).catch(async D=>{let M=a?.fn&&a.runAt?.includes("afterFillTransactionError")?await a.fn({...r,chain:o},{client:e,error:D,phase:"afterFillTransactionError"}):void 0;return M?y(M).catch(N=>w(N,M)):w(D,r)}):r;if(f??=x.nonce,r={...x,...d?{from:d?.address}:{},...typeof f<"u"?{nonce:f}:{}},typeof h<"u"&&(r.chainId??=o?.id??h,r.chainId!==h))throw new U0({chain:o?.id===r.chainId?o:{id:r.chainId,name:"Unknown"},currentChainId:h});let{blobs:v,gas:T,kzg:E,type:S}=r;a?.fn&&a.runAt?.includes("beforeFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"})??r);let _;async function O(){return _||(_=await ue(e,xn,"getBlock")({blockTag:"latest"}),_)}if(i.includes("nonce")&&typeof f>"u"&&d&&!s&&(r.nonce=await ue(e,k0,"getTransactionCount")({address:d.address,blockTag:"pending"})),(i.includes("blobVersionedHashes")||i.includes("sidecars"))&&v&&E){let D=D0({blobs:v,kzg:E});if(i.includes("blobVersionedHashes")){let M=Tb({commitments:D,to:"hex"});r.blobVersionedHashes=M}if(i.includes("sidecars")){let M=L0({blobs:v,commitments:D,kzg:E}),N=M0({blobs:v,commitments:D,proofs:M,to:"hex"});r.sidecars=N}}if(i.includes("chainId")&&(r.chainId=await u()),(i.includes("fees")||i.includes("type"))&&typeof S>"u")try{r.type=Pb(r)}catch{let D=Fse.get(e.uid);typeof D>"u"&&(D=typeof(await O())?.baseFeePerGas=="bigint",Fse.set(e.uid,D)),r.type=D?"eip1559":"legacy"}if(i.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let D=await O(),{maxFeePerGas:M,maxPriorityFeePerGas:N}=await WI(e,{block:D,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&typeof r.maxFeePerGas=="bigint"&&r.maxFeePerGas"u"){let D=await O(),{gasPrice:M}=await WI(e,{block:D,chain:o,request:r,type:"legacy"});r.gasPrice=M}}return i.includes("gas")&&typeof T>"u"&&(r.gas=await ue(e,Ob,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"})??r),jn(r),delete r.parameters,r}var s3,Fse,QD,Rb=b(()=>{l();tn();ZD();r9();fu();e3();Ug();Eb();zn();t3();r3();GI();n3();_t();_f();nl();e9();t9();Zf();s3=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Fse=new Map,QD=new xo(128)});async function Ob(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ft(r):void 0,s=t.stateOverride!==void 0||typeof t.blockNumber=="bigint"||t.blockTag!==void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local"||s)return["blobVersionedHashes"]})();try{let a=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await b0({authorization:t.authorizationList[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:c,authorizationList:u,blobs:d,blobVersionedHashes:f,blockNumber:p,blockTag:h,data:y,gas:w,gasPrice:x,maxFeePerBlobGas:v,maxFeePerGas:T,maxPriorityFeePerGas:E,nonce:S,value:_,stateOverride:O,...D}=n?await pu(e,{...t,parameters:i,to:a}):t;if(w&&t.gas!==w&&!s)return w;let N=(typeof p=="bigint"?oe(p):void 0)||h,L=xb(O);jn(t);let P=e.chain?.formatters?.transactionRequest?.format,I=(P||Bn)({...Ri(D,{format:P}),account:o,accessList:c,authorizationList:u,blobs:d,blobVersionedHashes:f,data:y,gasPrice:x,maxFeePerBlobGas:v,maxFeePerGas:T,maxPriorityFeePerGas:E,nonce:S,to:a,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:L?[I,N??e.experimental_blockTag??"latest",L]:N?[I,N]:[I]}))}catch(a){throw jne(a,{...t,account:o,chain:e.chain})}}var r9=b(()=>{l();tn();nt();Z4();qe();qne();P0();rl();VI();nl();Rb()});async function $0(e,t){let{abi:r,address:n,args:o,functionName:s,dataSuffix:i=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Wt({abi:r,args:o,functionName:s});try{return await ue(e,Ob,"estimateGas")({data:`${c}${i?i.replace("0x",""):""}`,to:n,...a})}catch(u){let d=a.account?ft(a.account):void 0;throw Js(u,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:d?.address})}}var i3=b(()=>{l();tn();us();p0();_t();r9()});function xr(e,t){if(!Ft(e,{strict:!1}))throw new br({address:e});if(!Ft(t,{strict:!1}))throw new br({address:t});return e.toLowerCase()===t.toLowerCase()}var Oi=b(()=>{l();tc();Gs()});function qn(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var hu=b(()=>{l()});function Yf(e){let{abi:t,data:r,eventName:n,strict:o,topics:s}=e,i=o??!0,a=t.filter(p=>p.type==="event"&&"name"in p),c=s[0],u=c?a.find(p=>!p.anonymous&&c===Wc(no(p))):void 0,d=u?[u]:wDe(a,s.length,n);if(d.length>1)throw new Gf(d.map(p=>p.name));let f=d[0];if(!f)throw c?new Jl(c,{docsPath:XD}):new Yl({docsPath:XD});return xDe({abiItem:f,argTopics:f.anonymous?s:s.slice(1),data:r,strict:i})}function wDe(e,t,r){return(r?e.filter(o=>o.name===r):e.every(o=>o.anonymous)?e:[]).filter(o=>o.anonymous&&bDe(o)===t)}function bDe(e){return e.inputs?.filter(t=>t.indexed).length??0}function xDe({abiItem:e,argTopics:t,data:r,strict:n}){let{name:o,inputs:s}=e,i=s?.some(p=>!("name"in p&&p.name)),a=i?[]:{},c=s.map((p,h)=>[p,h]).filter(([p])=>"indexed"in p&&p.indexed),u=[];for(let p=0;p!("indexed"in p&&p.indexed)),f=n?d:[...u.map(([p])=>p),...d];if(f.length>0){if(r&&r!=="0x")try{let p=Ys(f,r);if(p){let h=0;if(!n)for(let[y,w]of u)a[i?w:y.name||w]=p[h++];if(i)for(let y=0;y0?a:void 0}}function vDe({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Ys([e],t)||[])[0]}var XD,Gf,a3=b(()=>{l();Qr();nt();aD();Fo();Kw();zh();Cf();XD="/docs/contract/decodeEventLog";Gf=class extends G{constructor(t){let r=new Set(t).size===t.length;super("Ambiguous anonymous event log.",{docsPath:XD,metaMessages:[`Matched ${t.map(n=>`\`${n}\``).join(", ")}.`,"These events take the same number of indexed topics.",r?"Pass `eventName` to choose one.":"Pass an `abi` that holds only the event to decode."],name:"AbiEventAmbiguityError"})}}});function cc(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),i=t.filter(c=>c.type==="event").map(c=>({abi:c,selector:Wc(c)})),a=s?i.filter(c=>c.abi.anonymous&&s.includes(c.abi.name)):i.every(c=>c.abi.anonymous)?i:[];return n.map(c=>{let u=typeof c.blockNumber=="string"?qn(c):c,d=i.filter(y=>!y.abi.anonymous&&u.topics[0]===y.selector),f=(()=>{if(d.length>0)return s?d.filter(w=>s.includes(w.abi.name)):d;let y=a.filter(w=>(w.abi.inputs?.filter(x=>x.indexed).length??0)===u.topics.length);return y.length===1?y:[]})();if(f.length===0)return null;let p,h;for(let y of f)try{p=Yf({...u,abi:[y.abi],strict:!0}),h=y;break}catch{}if(!p&&!o){let y=f[0];if(!y||y.abi.anonymous)return null;h=y;try{p=Yf({data:u.data,topics:u.topics,abi:[h.abi],strict:!1})}catch{let w=h.abi.inputs?.some(x=>!("name"in x&&x.name));p={eventName:h.abi.name,args:w?[]:{}}}}return!p||!h||s&&!s.includes(p.eventName)||!EDe({anonymous:h.abi.anonymous,args:p.args,inputs:h.abi.inputs,matchArgs:r,topics:u.topics})?null:{...p,...u}}).filter(Boolean)}function EDe(e){let{anonymous:t,args:r,inputs:n,matchArgs:o,topics:s}=e;if(!o)return!0;if(!r)return!1;let i=n.filter(c=>c.indexed).slice(0,t?s.length:s.length-1);function a(c,u,d){try{if(c.type==="address")return xr(u,d);if(i.includes(c)&&(c.type==="string"||c.type==="bytes")){let f=c.type==="string"?zo(u):un(u);return Pt(f)===d}return typeof u=="string"&&typeof d=="string"&&Eg.test(c.type)?u.toLowerCase()===d.toLowerCase():Rf.test(c.type)&&(typeof u=="number"||typeof u=="bigint")&&(typeof d=="number"||typeof d=="bigint")?BigInt(u)===BigInt(d):u===d}catch{return!1}}return Array.isArray(r)&&Array.isArray(o)?o.every((c,u)=>{if(c==null)return!0;let d=n[u];return d?(Array.isArray(c)?c:[c]).some(p=>a(d,p,r[u])):!1}):typeof r=="object"&&!Array.isArray(r)&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).every(([c,u])=>{if(u==null)return!0;let d=n.find(p=>p.name===c);return d?(Array.isArray(u)?u:[u]).some(p=>a(d,p,r[c])):!1}):!1}var Dg=b(()=>{l();Oi();Pr();hu();Ks();Kw();P4();a3()});function Bb(e){if(!(e instanceof G))return!0;let t=e.walk(r=>r instanceof Nr||r instanceof Rn);return t?t instanceof Rn&&t.code===429||t instanceof Nr&&t.status===void 0?!1:t.status!==401&&t.status!==403&&t.status!==429:!0}var n9=b(()=>{l();nt();fs()});async function*o9(e,t){let{address:r,args:n,blockRange:o=1000n,event:s,events:i,fromBlock:a,strict:c,toBlock:u="latest"}=t;if(o<1n)throw new G("`blockRange` must be at least 1n.");let d=typeof u=="bigint"?u:(await ue(e,xn,"getBlock")({blockTag:u})).number,f=o,p=a;for(;p<=d;){let h=p+f-1n,y=h{if(p===y||!Bb(x))throw x});if(!w){f=(y-p+1n)/2n;continue}yield{endBlock:d,fromBlock:p,logs:w,toBlock:y},p=y+1n,f=f*2n{l();nt();_t();fu();c3();n9()});async function F0(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:s,events:i,args:a,blockRange:c,strict:u}={}){if(c!==void 0){let w=[];for await(let x of o9(e,{address:t,args:a,blockRange:c,event:s,events:i,fromBlock:n,strict:u,toBlock:o}))for(let v of x.logs)w.push(v);return w}let d=u??!1,f=i??(s?[s]:void 0),p=[];f&&(p=[f.flatMap(x=>nc({abi:[x],eventName:x.name,args:i?void 0:a}))],s&&(p=p[0]));let h;r?h=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]}):h=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n=="bigint"?oe(n):n,toBlock:typeof o=="bigint"?oe(o):o}]});let y=h.map(w=>qn(w));return f?cc({abi:f,args:a,logs:y,strict:d}):y}var c3=b(()=>{l();Cg();Dg();qe();hu();eL()});async function kb(e,t){let{abi:r,address:n,args:o,blockHash:s,eventName:i,fromBlock:a,toBlock:c,strict:u}=t,d=i?ls({abi:r,name:i}):void 0,f=d?void 0:r.filter(p=>p.type==="event");return ue(e,F0,"getLogs")({address:n,args:o,blockHash:s,event:d,events:f,fromBlock:a,toBlock:c,strict:u})}var s9=b(()=>{l();Bf();_t();c3()});function dn(e){let{abi:t,args:r,functionName:n,data:o}=e,s=t[0];if(n){let a=ls({abi:t,args:r,name:n});if(!a)throw new wa(n,{docsPath:tL});s=a}if(s.type!=="function")throw new wa(void 0,{docsPath:tL});if(!s.outputs)throw new Dh(s.name,{docsPath:tL});let i=Ys(s.outputs,o);if(i&&i.length>1)return i;if(i&&i.length===1)return i[0]}var tL,lc=b(()=>{l();Qr();zh();Bf();tL="/docs/contract/decodeFunctionResult"});var zse,Vse=b(()=>{l();zse="0.1.1"});function jse(){return zse}var qse=b(()=>{l();Vse()});function Wse(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?Wse(e.cause,t):t?null:e}var Ke,Bi=b(()=>{l();qse();Ke=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=r.docsOrigin??e.prototype.docsOrigin,i=`${s}${o??""}`,a=!!(r.version??e.prototype.showVersion),c=r.version??e.prototype.version,u=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o||a?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(d=>typeof d=="string").join(` +`);super(u,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=i,this.docsOrigin=s,this.docsPath=o,this.shortMessage=t,this.showVersion=a,this.version=c}walk(t){return Wse(this,t)}};Object.defineProperty(Ke,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${jse()}`}});Ke.setStaticOptions(Ke.defaultStaticOptions)});function Ub(e,t){if(uc(e)>t)throw new i9({givenSize:uc(e),maxSize:t})}function Kse(e,t){if(typeof t=="number"&&t>0&&t>uc(e)-1)throw new l3({offset:t,position:"start",size:uc(e)})}function Zse(e,t,r){if(typeof t=="number"&&typeof r=="number"&&uc(e)!==r-t)throw new l3({offset:r,position:"end",size:uc(e)})}function rL(e){if(e>=Jf.zero&&e<=Jf.nine)return e-Jf.zero;if(e>=Jf.A&&e<=Jf.F)return e-(Jf.A-10);if(e>=Jf.a&&e<=Jf.f)return e-(Jf.a-10)}function Gse(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new a9({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;s{l();mu();Jf={zero:48,nine:57,A:65,F:70,a:97,f:102}});function Db(e,t){if(Mr(e)>t)throw new c9({givenSize:Mr(e),maxSize:t})}function Jse(e,t){if(typeof t=="number"&&t>0&&t>Mr(e)-1)throw new u3({offset:t,position:"start",size:Mr(e)})}function Qse(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Mr(e)!==r-t)throw new u3({offset:r,position:"end",size:Mr(e)})}function oL(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new l9({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function Xse(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;s{l();io()});function z0(e,t,r){return JSON.stringify(e,(n,o)=>typeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+CDe:o,r)}var CDe,d3=b(()=>{l();CDe="#__bigint"});function TDe(e){if(!(e instanceof Uint8Array)){if(!e)throw new Lb(e);if(typeof e!="object")throw new Lb(e);if(!("BYTES_PER_ELEMENT"in e))throw new Lb(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new Lb(e)}}function aL(e){return e instanceof Uint8Array?e:typeof e=="string"?Lg(e):_De(e)}function _De(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Lg(e,t={}){let{size:r}=t,n=e.slice(2);n.length%2&&(n=`0${n}`),r&&(Db(e,r),n=n.padEnd(r*2,"0"));let o=n.length/2,s=new Uint8Array(o);for(let i=0,a=0;i1||n[0]>1)throw new iL(n);return!!n[0]}function Xf(e,t={}){let{size:r}=t;typeof r<"u"&&Ub(e,r);let n=vn(e,t);return f9(n,t)}function d9(e,t={}){let{size:r}=t,n=e;return typeof r<"u"&&(Ub(n,r),n=NDe(n)),SDe.decode(n)}function cL(e){return nL(e,{dir:"left"})}function NDe(e){return nL(e,{dir:"right"})}function oie(e){try{return TDe(e),!0}catch{return!1}}var SDe,IDe,iL,Lb,i9,l3,a9,mu=b(()=>{l();Bi();io();Yse();sL();d3();SDe=new TextDecoder,IDe=new TextEncoder;iL=class extends Ke{constructor(t){super(`Bytes value \`${t}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}},Lb=class extends Ke{constructor(t){super(`Value \`${typeof t=="object"?z0(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},i9=class extends Ke{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},l3=class extends Ke{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}},a9=class extends Ke{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function kDe(e,t={}){let{even:r=!1,strict:n=!1}=t;if(!e)throw new p9(e);if(typeof e!="string")throw new p9(e);if(n&&!BDe.test(e))throw new h9(e);if(!e.startsWith("0x"))throw new h9(e);if(r&&e.length%2!==0)throw new m9(e)}function fn(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Hb(e){return e instanceof Uint8Array?vn(e):Array.isArray(e)?vn(new Uint8Array(e)):e}function g9(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Db(r,t.size),ep(r,t.size)):r}function vn(e,t={}){let r="";for(let o=0;os||o>1n;return n<=s?n:n-o-1n}function f9(e,t={}){let{signed:r,size:n}=t;return Number(!r&&!n?e:lL(e,t))}function q0(e,t={}){let{even:r=!1,strict:n=!1}=t;try{return kDe(e,{even:r,strict:n}),!0}catch{return!1}}var RDe,ODe,BDe,V0,p9,h9,m9,c9,u3,l9,io=b(()=>{l();Bi();sL();d3();RDe=new TextEncoder,ODe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),BDe=/^0x[0-9a-fA-F]*$/;V0=class extends Ke{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},p9=class extends Ke{constructor(t){super(`Value \`${typeof t=="object"?z0(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},h9=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},m9=class extends Ke{constructor(t){super(`Hex value \`"${t}"\` is an odd length (${t.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"})}},c9=class extends Ke{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},u3=class extends Ke{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},l9=class extends Ke{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function sie(e){return{address:e.address,amount:Yt(e.amount),index:Yt(e.index),validatorIndex:Yt(e.validatorIndex)}}var iie=b(()=>{l();io()});function w9(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Yt(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Yt(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Yt(e.gasLimit)},...typeof e.number=="bigint"&&{number:Yt(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Yt(e.prevRandao)},...typeof e.time=="bigint"&&{time:Yt(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(sie)}}}var uL=b(()=>{l();io();iie()});var ki,W0,cie,b9,lie,dL,fL,x9,Fb,Hr,uie,die,fie,pie,So=b(()=>{l();ki=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],W0=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],cie=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],b9=[...cie,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],lie=[...cie,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],dL=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],fL=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],x9=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Fb=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],Hr=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],uie=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],die=[{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC1155InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC1155InvalidApprover",type:"error"},{inputs:[{internalType:"uint256",name:"idsLength",type:"uint256"},{internalType:"uint256",name:"valuesLength",type:"uint256"}],name:"ERC1155InvalidArrayLength",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC1155InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC1155InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC1155InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC1155MissingApprovalForAll",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"values",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}],fie=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"event",name:"ApprovalForAll",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"operator",type:"address"},{indexed:!1,name:"approved",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"payable",inputs:[{name:"spender",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"getApproved",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"address"}]},{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"operator",type:"address"}],outputs:[{type:"bool"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"owner",type:"address"}]},{type:"function",name:"safeTransferFrom",stateMutability:"payable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"safeTransferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"id",type:"uint256"},{name:"data",type:"bytes"}],outputs:[]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"index",type:"uint256"}],outputs:[{type:"uint256"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"index",type:"uint256"}],outputs:[{name:"tokenId",type:"uint256"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transferFrom",stateMutability:"payable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}],pie=[{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!0,name:"owner",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],name:"allowance",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],name:"approve",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"asset",outputs:[{name:"assetTokenAddress",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"convertToAssets",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"convertToShares",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"}],name:"deposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxDeposit",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxMint",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxRedeem",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxWithdraw",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"}],name:"mint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewDeposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewMint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewRedeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewWithdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"redeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"totalAssets",outputs:[{name:"totalManagedAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"withdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"}]});var hie,mie=b(()=>{l();hie="0x82ad56cb"});var zb,v9,f3,Mg,Vb=b(()=>{l();zb="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",v9="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",f3="0x608060405234801561001057600080fd5b506040516106ad3803806106ad83398101604081905261002f91610537565b600061003c848484610048565b9050806000526001601ff35b60007f649264926492649264926492649264926492649264926492649264926492649261007483610425565b036101e7576000606080848060200190518101906100929190610590565b60405192955090935091506000906001600160a01b038516906100b69085906105f6565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b908790600401610612565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d1919061064c565b6001600160e01b0319161494505050505061041e565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e906102279087908790600401610612565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610268919061064c565b6001600160e01b03191614905061041e565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061068d83398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e761043e565b5060208201516040808401518451859392600091859190811061030c5761030c610676565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061068d83398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b604080516000808252602082018084528a905260ff841692820192909252606081018590526080810184905260019060a0016020604051602081039080840390855afa1580156103e0573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116158015906104165750886001600160a01b0316816001600160a01b0316145b955050505050505b9392505050565b600060208251101561043657600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461047157600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b838110156104a557818101518382015260200161048d565b50506000910152565b600082601f8301126104bf57600080fd5b81516001600160401b038111156104d8576104d8610474565b604051601f8201601f19908116603f011681016001600160401b038111828210171561050657610506610474565b60405281815283820160200185101561051e57600080fd5b61052f82602083016020870161048a565b949350505050565b60008060006060848603121561054c57600080fd5b83516105578161045c565b6020850151604086015191945092506001600160401b0381111561057a57600080fd5b610586868287016104ae565b9150509250925092565b6000806000606084860312156105a557600080fd5b83516105b08161045c565b60208501519093506001600160401b038111156105cc57600080fd5b6105d8868287016104ae565b604086015190935090506001600160401b0381111561057a57600080fd5b6000825161060881846020870161048a565b9190910192915050565b828152604060208201526000825180604084015261063781606085016020870161048a565b601f01601f1916919091016060019392505050565b60006020828403121561065e57600080fd5b81516001600160e01b03198116811461041e57600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Mg="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"});function tp(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find(i=>"type"in i&&i.type==="constructor");if(!o)throw new Oh({docsPath:pL});if(!("inputs"in o))throw new Gl({docsPath:pL});if(!o.inputs||o.inputs.length===0)throw new Gl({docsPath:pL});let s=oo(o.inputs,r);return fr([n,s])}var pL,p3=b(()=>{l();Qr();Fn();rc();pL="/docs/contract/encodeDeployData"});function Ui({blockNumber:e,chain:t,contract:r}){let n=t?.contracts?.[r];if(!n)throw new Wf({chain:t,contract:{name:r}});if(e!==void 0&&n.blockCreated!==void 0&&n.blockCreated>e)throw new Wf({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}var K0=b(()=>{l();Ug()});function E9(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ni?e:o})();return new Yc(n,{docsPath:t,...r})}var hL=b(()=>{l();ou();tl();G4()});function jb(){let e=()=>{},t=()=>{};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}var A9=b(()=>{l()});function Z0({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let s=async()=>{let d=c();i();let f=d.map(({args:p})=>p);f.length!==0&&new Promise(p=>p(e(f))).then(p=>{o&&Array.isArray(p)&&p.sort(o);for(let h=0;h{for(let h=0;hmL.delete(t),a=()=>c().map(({args:d})=>d),c=()=>mL.get(t)||[],u=d=>mL.set(t,[...c(),d]);return{flush:i,async schedule(d){let{promise:f,resolve:p,reject:h}=jb();return r?.([...a(),d])&&s(),c().length>0?(u({args:d,resolve:p,reject:h}),f):(u({args:d,resolve:p,reject:h}),setTimeout(s,n),f)}}}var mL,h3=b(()=>{l();A9();mL=new Map});var C9,S9,I9,gie=b(()=>{l();so();nt();oc();C9=class extends G{constructor({callbackSelector:t,cause:r,data:n,extraData:o,sender:s,urls:i}){super(r.shortMessage||"An error occurred while fetching for an offchain result.",{cause:r,metaMessages:[...r.metaMessages||[],r.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(a=>` ${kf(a)}`)],` Sender: ${s}`,` Data: ${n}`,` Callback selector: ${t}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}},S9=class extends G{constructor({result:t,url:r}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${kf(r)}`,`Response: ${bt(t)}`],name:"OffchainLookupResponseMalformedError"})}},I9=class extends G{constructor({sender:t,to:r}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${r}`,`OffchainLookup sender address: ${t}`],name:"OffchainLookupSenderMismatchError"})}}});function T9(e){let{abi:t,data:r}=e,n=vo(r,0,4),o=t.find(s=>s.type==="function"&&n===va(no(s)));if(!o)throw new Bw(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:o.name,args:"inputs"in o&&o.inputs&&o.inputs.length>0?Ys(o.inputs,vo(r,4)):void 0}}var gL=b(()=>{l();Qr();Si();Ag();zh();Cf()});function m3(e){let{abi:t,errorName:r,args:n}=e,o=t[0];if(r){let c=ls({abi:t,args:n,name:r});if(!c)throw new pg(r,{docsPath:yL});o=c}if(o.type!=="error")throw new pg(void 0,{docsPath:yL});let s=no(o),i=va(s),a="0x";if(n&&n.length>0){if(!o.inputs)throw new Ow(o.name,{docsPath:yL});a=oo(o.inputs,n)}return fr([i,a])}var yL,wL=b(()=>{l();Qr();Fn();Ag();rc();Cf();Bf();yL="/docs/contract/encodeErrorResult"});function _9(e){let{abi:t,functionName:r,result:n}=e,o=t[0];if(r){let i=ls({abi:t,name:r});if(!i)throw new wa(r,{docsPath:bL});o=i}if(o.type!=="function")throw new wa(void 0,{docsPath:bL});if(!o.outputs)throw new Dh(o.name,{docsPath:bL});let s=(()=>{if(o.outputs.length===0)return[];if(o.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Mh(n)})();return oo(o.outputs,s)}var bL,xL=b(()=>{l();Qr();rc();Bf();bL="/docs/contract/encodeFunctionResult"});function vL(){let e=0,t=[];return{bytes:ol.bytes,queries:ol.queries,async run(r){e>=ol.concurrency?await new Promise(n=>t.push(n)):e++;try{return await r()}finally{let n=t.shift();n?n():e--}}}}async function EL(e){let{data:t,ccipRequest:r,budget:n=vL(),depth:o=0}=e,{args:[s]}=T9({abi:W0,data:t}),i=[],a=[];return await Promise.all(s.map(async(c,u)=>{try{let d=c.urls.includes(Ia);if(d&&o+1>=ol.depth)throw new Nr({details:`CCIP Read exceeded the maximum batch depth (${ol.depth}).`,url:Ia});if(d)a[u]=await EL({data:c.data,ccipRequest:r,budget:n,depth:o+1});else{if(n.queries<=0)throw new Nr({details:`CCIP Read exceeded the maximum number of queries (${ol.queries}).`,url:c.urls[0]??""});let f=c.urls.slice(0,n.queries);n.queries-=Math.max(1,f.length);let p=await n.run(async()=>n.bytes<0?"0x":r({...c,urls:f}));if(n.bytes-=gt(p),n.bytes<0)throw new Nr({details:`CCIP Read exceeded the maximum response size (${ol.bytes} bytes).`,url:Ia});a[u]=p}i[u]=!1}catch(d){if(n.bytes<0)throw d;i[u]=!0,a[u]=DDe(d)}})),_9({abi:W0,functionName:"query",result:[i,a]})}function DDe(e){return e.name==="HttpRequestError"&&e.status?m3({abi:W0,errorName:"HttpError",args:[e.status,e.shortMessage]}):m3({abi:[Gw],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}var Ia,ol,qb=b(()=>{l();So();R4();fs();gL();wL();xL();Fo();Ia="x-batch-gateway:true",ol={bytes:10485760,concurrency:16,depth:4,queries:256}});function P9(e){let t=e.filter(s=>!!s);if(t.length<2)return{signal:t[0]??null,cleanup:()=>{}};let r=new AbortController,n=()=>{o(),r.abort(t.find(s=>s.aborted)?.reason)},o=()=>{for(let s of t)s.removeEventListener("abort",n)};for(let s of t){if(s.aborted){o(),r.abort(s.reason);break}s.addEventListener("abort",n)}return{signal:r.signal,cleanup:o}}async function Wb(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw await e.body?.cancel(),new ic({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new ic({maxSize:t,size:c});return a}let n=e.body.getReader(),o=new TextDecoder,s="",i=0;try{for(;;){let{done:a,value:c}=await n.read();if(a)break;if(i+=c.byteLength,i>t)throw await n.cancel(),new ic({maxSize:t,size:i});s+=o.decode(c,{stream:!0})}return s+=o.decode(),s}finally{n.releaseLock()}}var N9=b(()=>{l();fs()});function sl(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((o,s)=>{(async()=>{let i,a=new AbortController;try{r>0&&(i=setTimeout(()=>{n?a.abort():s(t)},r)),o(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&Ii(c)){s(t);return}s(c)}finally{clearTimeout(i)}})()})}var Kb=b(()=>{l();oc()});var wie={};Te(wie,{ccipRequest:()=>Hg,offchainLookup:()=>B9,offchainLookupAbiItem:()=>O9,offchainLookupSignature:()=>R9});async function B9(e,{blockHash:t,blockNumber:r,blockTag:n,budget:o=vL(),data:s,depth:i=0,requestOptions:a,requireCanonical:c,to:u}){let{args:d}=Vh({data:s,abi:[O9]}),[f,p,h,y,w]=d,{ccipRead:x}=e,v=x&&typeof x?.request=="function"?x.request:Hg,T=yie(e.transport);try{if(i>=ol.depth)throw new Nr({details:`CCIP Read exceeded the maximum callback depth (${ol.depth}).`,url:p[0]??""});if(!xr(u,f))throw new I9({sender:f,to:u});let E=await(async()=>{if(p.includes(Ia))return EL({budget:o,ccipRequest:O=>v({...O,requestOptions:a,timeout:O.timeout??T}),data:h});if(o.queries<=0)throw new Nr({details:`CCIP Read exceeded the maximum number of queries (${ol.queries}).`,url:p[0]??""});let _=p.slice(0,o.queries);return o.queries-=Math.max(1,_.length),o.run(()=>v({data:h,requestOptions:a,sender:f,timeout:T,urls:_}))})(),S=en([y,oo([{type:"bytes"},{type:"bytes"}],[E,w])]);try{let{data:_}=await ms({...e,ccipRead:!1},{blockHash:t,blockNumber:r,blockTag:n,data:S,requestOptions:a,requireCanonical:c,to:u});return _}catch(_){let O=AL(_);if(O?.slice(0,10)!==R9)throw _;return await B9(e,{blockHash:t,blockNumber:r,blockTag:n,budget:o,data:O,depth:i+1,requestOptions:a,requireCanonical:c,to:u})}}catch(E){throw a?.signal?.aborted?Nn(a.signal):Ii(E)?E:new C9({callbackSelector:y,cause:E,data:s,extraData:w,sender:f,urls:p})}}async function Hg({data:e,requestOptions:t,sender:r,timeout:n=LDe,urls:o}){let s=new Error("An unknown error occurred.");for(let i of o){if(t?.signal?.aborted)throw Nn(t.signal);let a=i.replace("{sender}",r.toLowerCase()).replace("{data}",e),c=i.includes("{data}")?"GET":"POST",u=c==="POST"?{data:e,sender:r}:void 0,d=c==="POST"?{"Content-Type":"application/json"}:{};try{HDe(a);let{response:f,responseBody:p}=await sl(async({signal:y})=>{let{signal:w,cleanup:x}=P9([t?.signal,n>0?y:null]);try{let v=await fetch(a,{body:JSON.stringify(u),headers:d,method:c,...w?{signal:w}:{}}),T=await Wb(v,{maxResponseBodySize:MDe});return{response:v,responseBody:T}}finally{x()}},{errorInstance:new ds({body:u??{data:e,sender:r},url:i}),signal:!0,timeout:n}),h;if(f.headers.get("Content-Type")?.startsWith("application/json")?h=JSON.parse(p).data:h=p,!f.ok){s=new Nr({body:u,details:h?.error?bt(h.error):f.statusText,headers:f.headers,status:f.status,url:i});continue}if(!We(h)){s=new S9({result:h,url:i});continue}return h}catch(f){if(t?.signal?.aborted)throw Nn(t.signal);if(Ii(f))throw f;if(f instanceof Nr||f instanceof ds||f instanceof ic){s=f;continue}s=new Nr({body:u,cause:f,url:i})}}throw s}function HDe(e){let t=(()=>{try{return new URL(e)}catch{throw new Nr({details:"CCIP Read URL is invalid.",url:e})}})();if(!(t.protocol==="http:"||t.protocol==="https:"))throw new Nr({details:`CCIP Read URL scheme "${t.protocol.slice(0,-1)}" is not allowed.`,url:e})}function yie(e){let t=e.timeout??e.config?.timeout;if(t!==void 0)return t;let r=(e.transports??e.value?.transports??[]).map(yie).filter(n=>n!==void 0);return r.length?Math.max(...r):void 0}var LDe,MDe,R9,O9,k9=b(()=>{l();G0();gie();fs();oc();L4();rc();Oi();Fn();qs();qb();N9();Kb();so();LDe=1e4,MDe=10485760,R9="0x556f1830",O9={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function ms(e,t){let{account:r=e.account,authorizationList:n,batch:o=!!e.batch?.multicall,blockHash:s,blockNumber:i,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:u,blobs:d,blockOverrides:f,code:p,data:h,factory:y,factoryData:w,gas:x,gasPrice:v,maxFeePerBlobGas:T,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:_,requestOptions:O,to:D,value:M,stateOverride:N,...L}=t,P=r?ft(r):void 0;if(p&&(y||w))throw new G("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(p&&D)throw new G("Cannot provide both `code` & `to` as parameters.");let R=p&&h,I=y&&w&&D&&h,B=R||I,C=R?vie({code:p,data:h}):I?qDe({data:h,factory:y,factoryData:w,to:D}):h;try{jn(t);let A=ni({blockHash:s,blockNumber:i,blockTag:a,requireCanonical:c}),U=f?w9(f):void 0,H=xb(N),k=e.chain?.formatters?.transactionRequest?.format,j=(k||Bn)({...Ri(L,{format:k}),accessList:u,account:P,authorizationList:n,blobs:d,data:C,gas:x,gasPrice:v,maxFeePerBlobGas:T,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:_,to:B?void 0:D,value:M},"call");if(o&&$De({request:j})&&!U&&s===void 0)try{let{deployless:te=!1}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},X=xie(e,{blockNumber:i,deployless:te});if(!X||!jDe(H,X))return await VDe(e,{...j,blockHash:s,blockNumber:i,blockTag:a,multicallAddress:X,requestOptions:O,requireCanonical:c,rpcStateOverride:H})}catch(te){if(!(te instanceof kg)&&!(te instanceof Wf))throw te}let W=(()=>{let te=[j,A];return H&&U?[...te,H,U]:H?[...te,H]:U?[...te,{},U]:te})(),ae=await e.request({method:"eth_call",params:W},O);return ae==="0x"?{data:void 0}:{data:ae}}catch(A){if(O?.signal?.aborted)throw Nn(O.signal);if(Ii(A))throw A;let U=AL(A),{offchainLookup:H,offchainLookupSignature:k}=await Promise.resolve().then(()=>(k9(),wie));if(e.ccipRead!==!1&&U?.slice(0,10)===k&&D)return{data:await H(e,{blockHash:s,blockNumber:i,blockTag:a,data:U,requestOptions:O,requireCanonical:c,to:D})};throw B&&U?.slice(0,10)==="0x101bb98d"?new lb({factory:y}):E9(A,{...t,account:P,chain:e.chain})}}function $De({request:e}){let{data:t,to:r,...n}=e;return!(!t||t.startsWith(hie)||!r||Object.values(n).filter(o=>typeof o<"u").length>0)}function zDe(e){if(!e)return"default";let t=bie.get(e);if(t!==void 0)return t;let r=FDe++;return bie.set(e,r),r}async function VDe(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockHash:s,blockNumber:i,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:u,multicallAddress:d,requestOptions:f,rpcStateOverride:p,to:h}=t,y=d!==void 0?d:xie(e,{blockNumber:i,deployless:n}),w=ni({blockHash:s,blockNumber:i,blockTag:a,requireCanonical:c}),x=typeof w=="string"?w:JSON.stringify(w),v=p?`.${JSON.stringify(p)}`:"",{schedule:T}=Z0({id:`${e.uid}.${x}.${zDe(f)}${v}`,wait:o,shouldSplitBatch(_){return _.reduce((D,{data:M})=>D+(M.length-2),0)>r*2},fn:async _=>{let O=_.map(P=>({allowFailure:!0,callData:P.data,target:P.to})),D=Wt({abi:ki,args:[O],functionName:"aggregate3"}),M={...y===null?{data:vie({code:Mg,data:D})}:{to:y,data:D}},N=await e.request({method:"eth_call",params:p?[M,w,p]:[M,w]},f),L=dn({abi:ki,args:[O],functionName:"aggregate3",data:N||"0x"});if(L.length!==_.length)throw new G(`Multicall returned ${L.length} results for ${_.length} calls.`);return L}}),[{returnData:E,success:S}]=await T({data:u,to:h});if(!S)throw new sc({data:E});return E==="0x"?{data:void 0}:{data:E}}function xie(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return Ui({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new kg}function jDe(e,t){return e?Object.keys(e).some(r=>xr(r,t)):!1}function vie(e){let{code:t,data:r}=e;return tp({abi:Iw(["constructor(bytes, bytes)"]),bytecode:zb,args:[t,r]})}function qDe(e){let{data:t,factory:r,factoryData:n,to:o}=e;return tp({abi:Iw(["constructor(address, bytes, address, bytes)"]),bytecode:v9,args:[o,t,r,n]})}function AL(e){if(!(e instanceof G))return;let t=e.walk();return typeof t?.data=="object"?t.data?.data:t.data}var FDe,bie,G0=b(()=>{l();fg();uL();tn();So();mie();Vb();nt();Ug();ou();oc();lc();p3();us();Oi();B0();K0();hL();P0();rl();h3();VI();nl();FDe=0,bie=new WeakMap});async function er(e,t){let{abi:r,address:n,args:o,functionName:s,...i}=t,a=Wt({abi:r,args:o,functionName:s});try{let{data:c}=await ue(e,ms,"call")({...i,data:a,to:n});return dn({abi:r,args:o,functionName:s,data:c||"0x"})}catch(c){throw Js(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:s})}}var oi=b(()=>{l();lc();us();p0();_t();G0()});async function Y0(e,t){let{abi:r,address:n,args:o,functionName:s,dataSuffix:i=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account===void 0?e.account:a.account&&ft(a.account),u=Wt({abi:r,args:o,functionName:s});try{let{data:d}=await ue(e,ms,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=dn({abi:r,args:o,functionName:s,data:d||"0x"}),p=r.filter(h=>"name"in h&&h.name===t.functionName);return{result:f,request:{abi:p,address:n,args:o,dataSuffix:i,functionName:s,...a,account:c}}}catch(d){throw Js(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:s,sender:c?.address})}}var g3=b(()=>{l();tn();lc();us();p0();_t();G0()});function Io(e,t,r){let n=++WDe,o=()=>U9.get(e)||[],s=()=>{let f=o().filter(p=>p.id!==n);if(f.length===0){U9.delete(e),CL.delete(e);return}U9.set(e,f)},i=()=>{let d=o();if(!d.some(p=>p.id===n))return;let f=CL.get(e);if(d.length===1&&f){let p=f();p instanceof Promise&&p.catch(()=>{})}s()},a=o();if(U9.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return i;let c={};for(let d in t)c[d]=((...f)=>{let p=o();if(p.length!==0)for(let h of p)h.fns[d]?.(...f)});let u=r(c);return typeof u=="function"&&CL.set(e,u),i}var U9,CL,WDe,rp=b(()=>{l();U9=new Map,CL=new Map,WDe=0});async function $g(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(Nn(t));return}let o=()=>t?.removeEventListener("abort",i),s=setTimeout(()=>{o(),r()},Math.min(e,2**31-1)),i=()=>{clearTimeout(s),o(),n(Nn(t))};t?.addEventListener("abort",i,{once:!0})})}var D9=b(()=>{l();oc()});function dc(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,s=()=>o=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));let c=await r?.(a)??n;await $g(c);let u=async()=>{o&&(await e({unpoll:s}),await $g(n),u())};u()})(),s}var Fg=b(()=>{l();D9()});function Eie(e){let t=(o,s)=>({clear:()=>s.delete(o),get:()=>s.get(o),set:i=>s.set(o,i)}),r=t(e,KDe),n=t(e,ZDe);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function L9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=Eie(t),o=n.response.get();if(o&&r>0&&Date.now()-o.created.getTime(){l();KDe=new Map,ZDe=new Map});async function Ta(e,{cacheTime:t=e.cacheTime}={}){let r=await L9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:GDe(e.uid),cacheTime:t});return BigInt(r)}var GDe,zg=b(()=>{l();SL();GDe=e=>`blockNumber.${e}`});async function J0(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;let o=n.map(s=>qn(s));return!("abi"in t)||!t.abi?o:cc({abi:t.abi,eventName:t.eventName,logs:o,strict:r})}var y3=b(()=>{l();Dg();hu()});function gu(e){if(e.transport.type==="fallback"){let t=e.transport.transports.find(r=>r.config.type==="webSocket"||r.config.type==="ipc");return t?t.value:e.transport}return e.transport}function Q0(e){return!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))}var Zb=b(()=>{l()});async function X0(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}var w3=b(()=>{l()});function M9(e,t){let{abi:r,address:n,args:o,batch:s=!0,eventName:i,fromBlock:a,onError:c,onLogs:u,poll:d,pollingInterval:f=e.pollingInterval,strict:p}=t;return(typeof d<"u"?d:typeof a=="bigint"?!0:Q0(e))?(()=>{let x=p??!1,v=bt(["watchContractEvent",n,o,s,e.uid,i,f,x,a]);return Io(v,{onLogs:u,onError:c},T=>{let E=!0,S=a===void 0?void 0:a-1n,_,O=!1,D=L=>{if(L.length!==0)if(s)T.onLogs(L);else for(let P of L)T.onLogs([P])},M=(L,P)=>ue(e,kb,"getContractEvents")({abi:r,address:n,args:o,eventName:i,fromBlock:L,toBlock:P,strict:x}),N=dc(async()=>{if(!O){try{_=await ue(e,Zw,"createContractEventFilter")({abi:r,address:n,args:o,eventName:i,strict:x,fromBlock:a})}catch{}if(O=!0,_)return}try{if(_){let R=await ue(e,J0,"getFilterChanges")({filter:_});D(R);return}let L=await ue(e,Ta,"getBlockNumber")({});S??=L;let P=L-S;for(;S{if(R===B||!Bb(A))throw A});if(!E)return;if(!C){P=(B-R+1n)/2n;continue}S=B,D(C)}}catch(L){_&&L instanceof Ti&&(O=!1),T.onError?.(L)}},{emitOnBegin:!0,interval:f});return async()=>{E=!1,_&&await ue(e,X0,"uninstallFilter")({filter:_}),N()}})})():(()=>{let x=p??!1,v=bt(["watchContractEvent",n,o,s,e.uid,i,f,x]),T=!0,E=()=>T=!1;return Io(v,{onLogs:u,onError:c},S=>((async()=>{try{let _=gu(e),O=!!(i||p),D=i?nc({abi:r,eventName:i,args:o}):[],{unsubscribe:M}=await _.subscribe({params:["logs",{address:n,topics:D}],onData(N){if(!T)return;let L=N.result;try{let P=Yf({abi:r,data:L.data,eventName:i,topics:L.topics,strict:p}),R=qn(L,{args:P.args,eventName:P.eventName});S.onLogs([R])}catch(P){if(O&&(P instanceof Gf||P instanceof Yl||P instanceof Jl))return;let R,I;if(P instanceof jc||P instanceof Ql){if(p)return;R=P.abiItem.name,I=P.abiItem.inputs?.some(C=>!("name"in C&&C.name))}let B=qn(L,{args:I?[]:{},eventName:R});S.onLogs([B])}},onError(N){S.onError?.(N)}});E=M,T||E()}catch(_){c?.(_)}})(),()=>E()))})()}var IL=b(()=>{l();Qr();Lf();a3();Cg();hu();_t();rp();Fg();so();II();zg();s9();y3();n9();Zb();w3()});var kn,fc,yu=b(()=>{l();nt();kn=class extends G{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` +`),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}},fc=class extends G{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}});function em({chain:e,currentChainId:t}){if(!e)throw new Sb;if(t!==e.id)throw new U0({chain:e,currentChainId:t})}var b3=b(()=>{l();Ug()});async function Gb(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var H9=b(()=>{l()});async function tm(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:s,authorizationList:i,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,type:x,value:v,...T}=t;if(typeof r>"u")throw new kn({docsPath:"/docs/actions/wallet/sendTransaction"});let E=r?ft(r):null,S;try{jn(t);let _=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await b0({authorization:i[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if(E?.type==="json-rpc"||E===null){let O;o!==null&&(O=await ue(e,hs,"getChainId")({}),n&&em({currentChainId:O,chain:o}));let D=e.chain?.formatters?.transactionRequest?.format,N=(D||Bn)({...Ri(T,{format:D}),accessList:s,account:E,authorizationList:i,blobs:a,chainId:O,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,to:_,type:x,value:v},"sendTransaction"),L=TL.get(e.uid),P=L?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:P,params:[N]},{retryCount:0})}catch(R){if(L===!1)throw R;let I=R;if(I.name==="InvalidInputRpcError"||I.name==="InvalidParamsRpcError"||I.name==="MethodNotFoundRpcError"||I.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[N]},{retryCount:0}).then(B=>(TL.set(e.uid,!0),B)).catch(B=>{let C=B;throw C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError"?(TL.set(e.uid,!1),I):C});throw I}}if(E?.type==="local"){let O=(()=>{if(!E.nonceManager||typeof w<"u")return E.nonceManager;let R=E.nonceManager;return{async consume(I){S={address:I.address,chainId:I.chainId};let B=await R.consume(I);return S={...S,nonce:B},B},get(I){return R.get(I)},increment(I){return R.increment(I)},reset(I){return R.reset(I)}}})(),D=await ue(e,pu,"prepareTransactionRequest")({account:E,accessList:s,authorizationList:i,blobs:a,chain:o,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,nonceManager:O,parameters:[...s3,"sidecars"],type:x,value:v,...T,to:_}),M=o?.serializers?.transaction,N=await E.signTransaction(D,{serializer:M}),L=(o??e.chain)?.serializers?.transactionEnvelope,P=L?await L({serializedTransaction:N,transaction:D}):N;return await ue(e,Gb,"sendRawTransaction")({serializedTransaction:P})}throw E?.type==="smart"?new fc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new fc({docsPath:"/docs/actions/wallet/sendTransaction",type:E?.type})}catch(_){throw _ instanceof fc?_:(S&&E?.nonceManager?.reset(S),H0(_,{...t,account:E,chain:t.chain||void 0}))}}var TL,x3=b(()=>{l();tn();yu();nt();Z4();b3();Fn();o3();P0();rl();_t();_f();nl();Zf();Rb();H9();TL=new xo(128)});async function _a(e,t){return _a.internal(e,tm,"sendTransaction",t)}var Yb=b(()=>{l();tn();yu();us();p0();_t();x3();(function(e){async function t(r,n,o,s){let{abi:i,account:a=r.account,address:c,args:u,functionName:d,...f}=s;if(typeof a>"u")throw new kn({docsPath:"/docs/contract/writeContract"});let p=a?ft(a):null,h=Wt({abi:i,args:u,functionName:d});try{return await ue(r,n,o)({data:h,to:c,account:p,...f})}catch(y){throw Js(y,{abi:i,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:d,sender:p?.address})}}e.internal=t})(_a||(_a={}))});function Aie({abi:e,address:t,client:r}){let n=r,[o,s]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],i=o!=null,a=s!=null,c={},u=!1,d=!1,f=!1;for(let p of e)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:d=!0:p.type==="event"&&(f=!0),u&&d&&f)break;return i&&(u&&(c.read=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o,er,"readContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),d&&(c.simulate=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o,Y0,"simulateContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,Zw,"createContractEventFilter")({abi:e,address:t,eventName:h,args:x,...v})}}}),c.getEvents=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,kb,"getContractEvents")({abi:e,address:t,eventName:h,args:x,...v})}}}),c.watchEvent=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,M9,"watchContractEvent")({abi:e,address:t,eventName:h,args:x,...v})}}}))),a&&d&&(c.write=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(s,_a,"writeContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),(i||a)&&d&&(c.estimateGas=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o??s,$0,"estimateContractGas")({abi:e,address:t,functionName:h,args:w,...x,account:x.account??s.account})}}})),c.address=t,c.abi=e,c}function $9(e){let t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function _L(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);let n=r?e[0]:void 0,o=(r?e[1]:e[0])??{};return{args:n,options:o}}var Cie=b(()=>{l();_t();II();i3();s9();oi();g3();IL();Yb()});var Jb,PL=b(()=>{l();nt();Jb=class extends G{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}}});function np(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((s,i)=>{let a=()=>i(Nn(o));o?.addEventListener("abort",a,{once:!0});let c=async({count:u=0}={})=>{if(o?.aborted){i(Nn(o));return}let d=async({error:f})=>{let p=typeof t=="function"?t({count:u,error:f}):t;if(p)try{await $g(p,{signal:o})}catch(h){i(h);return}return c({count:u+1})};try{let f=await e();s(f)}catch(f){if(o?.aborted){i(Nn(o));return}if(Ii(f)){i(f);return}if(uo?.removeEventListener("abort",a))})}var v3=b(()=>{l();oc();D9()});function op(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>qn(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?wt(e.transactionIndex):null,status:e.status?NL[e.status]:null,type:e.type?Q4[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}var NL,Sie,Qb=b(()=>{l();Xr();Y4();hu();Ab();NL={"0x0":"reverted","0x1":"success"};Sie=N0("transactionReceipt",op)});async function F9(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:s=32,forceAtomic:i=!1,id:a,version:c="2.0.0"}=t,u=r?ft(r):null,d=t.capabilities;e.dataSuffix&&!t.capabilities?.dataSuffix&&(typeof e.dataSuffix=="string"?d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}}:d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}});let f=t.calls.map(p=>{let h=p,y=h.abi?Wt({abi:h.abi,functionName:h.functionName,args:h.args}):h.data;return{data:h.dataSuffix?en([y??"0x",h.dataSuffix]):y,to:h.to,value:h.value?oe(h.value):void 0}});try{let p=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:i,calls:f,capabilities:d,chainId:oe(n.id),from:u?.address,id:a,version:c}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){let h=p;if(o&&(h.name==="MethodNotFoundRpcError"||h.name==="MethodNotSupportedRpcError"||h.name==="UnknownRpcError"||h.details.toLowerCase()==="this request method is not supported"||h.details.toLowerCase().includes("does not exist / is not available")||h.details.toLowerCase().includes("missing or invalid. request()")||h.details.toLowerCase().includes("did not match any variant of untagged enum")||h.details.toLowerCase().includes("account upgraded to unsupported contract")||h.details.toLowerCase().includes("eip-7702 not supported")||h.details.toLowerCase().includes("unsupported wc_ method")||h.details.toLowerCase().includes("feature toggled misconfigured")||h.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d&&Object.values(d).some(v=>!v.optional)){let v="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new au(new G(v,{details:v}))}if(i&&f.length>1){let x="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new cu(new G(x,{details:x}))}let y=[];for(let x of f){try{let v=await ue(e,tm,"sendTransaction")({account:u,chain:n,data:x.data,to:x.to,value:x.value?dt(x.value):void 0});y.push({status:"fulfilled",value:v})}catch(v){y.push({reason:v,status:"rejected"})}s>0&&await new Promise(v=>setTimeout(v,s))}if(y.every(x=>x.status==="rejected"))throw y[0].reason;let w=y.map(x=>x.status==="fulfilled"?x.value:OL);return{id:en([...w,oe(n.id,{size:32}),RL])}}throw H0(p,{...t,account:u,chain:t.chain})}}var RL,OL,z9=b(()=>{l();tn();nt();Lf();us();Fn();Xr();qe();o3();_t();x3();RL="0x5792579257925792579257925792579257925792579257925792579257925792",OL=oe(0,{size:32})});async function V9(e,t){async function r(d){if(d.endsWith(RL.slice(2))){let p=bn(xa(d,-64,-32)),h=xa(d,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(h.map(x=>OL.slice(2)!==x?e.request({method:"eth_getTransactionReceipt",params:[`0x${x}`]},{dedupe:!0}):void 0)),w=y.some(x=>x===null)?100:y.every(x=>x?.status==="0x1")?200:y.every(x=>x?.status==="0x0")?500:600;return{atomic:!1,chainId:wt(p),receipts:y.filter(Boolean),status:w,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:n=!1,chainId:o,receipts:s,version:i="2.0.0",...a}=await r(t.id),[c,u]=(()=>{let d=a.status;return d>=100&&d<200?["pending",d]:d>=200&&d<300?["success",d]:d>=300&&d<700?["failure",d]:d==="CONFIRMED"?["success",200]:d==="PENDING"?["pending",100]:[void 0,d]})();return{...a,atomic:n,chainId:o?wt(o):void 0,receipts:s?.map(d=>({...d,blockNumber:dt(d.blockNumber),gasUsed:dt(d.gasUsed),status:NL[d.status]}))??[],statusCode:u,status:c,version:i}}var BL=b(()=>{l();Si();Hh();Xr();Qb();z9()});function Tie(e){let t=Iie.get(e);return t===void 0&&(t=++YDe,Iie.set(e,t)),t}async function j9(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:w})=>w===200||w>=300,retryCount:s=4,retryDelay:i=({count:w})=>~~(1<{let x=dc(async()=>{let v=T=>{clearTimeout(h),x(),T(),y()};try{let T=await np(async()=>{let E=await ue(e,V9,"getCallsStatus")({id:r});if(c&&E.status==="failure")throw new Jb(E);return E},{retryCount:s,delay:i});if(!o(T))return;v(()=>w.resolve(T))}catch(T){v(()=>w.reject(T))}},{interval:n,emitOnBegin:!0});return x});return h=a?setTimeout(()=>{y(),clearTimeout(h),p(new E3({id:r}))},a):void 0,await d.finally(()=>y())}var Iie,YDe,E3,q9=b(()=>{l();nt();PL();_t();rp();Fg();A9();v3();so();BL();Iie=new WeakMap,YDe=0;E3=class extends G{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}});function rm(e=11){if(!K9||W9+e>256*2){K9="",W9=0;for(let t=0;t<256;t++)K9+=(256+Math.random()*256|0).toString(16).substring(1)}return K9.substring(W9,W9+++e)}var W9,K9,A3=b(()=>{l();W9=256});function wu(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:s="base",name:i="Base Client",tokens:a,type:c="base"}=e,u=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime=="number"?"pending":void 0),d=r?.blockTime??12e3,f=Math.min(Math.max(Math.floor(d/2),500),4e3),p=e.pollingInterval??f,h=e.cacheTime??Math.min(p,Math.floor(d/2)),y=e.account?ft(e.account):void 0,{config:w,request:x,value:v}=e.transport({account:y,chain:r,pollingInterval:p}),T={...w,...v},E={account:y,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:s,name:i,pollingInterval:p,request:x,tokens:a,transport:T,type:c,uid:rm(),...u?{experimental_blockTag:u}:{}};return Nie(E)}function Nie(e){function t(n,o){return s=>{let i=s(n);for(let d in e)d!=="scope"&&delete i[d];let a={...n,...i};for(let d in i){let f=n[d],p=i[d];Pie(f)&&Pie(p)&&(a[d]={...f,...p})}let c=[...o,s],{scope:u}=a;return Object.assign(a,{extend:t(a,c),scope:typeof u=="function"&&_ie.has(u)?r(c):u})}}function r(n){let o=new WeakMap,s=(i={})=>{let a=i.signal&&o.get(i.signal);if(a)return a;let c=`scope.${JDe++}`,u=new AbortController,{signal:d}=i;d?.aborted?u.abort(d.reason):d?.addEventListener("abort",()=>u.abort(d.reason),{once:!0});let f=(h,y)=>e.request(h,{...y,signal:y?.signal??u.signal,uid:y?.uid??c}),p=n.reduce((h,y)=>h.extend(y),Nie({...e,request:f,uid:c}));return d&&o.set(d,p),p};return _ie.add(s),s}return Object.assign(e,{extend:t(e,[]),scope:r([])})}function Pie(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bu(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(s={})=>o.length===1?o(s):o(e,s)}for(let n of["extractEvent","extractEvents"])Object.hasOwn(t,n)&&(r[n]=t[n]);return r}function Rie(){return null}var _ie,JDe,nm=b(()=>{l();tn();A3();_ie=new WeakSet,JDe=0});function Oie(e){let{chains:t,transport:r,...n}=e,o=new Map;return{getClient({chainId:s}){let i=o.get(s);if(i)return i;let a=t.find(d=>d.id===s);if(!a)throw new C3({chainId:s});let c=typeof r=="function"?r({chainId:s}):r[s];if(!c)throw new S3({chainId:s});let u=wu({...n,chain:a,transport:c});return o.set(s,u),u}}}var C3,S3,Bie=b(()=>{l();nt();nm();C3=class extends G{constructor({chainId:t}){super(`Chain with id ${t} is not configured.`,{name:"createClientResolver.ChainNotConfiguredError"})}},S3=class extends G{constructor({chainId:t}){super(`Transport for chain with id ${t} is not configured.`,{name:"createClientResolver.TransportNotConfiguredError"})}}});function Xb(e){if(!(e instanceof G))return!1;let t=e.walk(r=>r instanceof Uf);return t instanceof Uf?t.data?.errorName==="HttpError"||t.data?.errorName==="ResolverError"||t.data?.errorName==="ResolverNotContract"||t.data?.errorName==="ResolverNotFound"||t.data?.errorName==="ReverseAddressMismatch"||t.data?.errorName==="UnsupportedResolverProfile":!1}var Z9=b(()=>{l();nt();ou()});function G9(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;return We(t)?t:null}var kL=b(()=>{l();qs()});function Vg(e){let t=new Uint8Array(32).fill(0);if(!e)return yt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=G9(r[n]),s=o?un(o):Pt(zo(r[n]),"bytes");t=Pt(en([t,s]),"bytes")}return yt(t)}var Y9=b(()=>{l();Fn();Pr();qe();Ks();kL()});function kie(e){return`[${e.slice(2)}]`}var Uie=b(()=>{l()});function J9(e){let t=new Uint8Array(32).fill(0);return e?G9(e)||Pt(zo(e)):yt(t)}var UL=b(()=>{l();Pr();qe();Ks();kL()});function e6(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(zo(t).byteLength+2),n=0,o=t.split(".");for(let s=0;s255&&(i=zo(kie(J9(o[s])))),r[n]=i.length,r.set(i,n+1),n+=i.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}var Q9=b(()=>{l();Pr();Uie();UL()});async function Die(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:s,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(p=>s.endsWith(p)))return null;let f=o!=null?[Vg(s),BigInt(o)]:[Vg(s)];try{let p=Wt({abi:fL,functionName:"addr",args:f}),h={address:u,abi:b9,functionName:"resolveWithGateways",args:[wr(e6(s)),p,i??[Ia]],blockNumber:r,blockTag:n},w=await ue(e,er,"readContract")(h);if(w[0]==="0x")return null;let x=QDe({coinType:o,data:w[0],args:f});return x==="0x"||bn(x)==="0x00"?null:x}catch(p){if(a)throw p;if(Xb(p))return null;throw p}}function QDe({coinType:e,data:t,args:r}){try{return dn({abi:fL,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=20,s=32,i=bn(t),a=gt(i),c=gt(t);if((e===60n||e>=0x80000000n&&e<=0xffffffffn)&&(c===o||c===s)&&a{l();So();lc();us();Zs();K0();Xa();Fo();Hh();qe();Z9();qb();Y9();Q9();_t();oi()});function tLe(e,t={}){let{pad:r=!0,url:n=!1}=t,o=new Uint8Array(Math.ceil(e.length/3)*4);for(let c=0,u=0;u>18],o[c+1]=X9[d>>12&63],o[c+2]=X9[d>>6&63],o[c+3]=X9[d&63]}let s=e.length%3,i=Math.floor(e.length/3)*4+(s&&s+1),a=eLe.decode(new Uint8Array(o.buffer,0,i));return r&&s===1&&(a+="=="),r&&s===2&&(a+="="),n&&(a=a.replaceAll("+","-").replaceAll("/","_")),a}function Mie(e,t={}){return tLe(Mb(e),t)}function rLe(e){let t=e.replace(/=+$/,""),r=t.length,n=new Uint8Array(r+3);XDe.encodeInto(t+"===",n);for(let s=0,i=0;s>16,n[i+1]=a>>8&255,n[i+2]=a&255}let o=(r>>2)*3+(r%4&&r%4-1);return new Uint8Array(n.buffer,0,o)}function Hie(e){return d9(rLe(e))}var XDe,eLe,X9,eT,DL=b(()=>{l();mu();XDe=new TextEncoder,eLe=new TextDecoder,X9=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),eT={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var tT,xu,om,t6,r6,rT=b(()=>{l();nt();tT=class extends G{constructor({data:t}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(t)}`],name:"EnsAvatarInvalidMetadataError"})}},xu=class extends G{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}},om=class extends G{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}},t6=class extends G{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}},r6=class extends G{constructor({chainId:t}){super(`Invalid ENSIP-11 chainId: ${t}. Must be between 0 and 0x7fffffff, or 1.`,{name:"EnsInvalidChainIdError"})}}});async function cLe(e,{timeout:t=zie}={}){try{let r=await sl(({signal:n})=>fetch(e,{method:"HEAD",...n?{signal:n}:{}}),{errorInstance:new ds({body:{},url:e}),signal:!0,timeout:t});return r.status===200?r.headers.get("content-type")?.startsWith("image/"):!1}catch(r){return r instanceof ds||typeof r=="object"&&typeof r.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(n=>{let o=new Image;o.onload=()=>{n(!0)},o.onerror=()=>{n(!1)},o.src=e})}}function Fie(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function LL({uri:e,gatewayUrls:t}){let r=sLe.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=Fie(t?.ipfs,"https://ipfs.io"),o=Fie(t?.arweave,"https://arweave.net"),s=e.match(nLe),{protocol:i,subpath:a,target:c,subtarget:u=""}=s?.groups||{},d=i==="ipns:/"||a==="ipns/",f=i==="ipfs:/"||a==="ipfs/"||oLe.test(e);if(e.startsWith("http")&&!d&&!f){let h=e;return t?.arweave&&(h=e.replace(/https:\/\/arweave.net/g,t?.arweave)),{uri:h,isOnChain:!1,isEncoded:!1}}if((d||f)&&c)return{uri:`${n}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(i==="ar:/"&&c)return{uri:`${o}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(iLe,"");if(p.startsWith("{let i=await fetch(r,s?{signal:s}:{});return Wb(i,{maxResponseBodySize:aLe})},{errorInstance:new ds({body:{},url:r}),signal:!0,timeout:t});return await nT({gatewayUrls:e,uri:ML(JSON.parse(n))})}catch{throw new om({uri:r})}}async function nT({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=LL({uri:t,gatewayUrls:e});if(n||await cLe(r))return r;throw new om({uri:t})}function jie(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));let[r,n,o]=t.split("/"),[s,i]=r.split(":"),[a,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new xu({reason:"Only EIP-155 supported"});if(!i)throw new xu({reason:"Chain ID not found"});if(!c)throw new xu({reason:"Contract address not found"});if(!o)throw new xu({reason:"Token ID not found"});if(!a)throw new xu({reason:"ERC namespace not found"});return{chainID:Number.parseInt(i,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function qie(e,{nft:t}){if(t.namespace==="erc721")return er(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return er(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new t6({namespace:t.namespace})}function Wie({nft:e,uri:t}){let r=e.namespace==="erc1155"?oe(BigInt(e.tokenID),{size:32}).slice(2):e.tokenID;return t.replace(/(?:0x)?{id}/,r)}var nLe,oLe,sLe,iLe,zie,aLe,Kie=b(()=>{l();DL();oi();rT();fs();qe();N9();Kb();nLe=/(?https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,oLe=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,sLe=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,iLe=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/,zie=1e4,aLe=10485760});async function Zie(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?lLe(e,{gatewayUrls:t,record:r}):nT({uri:r,gatewayUrls:t})}async function lLe(e,{gatewayUrls:t,record:r}){let n=jie(r),o=await qie(e,{nft:n}),{uri:s,isOnChain:i,isEncoded:a}=LL({uri:o,gatewayUrls:t});if(i&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){let c=a?Hie(s.replace("data:application/json;base64,","").replace(/\s/g,"")):s,u=JSON.parse(c);return nT({uri:ML(u),gatewayUrls:t})}return Vie({gatewayUrls:t,uri:Wie({nft:n,uri:s})})}var Gie=b(()=>{l();DL();Kie()});async function oT(e,t){let{blockNumber:r,blockTag:n,key:o,name:s,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(f=>s.endsWith(f)))return null;try{let f={address:u,abi:b9,args:[wr(e6(s)),Wt({abi:dL,functionName:"text",args:[Vg(s),o]}),i??[Ia]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await ue(e,er,"readContract")(f);if(h[0]==="0x")return null;let y=dn({abi:dL,functionName:"text",data:h[0]});return y===""?null:y}catch(f){if(a)throw f;if(Xb(f))return null;throw f}}var HL=b(()=>{l();So();lc();us();K0();qe();Z9();qb();Y9();Q9();_t();oi()});async function Yie(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:s,strict:i,universalResolverAddress:a}){let c=await ue(e,oT,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:s,strict:i});if(!c)return null;try{return await Zie(e,{record:c,gatewayUrls:n})}catch{return null}}var Jie=b(()=>{l();Gie();_t();HL()});async function Qie(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:s=60n,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let d={address:u,abi:lie,args:[r,s,i??[Ia]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},f=ue(e,er,"readContract"),[p]=await f(d);return p||null}catch(d){if(a)throw d;if(Xb(d))return null;throw d}}var Xie=b(()=>{l();So();K0();Z9();qb();_t();oi()});async function eae(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:s}=e,i=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),a=s?.ensTlds;if(a&&!a.some(u=>o.endsWith(u)))throw new Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);let[c]=await ue(e,er,"readContract")({address:i,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[wr(e6(o))],blockNumber:r,blockTag:n});return c}var tae=b(()=>{l();K0();qe();Q9();_t();oi()});async function rae(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:s,data:i,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,to:p,value:h,...y}=t,w=r?ft(r):void 0;try{jn(t);let v=(typeof n=="bigint"?oe(n):void 0)||o,T=e.chain?.formatters?.transactionRequest?.format,S=(T||Bn)({...Ri(y,{format:T}),account:w,blobs:s,data:i,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,to:p,value:h},"createAccessList"),_=await e.request({method:"eth_createAccessList",params:[S,v]});if(_.error)throw new G(_.error,{details:_.error});return{accessList:_.accessList,gasUsed:BigInt(_.gasUsed)}}catch(x){throw E9(x,{...t,account:w,chain:e.chain})}}var nae=b(()=>{l();tn();nt();qe();hL();P0();rl();nl()});async function oae(e){let t=Fh(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}var sae=b(()=>{l();N4()});async function sT(e,{address:t,args:r,event:n,events:o,fromBlock:s,strict:i,toBlock:a}={}){let c=o??(n?[n]:void 0),u=Fh(e,{method:"eth_newFilter"}),d=[];c&&(d=[c.flatMap(h=>nc({abi:[h],eventName:h.name,args:r}))],n&&(d=d[0]));let f=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?oe(s):s,toBlock:typeof a=="bigint"?oe(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:f,request:u(f),strict:!!i,toBlock:a,type:"event"}}var $L=b(()=>{l();Cg();qe();N4()});async function iT(e){let t=Fh(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}var FL=b(()=>{l();N4()});async function iae(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,u=Wt({abi:ki,functionName:"getEthBalance",args:[t]}),{data:d}=await ue(e,ms,"call")({to:c,data:u,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});return dn({abi:ki,functionName:"getEthBalance",args:[t],data:d||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,i]});return BigInt(a)}var aae=b(()=>{l();So();lc();us();B0();_t();G0()});async function cae(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var lae=b(()=>{l()});async function uae(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?oe(r):void 0,s=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:!!(t||o)});if(!s)throw new du({blockHash:t,blockNumber:r});let i=e.chain?.formatters?.transactionReceipt?.format||op;return s.map(a=>i(a,"getBlockReceipts"))}var dae=b(()=>{l();J4();qe();Qb()});async function fae(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?oe(r):void 0,s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:!!o}),wt(s)}var pae=b(()=>{l();Xr();qe()});async function jg(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),a=await e.request({method:"eth_getCode",params:[t,i]},{dedupe:typeof n=="bigint"||r!==void 0});if(a!=="0x")return a}var aT=b(()=>{l();B0()});async function hae(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await ue(e,jg,"getCode")({address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(o&>(o)===23&&o.startsWith("0xef0100"))return Gr(vo(o,3,23))}var mae=b(()=>{l();Zs();Fo();Si();_t();aT()});var cT,gae=b(()=>{l();nt();cT=class extends G{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}});async function yae(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[s,i,a,c,u,d,f]=await ue(e,er,"readContract")({abi:uLe,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:i,version:a,chainId:Number(c),verifyingContract:u,salt:d},extensions:f,fields:s}}catch(s){let i=s;throw i.name==="ContractFunctionExecutionError"&&i.cause.name==="ContractFunctionZeroDataError"?new cT({address:r}):i}}var uLe,wae=b(()=>{l();gae();_t();oi();uLe=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}]});function bae(e){return{baseFeePerGas:e.baseFeePerGas.map(t=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map(t=>t.map(r=>BigInt(r)))}}var xae=b(()=>{l()});async function vae(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let s=typeof r=="bigint"?oe(r):void 0,i=await e.request({method:"eth_feeHistory",params:[oe(t),s||n,o]},{dedupe:!!s});return bae(i)}var Eae=b(()=>{l();qe();xae()});async function Aae(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>qn(s));return t.abi?cc({abi:t.abi,eventName:t.eventName,logs:o,strict:r}):o}var Cae=b(()=>{l();Dg();hu()});function Sae(e,t){if(e.length!==t.length)throw new kh({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n{l();Qr();tc();Gs();Fn();Xa();qe();P4()});function I3(e){return!e||typeof e!="object"||!("BYTES_PER_ELEMENT"in e)?!1:e.BYTES_PER_ELEMENT===1&&e.constructor.name==="Uint8Array"}var zL=b(()=>{l()});function _ae(e){return e.opcode==="CREATE2"?jL(e):VL(e)}function VL(e){let t=un(Gr(e.from)),r=un(e.nonce);return r[0]===0&&(r=new Uint8Array([])),Gr(`0x${Pt(Vo([t,r],"bytes")).slice(26)}`)}function jL(e){let t=un(Gr(e.from)),r=Zr(I3(e.salt)?e.salt:un(e.salt),{size:32}),n="bytecodeHash"in e?I3(e.bytecodeHash)?e.bytecodeHash:un(e.bytecodeHash):Pt(e.bytecode,"bytes");return Gr(vo(Pt(en([un("0xff"),t,r,n])),12))}var Pae=b(()=>{l();Fn();zL();Xa();Si();Pr();wb();Ks();Zs()});function lT(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!Ft(o))throw new br({address:o});if(n<0)throw new Kf({chainId:n})}sm(e)}function uT(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new _b;for(let r of t){let n=gt(r),o=wt(vo(r,0,1));if(n!==32)throw new JI({hash:r,size:n});if(o!==1)throw new QI({hash:r,version:o})}}sm(e)}function sm(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new Kf({chainId:t});if(o&&!Ft(o))throw new br({address:o});if(n&&n>R0)throw new Pi({maxFeePerGas:n});if(typeof r=="bigint"&&typeof n=="bigint"&&r>n)throw new ac({maxFeePerGas:n,maxPriorityFeePerGas:r})}function n6(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(t<=0)throw new Kf({chainId:t});if(s&&!Ft(s))throw new br({address:s});if(r||o)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>R0)throw new Pi({maxFeePerGas:n})}function o6(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(s&&!Ft(s))throw new br({address:s});if(typeof t<"u"&&t<=0)throw new Kf({chainId:t});if(r||o)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>R0)throw new Pi({maxFeePerGas:n})}var dT=b(()=>{l();jI();tc();nt();YD();Ug();tl();Gs();Fo();Si();Xr()});function qg(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r{l();tc();zn();Gs()});function fT(e,t){let r=Pb(e);return r==="eip1559"?pLe(e,t):r==="eip2930"?hLe(e,t):r==="eip4844"?fLe(e,t):r==="eip7702"?dLe(e,t):mLe(e,t)}function dLe(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:s,to:i,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:f}=e;lT(e);let p=qg(d),h=Nae(r);return fr(["0x04",Vo([oe(n),s?oe(s):"0x",u?oe(u):"0x",c?oe(c):"0x",o?oe(o):"0x",i??"0x",a?oe(a):"0x",f??"0x",p,h,...s6(e,t)])])}function fLe(e,t){let{chainId:r,gas:n,nonce:o,to:s,value:i,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:f}=e;uT(e);let p=e.blobVersionedHashes,h=e.sidecars;if(e.blobs&&(typeof p>"u"||typeof h>"u")){let E=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(O=>yt(O)),S=e.kzg,_=D0({blobs:E,kzg:S});if(typeof p>"u"&&(p=Tb({commitments:_})),typeof h>"u"){let O=L0({blobs:E,commitments:_,kzg:S});h=M0({blobs:E,commitments:_,proofs:O})}}let y=qg(d),w=[oe(r),o?oe(o):"0x",u?oe(u):"0x",c?oe(c):"0x",n?oe(n):"0x",s??"0x",i?oe(i):"0x",f??"0x",y,a?oe(a):"0x",p??[],...s6(e,t)],x=[],v=[],T=[];if(h)for(let E=0;E{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new Kh({v:t.v});return h})(),f=bn(t.r),p=bn(t.s);u=[...u,oe(d),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(u=[...u,oe(r),"0x","0x"]);return Vo(u)}function s6(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let s=bn(r.r),i=bn(r.s);return[typeof o=="number"?o?oe(1):"0x":n===0n?"0x":n===1n?oe(1):n===27n?"0x":oe(1),s==="0x00"?"0x":s,i==="0x00"?"0x":i]}var pT=b(()=>{l();zn();Rae();t3();r3();GI();n3();Fn();Hh();qe();wb();dT();e9();qL()});function Nae(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...s}=r,i=r.address,a=s6({},s);a.length>0&&s.yParity&&(a[0]=wr(s.yParity)),t.push([n?wr(n):"0x",i,o?wr(o):"0x",...a])}return t}var Rae=b(()=>{l();qe();pT()});async function Oae({address:e,authorization:t,signature:r}){let n=await(async()=>{try{return await b0({authorization:t,signature:r})}catch(o){if(o instanceof tu)return;throw o}})();return n?xr(Gr(e),n):!1}var Bae=b(()=>{l();zn();Zs();Oi();Z4()});function kae(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(hT.get(r))return hT.get(r);let n=e().finally(()=>hT.delete(r));return hT.set(r,n),n}var hT,Uae=b(()=>{l();_f();hT=new xo(8192)});function Dae(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:s,retryDelay:i=150,retryCount:a=3,signal:c,uid:u}={...t,...n},{method:d}=r;if(s?.exclude?.includes(d))throw new Aa(new Error("method not supported"),{method:d});if(s?.include&&!s.include.includes(d))throw new Aa(new Error("method not supported"),{method:d});if(c?.aborted)throw Nn(c);let f=o?yLe(`${u}.${bt(r)}`):void 0;return kae(()=>np(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(p){if(c?.aborted)throw Nn(c);if(Ii(p))throw p;let h=p;switch(h.code){case Yh.code:throw new Yh(h);case Jh.code:throw new Jh(h);case Jc.code:throw new Jc(h,{method:r.method});case Qh.code:throw new Qh(h);case Qc.code:throw new Qc(h);case Ti.code:throw new Ti(h);case Xh.code:throw new Xh(h);case e0.code:throw new e0(h);case iu.code:throw new iu(h);case Aa.code:throw new Aa(h,{method:r.method});case Df.code:throw new Df(h);case t0.code:throw new t0(h);case Xc.code:throw new Xc(h);case r0.code:throw new r0(h);case n0.code:throw new n0(h);case o0.code:throw new o0(h);case s0.code:throw new s0(h);case i0.code:throw new i0(h);case au.code:throw new au(h);case a0.code:throw new a0(h);case c0.code:throw new c0(h);case l0.code:throw new l0(h);case u0.code:throw new u0(h);case d0.code:throw new d0(h);case cu.code:throw new cu(h);case 5e3:throw new Xc(h);case f0.code:throw new f0(h);default:throw p instanceof G?p:new ub(h)}}},{delay:({count:p,error:h})=>{let y=Lae(h)?.headers?.get("Retry-After");if(y){let w=Number.parseInt(y,10);if(!Number.isNaN(w))return w*1e3;let x=Date.parse(y)-Date.now();if(x>0)return x}return~~(1<gLe(p)}),{enabled:o,id:f})}}function gLe(e){if(Ii(e))return!1;let t=Lae(e)?.status;if("code"in e&&typeof e.code=="number"){if(e.code===-1||e.code===Df.code||e.code===Qc.code||e.code===429||e.code===-32007)return!0;if(e.code===Jc.code||e.code===Aa.code||!t)return!1}return t?t===403||t===408||t===413||t===429||t===500||t===502||t===503||t===504:!0}function Lae(e){if(e instanceof G)return e.walk(t=>t instanceof Nr||t instanceof Rn)}function yLe(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}var Mae=b(()=>{l();nt();fs();Lf();oc();Uae();v3();so()});function Hae({batchGateways:e,ccipRequest:t=Hg}){return{async request({data:r,requestOptions:n,sender:o,timeout:s,urls:i}){if(i.includes(Ia))return t({data:r,requestOptions:n,sender:o,timeout:s,urls:e});{let[a,c]=dn({abi:W0,functionName:"query",data:await t({data:Wt({abi:W0,functionName:"query",args:[[{sender:o,data:r,urls:i}]]}),requestOptions:n,sender:o,timeout:s,urls:e})});if(a[0]){let u;try{let d=Vh({abi:[...W0,Gw],data:c[0]});if(d.errorName==="HttpError")u=new Nr({body:{message:d.args[1]},status:d.args[0],url:i.join(" | ")});else{let f=d.args[0];f&&(u=new Error(f))}}catch{}throw u??new Error("An unknown error occurred.")}return c[0]}}}}var $ae=b(()=>{l();So();R4();fs();L4();lc();us();k9();qb()});function Fae(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return o=>{let s=typeof o=="function"?o(n):o,i={...n,...s};return Object.assign(i,{extend:r(i)})}}return Object.assign(t,{extend:r(t)})}function zae(){return{}}var Vae=b(()=>{l()});function jae({chains:e,id:t}){return e.find(r=>r.id===t)}var qae=b(()=>{l()});function Wg(e,t="hex"){let r=(()=>{if(typeof e=="string"){if(e.length>3&&e.length%2!==0)throw new $w(e);return qt(e)}return e})(),n=Zc(r,{recursiveReadLimit:Number.POSITIVE_INFINITY}),o=Zae(n,t);if(n.position=Wae)throw new Fw({limit:Wae});if(e.bytes.length===0)return t==="hex"?yt(e.bytes):e.bytes;let n=e.readByte();if(n<128&&e.decrementPosition(1),n<192){let s=Kae(e,n,128),i=e.readBytes(s);return t==="hex"?yt(i):i}let o=Kae(e,n,192);return wLe(e,o,t,r+1)}function Kae(e,t,r){if(r===128&&t<128)return 1;if(t<=r+55)return t-r;if(t===r+55+1)return e.readUint8();if(t===r+55+2)return e.readUint16();if(t===r+55+3)return e.readUint24();if(t===r+55+4)return e.readUint32();throw new G("Invalid RLP prefix")}function wLe(e,t,r,n){let o=e.position,s=[];for(;e.position-o{l();nt();yg();Jw();Pr();qe();Wae=1024});function i6(e){return We(e)&&e.length===66}var gT=b(()=>{l();qs()});function Gae(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}var bLe,Yae,xLe,Jae,Qae,Xae,ece,vLe,ELe,ALe,CLe,yT,wT,tce,rce=b(()=>{l();hD();Tf();bLe=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Yae=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),xLe=Yae.map(e=>(9*e+5)%16),Jae=(()=>{let r=[[Yae],[xLe]];for(let n=0;n<4;n++)for(let o of r)o.push(o[n].map(s=>bLe[s]));return r})(),Qae=Jae[0],Xae=Jae[1],ece=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),vLe=Qae.map((e,t)=>e.map(r=>ece[t][r])),ELe=Xae.map((e,t)=>e.map(r=>ece[t][r])),ALe=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),CLe=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);yT=new Uint32Array(16),wT=class extends db{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:t,h1:r,h2:n,h3:o,h4:s}=this;return[t,r,n,o,s]}set(t,r,n,o,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=o|0,this.h4=s|0}process(t,r){for(let h=0;h<16;h++,r+=4)yT[h]=t.getUint32(r,!0);let n=this.h0|0,o=n,s=this.h1|0,i=s,a=this.h2|0,c=a,u=this.h3|0,d=u,f=this.h4|0,p=f;for(let h=0;h<5;h++){let y=4-h,w=ALe[h],x=CLe[h],v=Qae[h],T=Xae[h],E=vLe[h],S=ELe[h];for(let _=0;_<16;_++){let O=S4(n+Gae(h,s,a,u)+yT[v[_]]+w,E[_])+f|0;n=f,f=u,u=S4(a,10)|0,a=s,s=O}for(let _=0;_<16;_++){let O=S4(o+Gae(y,i,c,d)+yT[T[_]]+x,S[_])+p|0;o=p,p=d,d=S4(c,10)|0,c=i,i=O}}this.set(this.h1+a+d|0,this.h2+u+p|0,this.h3+f+o|0,this.h4+n+i|0,this.h0+s+c|0)}roundClean(){ba(yT)}destroy(){this.destroyed=!0,ba(this.buffer),this.set(0,0,0,0,0)}},tce=Ww(()=>new wT)});var nce,oce=b(()=>{l();rce();nce=tce});function sce(e,t){let r=t||"hex",n=nce(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var ice=b(()=>{l();oce();qs();Pr();qe()});var ace=b(()=>{l();T4()});var cce=b(()=>{l();SI()});var lce=b(()=>{l();T4()});var uce=b(()=>{l();SI()});function WL(e){let{source:t}=e,r=new Map,n=new xo(8192),o=new Map,s=({address:a,chainId:c})=>`${a}.${c}`,i=a=>{r.delete(a),o.delete(a)};return{async consume({address:a,chainId:c,client:u}){let d=s({address:a,chainId:c}),f=this.get({address:a,chainId:c,client:u});this.increment({address:a,chainId:c});let p=await f;return await t.set({address:a,chainId:c},p),n.set(d,p),p},async increment({address:a,chainId:c}){let u=s({address:a,chainId:c}),d=r.get(u)??0;r.set(u,d+1)},async get({address:a,chainId:c,client:u}){let d=s({address:a,chainId:c}),f=o.get(d);return f||(f=(async()=>{try{let h=await t.get({address:a,chainId:c,client:u}),y=n.get(d);return y!==void 0&&h<=y?y+1:(n.delete(d),h)}finally{i(d)}})(),o.set(d,f)),(r.get(d)??0)+await f},reset({address:a,chainId:c}){let u=s({address:a,chainId:c});n.delete(u),i(u)}}}function SLe(){return{async get(e){let{address:t,client:r}=e;return k0(r,{address:t,blockTag:"pending"})},set(){}}}var dce,fce=b(()=>{l();e3();_f();dce=WL({source:SLe()})});function ILe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var a6,KL=b(()=>{l();a6=ILe()});function mce(e,t={}){let{url:r,headers:n}=_Le(e);return{async request(o){let{body:s,fetchFn:i=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??TLe,onRequest:c=t.onRequest,onResponse:u=t.onResponse,timeout:d=t.timeout??1e4}=o,f={...t.fetchOptions??{},...o.fetchOptions??{}},{headers:p,method:h,signal:y}=f;try{let{response:w,responseBody:x}=await sl(async({signal:E})=>{let{signal:S,cleanup:_}=P9([y,d>0?E:null]);try{let O={};for(let P of[n,{"Content-Type":"application/json"},p])new Headers(P).forEach((R,I)=>{O[I]=R});let D={...f,body:Array.isArray(s)?bt(s.map(P=>({jsonrpc:"2.0",id:P.id??a6.take(),...P}))):bt({jsonrpc:"2.0",id:s.id??a6.take(),...s}),headers:O,method:h||"POST",signal:S},M=(c&&await c(new Request(r,D),D))??{...D,url:r},N=await i(M.url??r,M);u&&await u(N);let L=await Wb(N,{maxResponseBodySize:a});return{response:N,responseBody:L}}finally{_()}},{errorInstance:pce,timeout:d,signal:!0}),v;if(w.headers.get("Content-Type")?.startsWith("application/json"))v=JSON.parse(x);else{v=x;try{v=JSON.parse(v||"{}")}catch(E){if(w.ok)throw E;v={error:v}}}let T=Array.isArray(s)&&Array.isArray(v)&&v.length===1?v[0]:v;if(!w.ok)throw hce(T)?new Rn({body:s,error:T.error,headers:w.headers,status:w.status,url:r}):new Nr({body:s,details:bt(v.error)||w.statusText,headers:w.headers,status:w.status,url:r});if(!Array.isArray(s)||!s.length||Array.isArray(v)&&v.length>=s.length)return v;if(!hce(T))throw new Error(`Expected ${s.length} responses to batch request.`);return s.map(()=>T)}catch(w){throw y?.aborted?Nn(y):w===pce?new ds({body:s,url:r}):Ii(w)||w instanceof Nr||w instanceof ic||w instanceof Rn||w instanceof ds?w:new Nr({body:s,cause:w,url:r})}}}}function hce(e){return typeof e?.error?.code=="number"&&typeof e?.error?.message=="string"}function _Le(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:t.toString(),...r}}catch{return{url:e}}}var TLe,pce,gce=b(()=>{l();fs();oc();N9();Kb();so();KL();TLe=10485760,pce=new Error("timed out")});async function wce(e){let{getSocket:t,keepAlive:r=!0,key:n="socket",reconnect:o=!0,url:s}=e,{interval:i=3e4}=typeof r=="object"?r:{},{attempts:a=5,delay:c=2e3}=typeof o=="object"?o:{},u=JSON.stringify({keepAlive:r,key:n,url:s,reconnect:o}),d=ZL.get(u);if(d)return d;let f=0,{schedule:p}=Z0({id:u,fn:async()=>{let w=new Map,x=new Map,v,T,E,S,_=!1,O=!1;function D(){if(o&&!O&&f{if(S=void 0,O){_=!1;return}await M().catch(console.error),_=!1},c)}else w.clear(),x.clear()}async function M(){let N=await t({onClose(){for(let L of w.values())L.onError?.(new su({url:s}));for(let L of x.values())L.onError?.(new su({url:s}));D()},onError(L){v=L;for(let P of w.values())P.onError?.(v);for(let P of x.values())P.onError?.(v);D()},onOpen(){v=void 0,f=0},onResponse(L){let P=L.method==="eth_subscription",R=P?L.params.subscription:L.id,I=P?x:w,B=I.get(R);B&&B.onResponse(L),P||I.delete(R)}});if(O)return N.close(),N;if(T=N,r&&(E&&clearInterval(E),E=setInterval(()=>T.ping?.(),i)),o&&x.size>0){let L=x.entries();for(let[P,{onResponse:R,body:I,onError:B}]of L)I&&(x.delete(P),d?.request({body:I,onResponse:R,onError:B}))}return N}return await M(),v=void 0,d={close(){O=!0,E&&clearInterval(E),S&&(clearTimeout(S),S=void 0,_=!1),T.close(),ZL.delete(u)},get socket(){return T},request({body:N,onError:L,onResponse:P}){v&&L&&L(v);let R=N.id??a6.take(),I=B=>{typeof B.id=="number"&&R!==B.id||(N.method==="eth_subscribe"&&typeof B.result=="string"&&x.set(B.result,{onResponse:P,onError:L,body:N}),P(B))};N.method==="eth_unsubscribe"&&x.delete(N.params?.[0]),w.set(R,{onResponse:I,onError:L});try{T.request({body:{jsonrpc:"2.0",id:R,...N}})}catch(B){L?.(B)}},async requestAsync({body:N,timeout:L=1e4}){let P=N.id??a6.take();try{return await sl(()=>new Promise((R,I)=>this.request({body:{...N,id:P},onError:I,onResponse:R})),{errorInstance:yce,timeout:L})}catch(R){throw R===yce?new ds({body:N,url:s}):R}finally{w.delete(P)}},requests:w,subscriptions:x,url:s},ZL.set(u,d),[d]}}),[h,[y]]=await p();return y}var ZL,yce,bce=b(()=>{l();fs();h3();Kb();KL();ZL=new Map,yce=new Error("timed out")});function xce(){if(typeof m<"u")return m;if(typeof global.WebSocket<"u")return global.WebSocket;if(typeof window.WebSocket<"u")return window.WebSocket;if(typeof self.WebSocket<"u")return self.WebSocket;throw new Error("`WebSocket` is not supported in this environment")}var vce=b(()=>{l()});var Ece={};Te(Ece,{WebSocket:()=>PLe});var PLe,Ace=b(()=>{l();vce();PLe=xce()});async function c6(e,t={}){let{keepAlive:r,reconnect:n}=t;return wce({async getSocket({onClose:o,onError:s,onOpen:i,onResponse:a}){let c=await Promise.resolve().then(()=>(Ace(),Ece)).then(h=>h.WebSocket),u=new c(e);function d(){u.removeEventListener("close",d),u.removeEventListener("message",f),u.removeEventListener("error",s),u.removeEventListener("open",i),o()}function f({data:h}){if(!(typeof h=="string"&&h.trim().length===0))try{let y=JSON.parse(h);a(y)}catch(y){s(y)}}u.addEventListener("close",d),u.addEventListener("message",f),u.addEventListener("error",s),u.addEventListener("open",i),u.readyState===c.CONNECTING&&await new Promise((h,y)=>{u&&(u.onopen=h,u.onerror=y)});let{close:p}=u;return Object.assign(u,{close(){p.bind(u)(),d()},ping(){try{if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new _g({url:u.url,cause:new su({url:u.url})});let h={jsonrpc:"2.0",id:null,method:"net_version",params:[]};u.send(JSON.stringify(h))}catch(h){s(h)}},request({body:h}){if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new _g({body:h,url:u.url,cause:new su({url:u.url})});return u.send(JSON.stringify(h))}})},keepAlive:r,reconnect:n,url:e})}var GL=b(()=>{l();fs();bce()});async function Cce(e){let t=await c6(e);return Object.assign(t.socket,{requests:t.requests,subscriptions:t.subscriptions})}var Sce=b(()=>{l();GL()});var bT,YL=b(()=>{l();bT=`Ethereum Signed Message: +`});function xT(e){let t=typeof e=="string"?ec(e):typeof e.raw=="string"?e.raw:yt(e.raw),r=ec(`${bT}${gt(t)}`);return en([r,t])}var JL=b(()=>{l();YL();Fn();Fo();qe()});function im(e,t){return Pt(xT(e),t)}var T3=b(()=>{l();Ks();JL()});var l6,u6,d6,Kg,QL=b(()=>{l();so();nt();l6=class extends G{constructor({domain:t}){super(`Invalid domain "${bt(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."],name:"InvalidDomainError"})}},u6=class extends G{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."],name:"InvalidPrimaryTypeError"})}},d6=class extends G{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:['Struct type must contain only letters, digits, "_", "$" and ":", and must not be a Solidity type.'],name:"InvalidStructTypeError"})}},Kg=class extends G{constructor({type:t}){let r=/^u?int(\[[0-9]*\])*$/.test(t);super(`Type "${t}" is not a valid EIP-712 type.`,{metaMessages:r?[`Use "${t.replace(/^(u?int)/,"$&256")}" instead.`]:void 0,name:"InvalidTypedDataTypeError"})}}});function vT(e){let{domain:t,message:r,primaryType:n,types:o}=e,s=(c,u)=>{let d={...u};for(let f of c){let{name:p,type:h}=f;h==="address"&&(d[p]=d[p].toLowerCase())}return d},i=o.EIP712Domain?t?s(o.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return s(o[n],r)})();return bt({domain:i,message:a,primaryType:n,types:o})}function f6(e){let{domain:t,message:r,primaryType:n,types:o}=e,s=(i,a)=>{for(let c of i){let{name:u,type:d}=c,f=a[u],p=d.match(Rf);if(p&&(typeof f=="number"||typeof f=="bigint")){let[y,w,x]=p;oe(f,{signed:w==="int",size:Number.parseInt(x,10)/8})}if(d==="address"&&typeof f=="string"&&!Ft(f))throw new br({address:f});let h=d.match(Eg);if(h){let[y,w]=h;if(w&>(f)!==Number.parseInt(w,10))throw new Lh({expectedSize:Number.parseInt(w,10),givenSize:gt(f)})}Object.hasOwn(o,d)&&s(o[d],f)}};for(let i of Object.keys(o))OLe(i);for(let i of Object.values(o))for(let a of i??[])NLe(a.type,o);if(o.EIP712Domain&&t){if(typeof t!="object")throw new l6({domain:t});s(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])s(o[n],r);else throw new u6({primaryType:n,types:o})}function Zg({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},typeof e?.version=="string"&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function Ice({domain:e}){return _3({domain:e,types:{EIP712Domain:Zg({domain:e})}})}function NLe(e,t){let r=e.replace(/(\[[0-9]*\])+$/,"");if(r==="int"||r==="uint")throw new Kg({type:e});if(!Object.hasOwn(t,r)&&!RLe(r))throw new Kg({type:e})}function RLe(e){return e==="address"||e==="bool"||e==="string"||Eg.test(e)||Rf.test(e)}function OLe(e){if(!/^[A-Za-z0-9_$:]+$/.test(e)||e==="address"||e==="bool"||e==="string"||/^(u?int|bytes)[0-9]*$/.test(e))throw new d6({type:e})}var ET=b(()=>{l();Qr();tc();QL();Gs();Fo();qe();P4();P3();so()});function p6(e){let{domain:t={},message:r,primaryType:n}=e,o={EIP712Domain:Zg({domain:t}),...e.types};f6({domain:t,message:r,primaryType:n,types:o});let s=["0x1901"];return t&&s.push(_3({domain:t,types:o})),n!=="EIP712Domain"&&s.push(AT({data:r,primaryType:n,types:o})),Pt(en(s))}function _3({domain:e,types:t}){return AT({data:e,primaryType:"EIP712Domain",types:t})}function AT({data:e,primaryType:t,types:r}){let n=Tce({data:e,primaryType:t,types:r});return Pt(n)}function Tce({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],o=[BLe({primaryType:t,types:r})];for(let s of r[t]){let[i,a]=Pce({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(i),o.push(a)}return oo(n,o)}function BLe({primaryType:e,types:t}){let r=wr(kLe({primaryType:e,types:t}));return Pt(r)}function kLe({primaryType:e,types:t}){let r="",n=_ce({primaryType:e,types:t});n.delete(e);let o=[e,...Array.from(n).sort()];for(let s of o)r+=`${s}(${t[s].map(({name:i,type:a})=>`${a} ${i}`).join(",")})`;return r}function _ce({primaryType:e,types:t},r=new Set){let n=e.replace(/(\[[0-9]*\])+$/,"");if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let o of t[n])_ce({primaryType:o.type,types:t},r);return r}function Pce({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},Pt(Tce({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},Pt(n)];if(r==="string")return[{type:"bytes32"},Pt(wr(n))];if(r.lastIndexOf("]")===r.length-1){let o=r.slice(0,r.lastIndexOf("[")),s=n.map(i=>Pce({name:t,type:o,types:e,value:i}));return[{type:"bytes32"},Pt(oo(s.map(([i])=>i),s.map(([,i])=>i)))]}return[{type:r},n]}var P3=b(()=>{l();rc();Fn();qe();Ks();ET()});var CT,Nce,ST=b(()=>{l();CT="0x6492649264926492649264926492649264926492649264926492649264926492",Nce="0x0000000000000000000000000000000000000000000000000000000000000000"});function IT(e){return xa(e,-32)===CT}var XL=b(()=>{l();ST();Si()});var N3,Rce=b(()=>{l();N3=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});var R3,eM=b(()=>{l();Rce();R3={checksum:new N3(8192),signatureHash:new N3(8192)}});var TT,Oce=b(()=>{l();eM();TT=R3.checksum});function Gg(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=CI(aL(e));return r==="Bytes"?n:vn(n)}var _T=b(()=>{l();JU();mu();io()});function Bce(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new PT({prefix:n,cause:new oM});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new PT({prefix:n,cause:new nM});return}throw new rM({publicKey:e})}function kce(e){let t=(()=>{if(q0(e))return Uce(e);if(oie(e))return DLe(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return Bce(t),t}function DLe(e){return Uce(vn(e))}function Uce(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new sM({publicKey:e});if(e.length===130){let n=BigInt(rn(e,0,32)),o=BigInt(rn(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(rn(e,0,1)),o=BigInt(rn(e,1,33)),s=BigInt(rn(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(rn(e,0,1)),r=BigInt(rn(e,1,33));return{prefix:t,x:r}}function iM(e,t={}){Bce(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return fn(s?Yt(r,{size:1}):"0x",Yt(n,{size:32}),typeof o=="bigint"?Yt(o,{size:32}):"0x")}var rM,PT,nM,oM,sM,aM=b(()=>{l();mu();Bi();io();d3();rM=class extends Ke{constructor({publicKey:t}){super(`Value \`${z0(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},PT=class extends Ke{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},nM=class extends Ke{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},oM=class extends Ke{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},sM=class extends Ke{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Mr(Hb(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});function Yg(e,t={}){let{strict:r=!0}=t;if(!LLe.test(e))throw new h6({address:e,cause:new O3});if(r){if(e.toLowerCase()===e)return;if(NT(e)!==e)throw new h6({address:e,cause:new cM})}}function NT(e){if(TT.has(e))return TT.get(e);Yg(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=Gg(Mb(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return TT.set(e,o),o}function MLe(e,t={}){let{checksum:r=!1}=t;return Yg(e),r?NT(e):e}function Lce(e,t={}){let r=Gg(`0x${iM(e).slice(4)}`).substring(26);return MLe(`0x${r}`,t)}function lM(e,t={}){let{strict:r=!0}=t??{};try{return Yg(e,{strict:r}),!0}catch{return!1}}var LLe,h6,O3,cM,B3=b(()=>{l();mu();Oce();Bi();_T();aM();LLe=/^0x[a-fA-F0-9]{40}$/;h6=class extends Ke{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},O3=class extends Ke{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},cM=class extends Ke{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});var Mce,Hce,OT,AOt,COt,SOt,IOt,TOt,_Ot,POt,NOt,ROt,OOt,BOt,kOt,UOt,DOt,LOt,MOt,HOt,$Ot,FOt,zOt,VOt,jOt,qOt,WOt,KOt,ZOt,GOt,YOt,JOt,QOt,XOt,eBt,tBt,rBt,nBt,oBt,sBt,iBt,aBt,cBt,lBt,uBt,dBt,fBt,pBt,hBt,mBt,gBt,yBt,wBt,bBt,xBt,vBt,EBt,ABt,CBt,SBt,IBt,TBt,_Bt,PBt,NBt,RBt,OBt,BBt,kBt,UBt,DBt,LBt,MBt,HBt,$Bt,FBt,zBt,VBt,jBt,qBt,WBt,KBt,ZBt,GBt,YBt,JBt,QBt,XBt,ekt,tkt,rkt,nkt,okt,skt,ikt,akt,ckt,lkt,uM,BT=b(()=>{l();Mce=/^(.*)\[([0-9]*)\]$/,Hce=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,OT=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,AOt=2n**(8n-1n)-1n,COt=2n**(16n-1n)-1n,SOt=2n**(24n-1n)-1n,IOt=2n**(32n-1n)-1n,TOt=2n**(40n-1n)-1n,_Ot=2n**(48n-1n)-1n,POt=2n**(56n-1n)-1n,NOt=2n**(64n-1n)-1n,ROt=2n**(72n-1n)-1n,OOt=2n**(80n-1n)-1n,BOt=2n**(88n-1n)-1n,kOt=2n**(96n-1n)-1n,UOt=2n**(104n-1n)-1n,DOt=2n**(112n-1n)-1n,LOt=2n**(120n-1n)-1n,MOt=2n**(128n-1n)-1n,HOt=2n**(136n-1n)-1n,$Ot=2n**(144n-1n)-1n,FOt=2n**(152n-1n)-1n,zOt=2n**(160n-1n)-1n,VOt=2n**(168n-1n)-1n,jOt=2n**(176n-1n)-1n,qOt=2n**(184n-1n)-1n,WOt=2n**(192n-1n)-1n,KOt=2n**(200n-1n)-1n,ZOt=2n**(208n-1n)-1n,GOt=2n**(216n-1n)-1n,YOt=2n**(224n-1n)-1n,JOt=2n**(232n-1n)-1n,QOt=2n**(240n-1n)-1n,XOt=2n**(248n-1n)-1n,eBt=2n**(256n-1n)-1n,tBt=-(2n**(8n-1n)),rBt=-(2n**(16n-1n)),nBt=-(2n**(24n-1n)),oBt=-(2n**(32n-1n)),sBt=-(2n**(40n-1n)),iBt=-(2n**(48n-1n)),aBt=-(2n**(56n-1n)),cBt=-(2n**(64n-1n)),lBt=-(2n**(72n-1n)),uBt=-(2n**(80n-1n)),dBt=-(2n**(88n-1n)),fBt=-(2n**(96n-1n)),pBt=-(2n**(104n-1n)),hBt=-(2n**(112n-1n)),mBt=-(2n**(120n-1n)),gBt=-(2n**(128n-1n)),yBt=-(2n**(136n-1n)),wBt=-(2n**(144n-1n)),bBt=-(2n**(152n-1n)),xBt=-(2n**(160n-1n)),vBt=-(2n**(168n-1n)),EBt=-(2n**(176n-1n)),ABt=-(2n**(184n-1n)),CBt=-(2n**(192n-1n)),SBt=-(2n**(200n-1n)),IBt=-(2n**(208n-1n)),TBt=-(2n**(216n-1n)),_Bt=-(2n**(224n-1n)),PBt=-(2n**(232n-1n)),NBt=-(2n**(240n-1n)),RBt=-(2n**(248n-1n)),OBt=-(2n**(256n-1n)),BBt=2n**8n-1n,kBt=2n**16n-1n,UBt=2n**24n-1n,DBt=2n**32n-1n,LBt=2n**40n-1n,MBt=2n**48n-1n,HBt=2n**56n-1n,$Bt=2n**64n-1n,FBt=2n**72n-1n,zBt=2n**80n-1n,VBt=2n**88n-1n,jBt=2n**96n-1n,qBt=2n**104n-1n,WBt=2n**112n-1n,KBt=2n**120n-1n,ZBt=2n**128n-1n,GBt=2n**136n-1n,YBt=2n**144n-1n,JBt=2n**152n-1n,QBt=2n**160n-1n,XBt=2n**168n-1n,ekt=2n**176n-1n,tkt=2n**184n-1n,rkt=2n**192n-1n,nkt=2n**200n-1n,okt=2n**208n-1n,skt=2n**216n-1n,ikt=2n**224n-1n,akt=2n**232n-1n,ckt=2n**240n-1n,lkt=2n**248n-1n,uM=2n**256n-1n});function Jg(e,t,r){let{checksumAddress:n,staticPosition:o}=r,s=Qg(t.type);if(s){let[i,a]=s;return $Le(e,{...t,type:a},{checksumAddress:n,length:i,staticPosition:o})}if(t.type==="tuple")return jLe(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return HLe(e,{checksum:n});if(t.type==="bool")return FLe(e);if(t.type.startsWith("bytes"))return zLe(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return VLe(e,t);if(t.type==="string")return qLe(e,{staticPosition:o});throw new g6(t.type)}function HLe(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);for(let s=0;s<12;s++)if(n[s]!==0)throw new h6({address:vn(n),cause:new O3});return[(s=>r?NT(s):s)(vn(tie(n,-20))),32]}function $Le(e,t,r){let{checksumAddress:n,length:o,staticPosition:s}=r;if(o===null){let c=Xf(e.readBytes(dM)),u=s+c,d=u+Fce;e.setPosition(u);let f=Xf(e.readBytes(Fce)),p=m6(t),h=0,y=[];for(let w=0;ws||o48?o:Number(o),32]}function jLe(e,t,r){let{checksumAddress:n,staticPosition:o}=r,s=t.components.length===0||t.components.some(({name:c})=>!c),i=s?[]:{},a=0;if(m6(t)){let c=Xf(e.readBytes(dM)),u=o+c;for(let d=0;d0?fn(u,c):u}}if(i)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:fn(...a.map(({encoded:c})=>c))}}function ZLe(e,{type:t}){let[,r]=t.split("bytes"),n=Mr(e);if(!r){let o=e;return n%32!==0&&(o=j0(o,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:fn(ep(Yt(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new k3({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:j0(e)}}function GLe(e){if(typeof e!="boolean")throw new Ke(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ep(g9(e))}}function YLe(e,{signed:t,size:r}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||ei))}}function Qg(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function m6(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(m6);let r=Qg(e.type);return!!(r&&m6({...e,type:r[1]}))}var Fce,dM,pM=b(()=>{l();y6();B3();mu();Bi();io();BT();Fce=32,dM=32});function MT(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(eMe);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var eMe,LT,hM,mM,gM=b(()=>{l();Bi();eMe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new mM({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new hM({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new LT({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new LT({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};LT=class extends Ke{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}},hM=class extends Ke{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}},mM=class extends Ke{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}});function Xg(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,s=typeof t=="string"?Lg(t):t,i=MT(s);if(uc(s)===0&&e.length>0)throw new bM;if(uc(s)&&uc(s)<32)throw new wM({data:typeof t=="string"?t:vn(t),parameters:e,size:uc(s)});let a=0,c=n==="Array"?[]:{};for(let u=0;u{l();fg();B3();mu();Bi();io();pM();gM();BT();(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return Yg(c),ep(c.toLowerCase(),o?32:0)}if(r==="string")return $b(n);if(r==="bytes")return n;if(r==="bool")return ep(g9(n),o?32:1);let s=r.match(OT);if(s){let[c,u,d="256"]=s,f=Number.parseInt(d,10)/8;return Yt(n,{size:o?32:f,signed:u==="int"})}let i=r.match(Hce);if(i){let[c,u]=i;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new k3({expectedSize:Number.parseInt(u,10),value:n});return j0(n,o?32:0)}let a=r.match(Mce);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let f=0;fqce(t))):nMe(e)}function rMe(e){let t=e.reduce((o,s)=>o+s.length,0),r=Wce(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function nMe(e){let t=typeof e=="string"?Lg(e):e,r=Wce(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function Wce(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new Ke("Length is too large.")}var Kce=b(()=>{l();mu();Bi();io();gM()});function H3(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new L3({signature:e});if(typeof e.s>"u")throw new L3({signature:e});if(r&&typeof e.yParity>"u")throw new L3({signature:e});if(e.r<0n||e.r>uM)throw new vM({value:e.r});if(e.s<0n||e.s>uM)throw new EM({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new M3({value:e.yParity})}function sMe(e){return Zce(vn(e))}function Zce(e){if(e.length!==130&&e.length!==132)throw new xM({signature:e});let t=BigInt(rn(e,0,32)),r=BigInt(rn(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return IM(o)}catch{throw new M3({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function Gce(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return CM(e)}function CM(e){let t=typeof e=="string"?Zce(e):e instanceof Uint8Array?sMe(e):typeof e.r=="string"?SM(e):e.v?iMe(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return H3(t),t}function iMe(e){return{r:e.r,s:e.s,yParity:IM(e.v)}}function SM(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=IM(r)),typeof n!="number")throw new M3({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function IM(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new AM({value:e})}var xM,L3,vM,EM,M3,AM,TM=b(()=>{l();Bi();io();d3();BT();xM=class extends Ke{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Mr(Hb(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},L3=class extends Ke{constructor({signature:t}){super(`Signature \`${z0(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},vM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},EM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},M3=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},AM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}});function Jce(e,t={}){return typeof e.chainId=="string"?aMe(e):{...e,...t.signature}}function aMe(e){let{address:t,chainId:r,nonce:n}=e,o=SM(e);return H3({r:o.r,s:o.s}),Xce(o.yParity),{address:t,chainId:Number(r),nonce:BigInt(n),...o}}function Qce(e){return cMe(e,{presign:!0})}function cMe(e,t={}){let{presign:r}=t;return Gg(fn("0x05",jce(lMe(r?{address:e.address,chainId:e.chainId,nonce:e.nonce}:e))))}function lMe(e){let{address:t,chainId:r,nonce:n,r:o,s,yParity:i}=e,a=Gce({r:o,s});return a&&typeof i<"u"&&Xce(i),[r?Yt(r):"0x",t,n?Yt(n):"0x",...a?[i?Yt(i,{size:1}):"0x",a.r===0n?"0x":y9(Yt(a.r)),a.s===0n?"0x":y9(Yt(a.s))]:[]]}function Xce(e){if(!(Number.isInteger(e)&&e>=0&&e<256))throw new V0({max:"255",min:"0",signed:!1,size:1,value:`${e}`})}var ele=b(()=>{l();_T();io();Kce();TM()});function tle(e){return Lce(dMe(e))}function dMe(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new ei.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Hb(t).substring(2));return kce(a)}var Ekt,rle=b(()=>{l();Bg();B3();mu();io();aM();Ekt=Mb("ox.secp256k1.fromSeed.v1")});var il={};Te(il,{InvalidWrappedSignatureError:()=>$T,assert:()=>FT,from:()=>pMe,magicBytes:()=>_M,suffixParameters:()=>PM,unwrap:()=>nle,validate:()=>mMe,wrap:()=>hMe});function FT(e){if(typeof e=="string"){if(rn(e,-32)!==_M)throw new $T(e)}else H3(e.authorization)}function pMe(e){return typeof e=="string"?nle(e):e}function nle(e){FT(e);let t=f9(rn(e,-64,-32)),r=rn(e,-t-64,-64),n=rn(e,0,-t-64),[o,s,i]=Xg(PM,r);return{authorization:Jce({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...i&&i!=="0x"?{data:i,to:s}:{}}}function hMe(e){let{data:t,signature:r}=e;FT(e);let n=tle({payload:Qce(e.authorization),signature:CM(e.authorization)}),o=am(PM,[{...e.authorization,delegation:e.authorization.address,chainId:BigInt(e.authorization.chainId)},e.to??n,t??"0x"]),s=Yt(Mr(o),{size:32});return fn(r,o,s,_M)}function mMe(e){try{return FT(e),!0}catch{return!1}}var _M,PM,$T,ole=b(()=>{l();y6();ele();Bi();io();rle();TM();_M="0x8010801080108010801080108010801080108010801080108010801080108010",PM=D3("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");$T=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}});var $3=b(()=>{l();ole()});function zT(e){return il.validate(e)}var NM=b(()=>{l();$3()});function sle(e){if(!IT(e))return{signature:e};let[t,r,n]=Ys([{type:"address"},{type:"bytes"},{type:"bytes"}],e);return{address:t,data:r,signature:n}}var ile=b(()=>{l();zh();XL()});function ale(e){if(!zT(e))return{signature:e};let{authorization:t,to:r,...n}=il.unwrap(e);return{authorization:{address:t.address,chainId:t.chainId,nonce:Number(t.nonce),r:oe(t.r,{size:32}),s:oe(t.s,{size:32}),yParity:t.yParity},...r?{address:r}:{},...n}}var cle=b(()=>{l();$3();qe();NM()});async function VT({message:e,signature:t}){return ti({hash:im(e),signature:t})}var RM=b(()=>{l();T3();w0()});async function jT(e){let{domain:t,message:r,primaryType:n,signature:o,types:s}=e;return ti({hash:p6({domain:t,message:r,primaryType:n,types:s}),signature:o})}var OM=b(()=>{l();P3();w0()});function lle(e){let{address:t,data:r,signature:n,to:o="hex"}=e,s=fr([oo([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),CT]);return o==="hex"?s:qt(s)}var ule=b(()=>{l();ST();rc();Fn();Pr()});function dle(e){let{address:t,data:r,signature:n,to:o="hex"}=e,s=il.wrap({authorization:{address:e.authorization.address,chainId:e.authorization.chainId,nonce:BigInt(e.authorization.nonce),r:BigInt(e.authorization.r),s:BigInt(e.authorization.s),yParity:e.authorization.yParity},data:r,signature:n,to:t});return o==="hex"?s:qt(s)}var fle=b(()=>{l();$3();Pr()});async function ple({address:e,hash:t,signature:r}){return xr(Gr(e),await ti({hash:t,signature:r}))}var hle=b(()=>{l();Zs();Oi();w0()});async function mle({address:e,message:t,signature:r}){return xr(Gr(e),await VT({message:t,signature:r}))}var gle=b(()=>{l();Zs();Oi();RM()});async function yle(e){let{address:t,domain:r,message:n,primaryType:o,signature:s,types:i}=e;return xr(Gr(t),await jT({domain:r,message:n,primaryType:o,signature:s,types:i}))}var wle=b(()=>{l();Zs();Oi();OM()});function qT(e){let t=xa(e,0,1);if(t==="0x04")return"eip7702";if(t==="0x03")return"eip4844";if(t==="0x02")return"eip1559";if(t==="0x01")return"eip2930";if(t!=="0x"&&wt(t)>=192)return"legacy";throw new ob({serializedType:t})}var BM=b(()=>{l();zn();Si();Xr()});function WT(e){let t=qT(e);return t==="eip1559"?wMe(e):t==="eip2930"?bMe(e):t==="eip4844"?yMe(e):t==="eip7702"?gMe(e):xMe(e)}function gMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p,h,y]=t;if(t.length!==10&&t.length!==13)throw new ru({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:o,maxFeePerGas:s,gas:i,to:a,value:c,data:u,accessList:d,authorizationList:f,...t.length>9?{v:p,r:h,s:y}:{}},serializedTransaction:e,type:"eip7702"});let w={chainId:wt(r),type:"eip7702"};return We(a)&&a!=="0x"&&(w.to=a),We(i)&&i!=="0x"&&(w.gas=dt(i)),We(u)&&u!=="0x"&&(w.data=u),We(n)&&(w.nonce=n==="0x"?0:wt(n)),We(c)&&c!=="0x"&&(w.value=dt(c)),We(o)&&o!=="0x"&&(w.maxPriorityFeePerGas=dt(o)),We(s)&&(s!=="0x"||w.maxPriorityFeePerGas)&&(w.maxFeePerGas=s==="0x"?0n:dt(s)),d.length!==0&&d!=="0x"&&(w.accessList=ZT(d)),f.length!==0&&f!=="0x"&&(w.authorizationList=vMe(f)),lT(w),{...t.length===13?F3(t):void 0,...w}}function yMe(e){let t=KT(e),r=t.length===4,n=r?t[0]:t,o=r?t.slice(1):[],[s,i,a,c,u,d,f,p,h,y,w,x,v,T]=n,[E,S,_]=o;if(!(n.length===11||n.length===14))throw new ru({attributes:{chainId:s,nonce:i,maxPriorityFeePerGas:a,maxFeePerGas:c,gas:u,to:d,value:f,data:p,accessList:h,...n.length>9?{v:x,r:v,s:T}:{}},serializedTransaction:e,type:"eip4844"});let O={blobVersionedHashes:w,chainId:wt(s),to:d,type:"eip4844"};return We(u)&&u!=="0x"&&(O.gas=dt(u)),We(p)&&p!=="0x"&&(O.data=p),We(i)&&(O.nonce=i==="0x"?0:wt(i)),We(f)&&f!=="0x"&&(O.value=dt(f)),We(y)&&y!=="0x"&&(O.maxFeePerBlobGas=dt(y)),We(a)&&a!=="0x"&&(O.maxPriorityFeePerGas=dt(a)),We(c)&&(c!=="0x"||O.maxPriorityFeePerGas)&&(O.maxFeePerGas=c==="0x"?0n:dt(c)),h.length!==0&&h!=="0x"&&(O.accessList=ZT(h)),E&&S&&_&&(O.sidecars=M0({blobs:E,commitments:S,proofs:_})),uT(O),{...n.length===14?F3(n):void 0,...O}}function wMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p,h]=t;if(!(t.length===9||t.length===12))throw new ru({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:o,maxFeePerGas:s,gas:i,to:a,value:c,data:u,accessList:d,...t.length>9?{v:f,r:p,s:h}:{}},serializedTransaction:e,type:"eip1559"});let y={chainId:wt(r),type:"eip1559"};return We(a)&&a!=="0x"&&(y.to=a),We(i)&&i!=="0x"&&(y.gas=dt(i)),We(u)&&u!=="0x"&&(y.data=u),We(n)&&(y.nonce=n==="0x"?0:wt(n)),We(c)&&c!=="0x"&&(y.value=dt(c)),We(o)&&o!=="0x"&&(y.maxPriorityFeePerGas=dt(o)),We(s)&&(s!=="0x"||y.maxPriorityFeePerGas)&&(y.maxFeePerGas=s==="0x"?0n:dt(s)),d.length!==0&&d!=="0x"&&(y.accessList=ZT(d)),sm(y),{...t.length===12?F3(t):void 0,...y}}function bMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p]=t;if(!(t.length===8||t.length===11))throw new ru({attributes:{chainId:r,nonce:n,gasPrice:o,gas:s,to:i,value:a,data:c,accessList:u,...t.length>8?{v:d,r:f,s:p}:{}},serializedTransaction:e,type:"eip2930"});let h={chainId:wt(r),type:"eip2930"};return We(i)&&i!=="0x"&&(h.to=i),We(s)&&s!=="0x"&&(h.gas=dt(s)),We(c)&&c!=="0x"&&(h.data=c),We(n)&&(h.nonce=n==="0x"?0:wt(n)),We(a)&&a!=="0x"&&(h.value=dt(a)),We(o)&&o!=="0x"&&(h.gasPrice=dt(o)),u.length!==0&&u!=="0x"&&(h.accessList=ZT(u)),n6(h),{...t.length===11?F3(t):void 0,...h}}function xMe(e){let t=Wg(e,"hex"),[r,n,o,s,i,a,c,u,d]=t;if(!(t.length===6||t.length===9))throw new ru({attributes:{nonce:r,gasPrice:n,gas:o,to:s,value:i,data:a,...t.length>6?{v:c,r:u,s:d}:{}},serializedTransaction:e,type:"legacy"});let f={type:"legacy"};if(We(s)&&s!=="0x"&&(f.to=s),We(o)&&o!=="0x"&&(f.gas=dt(o)),We(a)&&a!=="0x"&&(f.data=a),We(r)&&(f.nonce=r==="0x"?0:wt(r)),We(i)&&i!=="0x"&&(f.value=dt(i)),We(n)&&n!=="0x"&&(f.gasPrice=dt(n)),o6(f),t.length===6)return f;let p=We(c)&&c!=="0x"?dt(c):0n;if(d==="0x"&&u==="0x")return p>0&&(f.chainId=Number(p)),f;let h=p,y=Number((h-35n)/2n);if(y>0)f.chainId=y;else if(h!==27n&&h!==28n)throw new Kh({v:h});return f.v=h,f.s=d,f.r=u,f.yParity=h%2n===0n?1:0,f}function KT(e){return Wg(`0x${e.slice(4)}`,"hex")}function ZT(e){let t=[];for(let r=0;ri6(s)?s:bn(s))})}return t}function vMe(e){let t=[];for(let r=0;r1n&&u<256n?{r:cs(a,{size:32}),s:cs(c,{size:32}),yParity:Number(u)}:F3([i,a,c]);t.push({address:o,chainId:n==="0x"?0:wt(n),nonce:s==="0x"?0:wt(s),...d})}return t}function F3(e){let t=e.slice(-3),r=t[0]==="0x"?0n:dt(t[0]);if(r!==0n&&r!==1n)throw new tu({yParity:r});let n=r===0n?27n:28n;return{r:cs(t[1],{size:32}),s:cs(t[2],{size:32}),v:n,yParity:n===27n?0:1}}var kM=b(()=>{l();tc();zn();Gs();n3();qs();Xa();Hh();Xr();mT();gT();dT();BM()});function pc(e,t){return NI(e,t)}var z3=b(()=>{l();Sg()});function ble(e,t="wei"){return Kre(e,t)}var xle=b(()=>{l();Sg()});function vle(e,t="wei"){return Zre(e,t)}var Ele=b(()=>{l();Sg()});function GT(e,t){return RI(e,t)}var UM=b(()=>{l();Sg()});var DM=b(()=>{l();us();Xr()});function EMe(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function Ale(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?wt(e.nonce):void 0,storageProof:e.storageProof?EMe(e.storageProof):void 0}}var Cle=b(()=>{l();DM()});async function Sle(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s,storageKeys:i}){let a=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),c=await e.request({method:"eth_getProof",params:[t,i,a]});return Ale(c)}var Ile=b(()=>{l();B0();Cle()});async function Tle(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new Gc({hash:t});return r}var _le=b(()=>{l();zn()});async function Ple(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s,slot:i}){let a=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});return await e.request({method:"eth_getStorageAt",params:[t,i,a]})}var Nle=b(()=>{l();B0()});async function Rle(e,{blockHash:t,blockNumber:r,blockTag:n="latest",requireCanonical:o,requests:s}){let i=ni({blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o});return e.request({method:"eth_getStorageValues",params:[s,i]})}var Ole=b(()=>{l();B0()});async function cm(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:s,sender:i,nonce:a}){let c=n||"latest",u=r!==void 0?oe(r):void 0,d=null;if(o?d=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0}):t?d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,oe(s)]},{dedupe:!0}):(u||c)&&typeof s=="number"?d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,oe(s)]},{dedupe:!!u}):i&&typeof a=="number"&&(d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[i,oe(a)]},{dedupe:!0})),!d)throw new Gc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:s});return(e.chain?.formatters?.transaction?.format||jf)(d,"getTransaction")}var YT=b(()=>{l();zn();qe();Ab()});async function Ble(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([ue(e,Ta,"getBlockNumber")({}),t?ue(e,cm,"getTransaction")({hash:t}):void 0]),s=r?.blockNumber||o?.blockNumber;if(!s)return 0n;let i=n{l();_t();zg();YT()});async function lm(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new nu({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||op)(r,"getTransactionReceipt")}var LM=b(()=>{l();zn();Qb()});async function Ule(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,requireCanonical:u,stateOverride:d}=t,f=t.contracts,p=typeof e.batch?.multicall=="object"?e.batch.multicall:{},h=t.batchSize??p.batchSize??1024,y=t.deployless??p.deployless??!1,w=(()=>{if(t.multicallAddress)return t.multicallAddress;if(y)return null;if(e.chain)return Ui({blockNumber:i,chain:e.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),x=[[]],v=0,T=0;for(let D=0;D0&&T>h&&x[v].length>0&&(v++,T=(R.length-2)/2,x[v]=[]),x[v]=[...x[v],{allowFailure:!0,callData:R,target:N}]}catch(R){let I=Js(R,{abi:M,address:N,args:L,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!o)throw I;x[v]=[...x[v],{allowFailure:!0,callData:"0x",target:N}]}}let E=!!e.batch?.multicall,S=E?x.flatMap(D=>D.map(M=>[M])):x,_=await Promise.allSettled(S.map(D=>E?AMe(e,{account:r,authorizationList:n,batchSize:h,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,call:D[0],multicallAddress:w,requireCanonical:u,stateOverride:d}).then(M=>[M]):ue(e,er,"readContract")({...w===null?{code:Mg}:{address:w},abi:ki,account:r,args:[D],authorizationList:n,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:u,stateOverride:d}))),O=[];for(let D=0;D<_.length;D++){let M=_[D];if(M.status==="rejected"){if(!o)throw M.reason;for(let L=0;Lf+(p.length-2)/2,0)>r},fn:u=>ue(e,er,"readContract")({...o===null?{code:Mg}:{address:o},...s,abi:ki,args:[u],functionName:"aggregate3"})}),[c]=await a(n);return c}var Dle=b(()=>{l();So();Vb();Qr();nt();ou();lc();us();K0();p0();_t();h3();so();oi()});async function w6(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:s,traceTransfers:i,validation:a}=t;try{let c=[];for(let p of o){let h=p.blockOverrides?w9(p.blockOverrides):void 0,y=p.calls.map(x=>{let v=x,T=v.account?ft(v.account):void 0,E=v.abi?Wt(v):v.data,S={...v,account:T,data:v.dataSuffix?en([E||"0x",v.dataSuffix]):E,from:v.from??T?.address};return jn(S),Bn(S)}),w=p.stateOverrides?xb(p.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:w})}let d=(typeof r=="bigint"?oe(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:i,validation:a},d]})).map((p,h)=>({...qf(p),calls:p.calls.map((y,w)=>{let{abi:x,args:v,functionName:T,to:E}=o[h].calls[w],S=y.error?.data??y.returnData,_=BigInt(y.gasUsed),O=y.maxUsedGas===void 0?void 0:BigInt(y.maxUsedGas),D=y.logs?.map(P=>qn(P)),M=y.status==="0x1"?"success":"failure",N=x&&M==="success"&&S!=="0x"?dn({abi:x,data:S,functionName:T}):null,L=(()=>{if(M==="success")return;let P;if(S==="0x"?P=new Ci:S&&(P=new sc({data:S})),!!P)return Js(P,{abi:x??[],address:E??"0x",args:v,functionName:T??""})})();return{data:S,gasUsed:_,logs:D,...O===void 0?{}:{maxUsedGas:O},status:M,...M==="success"?{result:N}:{error:L}}})}))}catch(c){let u=c,d=_0(u,{});throw d instanceof Ni?u:d}}var MM=b(()=>{l();uL();tn();Qr();ou();tl();lc();us();Fn();qe();p0();G4();X4();hu();rl();VI();nl()});function XT(e){let t=!0,r="",n=0,o="",s=!1;for(let i=0;ir==="object"&&JT(Lle(e,i,a),i));let o=CMe.exec(n);if(o){if(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&!Number.isInteger(e))return!1;let i=n.startsWith("int"),a=Number.parseInt(o[1]??"256",10),c=2n**(BigInt(a)-(i?1n:0n))-1n,u=i?-c-1n:0n;return e>=u&&e<=c}if(SMe.test(n)){if(typeof e!="string"&&!(e instanceof Uint8Array))return!1;let i=n.slice(5);return i?e instanceof Uint8Array?e.length===Number.parseInt(i,10):q0(e)?Mr(e)===Number.parseInt(i,10):!1:e instanceof Uint8Array||q0(e)}let s=Qg(n);if(s){let[i,a]=s;return Array.isArray(e)&&(i===null||e.length===i)&&e.every(c=>JT(c,{...t,type:a}))}return!1}}}function QT(e,t,r){for(let n in e){let o=e[n],s=t[n];if(!s)continue;if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s){let f=r[n],p=QT(o.components,s.components,o.components.map((h,y)=>Lle(f,h,y)));if(p)return p;continue}let i=Qg(o.type),a=Qg(s.type);if(i&&a){let f=QT([{...o,type:i[1]}],[{...s,type:a[1]}],[r[n]?.[0]]);if(f)return f;if(i[1]===a[1]&&o.type!==s.type)return[o.type,s.type];continue}let c=[o.type,s.type],u=r[n];if(c.includes("address")&&(c.includes("string")||c.includes("bytes"))?u===void 0||lM(u,{strict:!1}):o.type!==s.type)return c}}function Lle(e,t,r){return Array.isArray(e)?e[r]:e?.[t.name]}var CMe,SMe,Mle=b(()=>{l();B3();Bi();io();pM();CMe=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,SMe=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/});function b6(e,t={}){let{prepare:r=!0}=t,n=Array.isArray(e)?Tw(e):typeof e=="string"?Tw(e):e;return{...n,...r?{hash:ey(n)}:{}}}function x6(e,t,r){let{args:n=[],prepare:o=!0}=r??{},s=q0(t,{strict:!1}),i=e.filter(d=>s?d.type==="function"||d.type==="error"?$M(d)===rn(t,0,4):d.type==="event"?ey(d)===t:!1:"name"in d&&d.name===t);if(i.length===0)throw new sp({name:t});if(i.length===1)return{...i[0],...o?{hash:ey(i[0])}:{}};let a,c;for(let d of i){if(!("inputs"in d))continue;if(!n||n.length===0){!c&&(!d.inputs||d.inputs.length===0)&&(c=d);continue}if(!d.inputs||d.inputs.length===0||d.inputs.length!==n.length)continue;if(n.every((p,h)=>{let y="inputs"in d&&d.inputs[h];return y?JT(p,y):!1})){if(a&&"inputs"in a&&a.inputs){let p=QT(d.inputs,a.inputs,n);if(p)throw new HM({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let u=(()=>{if(a)return a;let d=c??i[0],f=i.filter(p=>p!==d);return{...d,overloads:f}})();if(!u)throw new sp({name:t});return{...u,...o?{hash:ey(u)}:{}}}function $M(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return x6(r,n)}return e[0]})();return rn(ey(t),0,4)}function TMe(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return x6(n,o)}return e[0]})(),r=typeof t=="string"?t:Af(t);return XT(r)}function ey(...e){let t=(()=>{if(Array.isArray(e[0])){let[s,i]=e;return x6(s,i)}return e[0]})();if(typeof t!="string"&&"hash"in t&&t.hash)return t.hash;let r=TMe(t),n=R3.signatureHash.get(r);if(n)return n;let o=Gg($b(r));return R3.signatureHash.set(r,o),o}var HM,sp,e_=b(()=>{l();fg();Bi();_T();io();Mle();eM();HM=class extends Ke{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${XT(Af(t.abiItem))}\`, and`,`\`${r.type}\` in \`${XT(Af(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}},sp=class extends Ke{constructor({name:t,data:r,type:n="item"}){let o=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${o} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}});function Hle(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[s,i]=e;return[_Me(s),i]}return e})(),{bytecode:n,args:o}=r;return fn(n,t.inputs?.length&&o?.length?am(t.inputs,o):"0x")}function $le(e){return b6(e)}function _Me(e){let t=e.find(r=>r.type==="constructor");if(!t)throw new sp({name:"constructor"});return t}var Fle=b(()=>{l();e_();y6();io()});function zle(e,t={}){return b6(e,t)}function Vle(e){return ey(e)}var jle=b(()=>{l();e_()});function qle(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[s,i,a,c]=e;return[zM(s,i),a,c]}return e})(),o=Xg(t.outputs,r,n);if(!(o&&Object.keys(o).length===0))return o&&Object.keys(o).length===1?Array.isArray(o)?o[0]:Object.values(o)[0]:o}function um(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[u,d,f]=e;return[zM(u,d,{args:f}),f]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?zM([t,...n],t.name,{args:r}):t,s=RMe(o),i=r.length>0?am(o.inputs,r):void 0;return i?fn(s,i):s}function ty(e,t={}){return b6(e,t)}function zM(e,t,r){let n=x6(e,t,r);if(n.type!=="function")throw new sp({name:t,type:"function"});return n}function RMe(e){return $M(e)}var Wle=b(()=>{l();e_();y6();io()});var v6,dm,t_=b(()=>{l();v6="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",dm="0x0000000000000000000000000000000000000000"});async function eue(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:s,traceAssetChanges:i,traceTransfers:a,validation:c}=t,u=t.account?ft(t.account):void 0;if(i&&!u)throw new G("`account` is required when `traceAssetChanges` is true");let d=u?Hle($le("constructor(bytes, bytes)"),{bytecode:zb,args:[BMe,um(ty("function getBalance(address)"),[u.address])]}):void 0,f=n??e.experimental_blockTag??"latest",p=r;if(i&&typeof p!="bigint"&&f!=="earliest"&&f!=="pending")if(f==="latest")p=await Ta(e,{cacheTime:0});else{let W=await xn(e,{blockTag:f});if(typeof W.number!="bigint")throw new G(`Block tag \`${f}\` did not resolve to a number.`);p=W.number}let h=typeof p=="bigint"?{blockNumber:p}:{blockTag:f},y=i?await w6(e,{...h,blocks:[{calls:o.map(W=>({...W,from:u.address})),stateOverrides:s}],traceTransfers:a,validation:c}):void 0,w=y?[...new Set([...LMe(y[0].calls.flatMap(W=>W.logs??[]),u.address),...t.calls.map(W=>W.to?.toLowerCase())])].filter(W=>!!W&&W!==v6&&W!==dm):[],x=MMe([...u?[u.address]:[],...w,...s?.map(({address:W})=>W)??[]]),v=[{address:x,code:Xle}],[T,E]=await Promise.all([i?Promise.all([Qle(e,{account:u.address,...h,data:d,stateOverride:s}),...w.map(W=>Qle(e,{account:u.address,address:W,...h,data:um(Kle,[u.address]),staticCallAddress:x,stateOverride:s}))]):[],w6(e,{...h,blocks:[{calls:[...o,{to:dm}].map(W=>({...W,from:u?.address})),stateOverrides:s},...i?[{calls:[{data:d}]},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Kle,[u.address]))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Zle))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Gle,[0n]))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Yle))})),stateOverrides:v}]:[]],traceTransfers:a,validation:c})]),S=E[0],[_,O,D,M,N]=i?E.slice(1):[],{calls:L,...P}=S,R=L.slice(0,-1),I=T.map(W=>Jle(W)?dt(W.data):null),B=_?.calls??[],C=O?.calls??[],U=[...B,...C].map(W=>Jle(W)?dt(W.data):null),H=(D?.calls??[]).map(W=>VM(W,Zle)),k=(N?.calls??[]).map(W=>VM(W,Yle)),F=(M?.calls??[]).map(W=>VM(W,Gle)),j=[];for(let[W,ae]of U.entries()){let te=I[W],X=T[W],pe=typeof te=="bigint"?te:W>0&&X?.status==="success"&&X.data==="0x"?0n:null;if(typeof ae!="bigint"||typeof pe!="bigint")continue;let me=H[W-1],Ne=k[W-1],ye=F[W-1],Re=W===0?{address:v6,decimals:18,symbol:"ETH"}:{address:w[W-1],decimals:ye||me?Number(me??1):void 0,symbol:Ne??void 0};j.push({token:Re,value:{pre:pe,post:ae,diff:ae-pe}})}return{assetChanges:j,block:P,results:R}}function j3(e,t){return um(DMe,[e,t])}function LMe(e,t){let r=Zr(t.toLowerCase(),{size:32});return e.filter(n=>n.topics[0]?.toLowerCase()!==UMe||n.address.toLowerCase()===v6?!1:n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r).map(n=>n.address.toLowerCase())}function Jle(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function VM(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return qle(t,e.data)}catch{return null}}async function Qle(e,t){let{account:r,address:n,blockNumber:o,blockTag:s,data:i,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await ms({...e,ccipRead:!1},{account:n?dm:r,data:n?j3(n,i):i,stateOverride:n&&a?[...c??[],{address:a,code:Xle}]:c,...n?{gas:V3,to:a}:{},...typeof o=="bigint"?{blockNumber:o}:{blockTag:s}})).data??"0x",status:"success"}}catch(u){if(!(u instanceof Yc)||!(u.cause instanceof ri))throw u;return{data:"0x",status:"failure"}}}function MMe(e){let t=new Set(e.map(n=>n.toLowerCase())),r=kMe;for(;t.has(`0x${r.toString(16).padStart(40,"0")}`);)r++;return`0x${r.toString(16).padStart(40,"0")}`}var BMe,Xle,V3,kMe,UMe,Kle,Zle,Gle,Yle,DMe,tue=b(()=>{l();Fle();jle();Wle();tn();t_();Vb();nt();ou();tl();Xa();Xr();G0();fu();zg();MM();BMe="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",Xle="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",V3=1000000n,kMe=0x00000000000000000000000000000000deadbeefn,UMe=Vle(zle("event Transfer(address indexed from, address indexed to, uint256 value)")),Kle=ty("function balanceOf(address) returns (uint256)"),Zle=ty("function decimals() returns (uint256)"),Gle=ty("function tokenURI(uint256) returns (string)"),Yle=ty("function symbol() returns (string)"),DMe=ty("function query(address target, bytes data)")});var q3={};Te(q3,{InvalidWrappedSignatureError:()=>r_,assert:()=>qM,from:()=>FMe,magicBytes:()=>jM,universalSignatureValidatorAbi:()=>$Me,universalSignatureValidatorBytecode:()=>HMe,unwrap:()=>rue,validate:()=>VMe,wrap:()=>zMe});function qM(e){if(rn(e,-32)!==jM)throw new r_(e)}function FMe(e){return typeof e=="string"?rue(e):e}function rue(e){qM(e);let[t,r,n]=Xg(D3("address, bytes, bytes"),e);return{data:r,signature:n,to:t}}function zMe(e){let{data:t,signature:r,to:n}=e;return fn(am(D3("address, bytes, bytes"),[n,t,r]),jM)}function VMe(e){try{return qM(e),!0}catch{return!1}}var jM,HMe,$Me,r_,nue=b(()=>{l();y6();Bi();io();jM="0x6492649264926492649264926492649264926492649264926492649264926492",HMe="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",$Me=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];r_=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}});var oue=b(()=>{l();nue()});function W3({r:e,s:t,to:r="hex",v:n,yParity:o}){let s=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),i=`0x${new ei.Signature(dt(e),dt(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?i:qt(i)}var WM=b(()=>{l();Bg();Xr();Pr()});async function fm(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:s=t.universalSignatureVerifierAddress??(()=>{let{blockNumber:u}=t,d=n?.contracts?.erc6492Verifier;if(!(u!==void 0&&d?.blockCreated&&d.blockCreated>u))return d?.address})(),multicallAddress:i=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(r===dm)return!1;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let u=t.signature;return We(u)?u:typeof u=="object"&&"r"in u&&"s"in u?W3(u):yt(u)})();try{if(a==="eoa")try{if(xr(Gr(r),await ti({hash:o,signature:c})))return!0}catch{}return il.validate(c)?await jMe(e,{...t,multicallAddress:i,signature:c}):await qMe(e,{...t,verifierAddress:s,signature:c})}catch(u){if(a!=="eoa")try{if(xr(Gr(r),await ti({hash:o,signature:c})))return!0}catch{}if(u instanceof vu)return!1;throw u}}async function jMe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:s,hash:i,multicallAddress:a,requireCanonical:c}=t,{authorization:u,data:d,signature:f,to:p}=il.unwrap(t.signature);if(await jg(e,{address:r,blockHash:n,blockNumber:o,blockTag:s,requireCanonical:c})===fr(["0xef0100",u.address]))return await WMe(e,{...t,signature:f});let y={address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce),r:oe(u.r,{size:32}),s:oe(u.s,{size:32}),yParity:u.yParity};if(!await Oae({address:r,authorization:y}))throw new vu;let{data:x}=await ms({...e,ccipRead:!1},{...a?{to:a}:{code:Mg},authorizationList:[y],blockHash:n,blockNumber:o,blockTag:s??"pending",data:Wt({abi:ki,functionName:"aggregate3",args:[[...d?[{allowFailure:!0,target:p??r,callData:d}]:[],{allowFailure:!0,target:r,callData:Wt({abi:x9,functionName:"isValidSignature",args:[i,f]})}]]}),requireCanonical:c}),v=dn({abi:ki,functionName:"aggregate3",data:x??"0x"}),T=v[v.length-1];if(T?.success&&T.returnData.startsWith("0x1626ba7e"))return!0;throw new vu}async function qMe(e,t){let{address:r,factory:n,factoryData:o,hash:s,signature:i,verifierAddress:a,...c}=t,u=await(async()=>!n&&!o||q3.validate(i)?i:q3.wrap({data:o,signature:i,to:n}))(),d=a?{batch:!1,to:a,data:Wt({abi:Fb,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:tp({abi:Fb,args:[r,s,u],bytecode:f3}),...c},{data:f}=await ms({...e,ccipRead:!1},d).catch(p=>{throw p instanceof Yc?new vu:p});if(qw(f??"0x0"))return!0;throw new vu}async function WMe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:s,hash:i,requireCanonical:a,signature:c}=t,{data:u}=await ms({...e,ccipRead:!1},{batch:!1,blockHash:n,blockNumber:o,blockTag:s,data:Wt({abi:x9,functionName:"isValidSignature",args:[i,c]}),requireCanonical:a,to:r}).catch(f=>{throw f instanceof Yc?new vu:f});if((()=>{try{return dn({abi:x9,functionName:"isValidSignature",data:u??"0x"})}catch{throw new vu}})().startsWith("0x1626ba7e"))return!0;throw new vu}var vu,K3=b(()=>{l();oue();$3();So();t_();Vb();ou();lc();p3();us();Zs();Oi();Bae();Fn();qs();Xr();qe();w0();WM();G0();aT();vu=class extends Error{}});async function sue(e,{address:t,message:r,factory:n,factoryData:o,signature:s,...i}){let a=im(r);return ue(e,fm,"verifyHash")({address:t,factory:n,factoryData:o,hash:a,signature:s,...i})}var iue=b(()=>{l();_t();T3();K3()});async function aue(e,t){let{address:r,factory:n,factoryData:o,signature:s,message:i,primaryType:a,types:c,domain:u,...d}=t,f=p6({message:i,primaryType:a,types:c,domain:u});return ue(e,fm,"verifyHash")({address:r,factory:n,factoryData:o,hash:f,signature:s,...d})}var cue=b(()=>{l();_t();P3();K3()});function n_(e,{emitOnBegin:t=!1,emitMissed:r,onBlockNumber:n,onError:o,poll:s,pollingInterval:i=e.pollingInterval}){let a=typeof s<"u"?s:Q0(e),c=e.chain?.blockTime,u=r??(c!==void 0&&i>c/2),d;return a?(()=>{let h=bt(["watchBlockNumber",e.uid,t,u,i]);return Io(h,{onBlockNumber:n,onError:o},y=>dc(async()=>{try{let w=await ue(e,Ta,"getBlockNumber")({cacheTime:0});if(d!==void 0){if(w===d)return;if(w-d>1&&u)for(let x=d+1n;xd)&&(y.onBlockNumber(w,d),d=w)}catch(w){y.onError?.(w)}},{emitOnBegin:t,interval:i}))})():(()=>{let h=bt(["watchBlockNumber",e.uid,t,u]);return Io(h,{onBlockNumber:n,onError:o},y=>{let w=!0,x=()=>w=!1;return(async()=>{try{let v=gu(e),{unsubscribe:T}=await v.subscribe({params:["newHeads"],onData(E){if(!w)return;let S=dt(E.result?.number);y.onBlockNumber(S,d),d=S},onError(E){y.onError?.(E)}});x=T,w||x()}catch(v){o?.(v)}})(),()=>x()})})()}var KM=b(()=>{l();Xr();_t();rp();Fg();so();zg();Zb()});async function Z3(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:s,retryCount:i=6,retryDelay:a=({count:L})=>~~(1<e.chain?.transactionReplacement?.getKey?.(L)??String(L.nonce),p=t.pollingInterval?t.pollingInterval:e.chain?.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval,h=bt(["waitForTransactionReceipt",e.uid,o,{checkReplacement:r,confirmations:n,pollingInterval:p,replacement:d,retryCount:i,signal:c?rm():void 0,timeout:u}]),y,w,x,v=!1,T,E,S,{promise:_,resolve:O,reject:D}=jb(),M=u?setTimeout(()=>{S?.(),E?.(),T=void 0,D(new Gh({hash:o}))},u):void 0,N=()=>{clearTimeout(M),S?.(),E?.(),D(Nn(c))};return c?.addEventListener("abort",N,{once:!0}),E=Io(h,{onReplaced:s,resolve:O,reject:D},async L=>{if(w=await ue(e,lm,"getTransactionReceipt")({hash:o}).catch(()=>{}),c?.aborted)return;if(w&&n<=1){clearTimeout(M),L.resolve(w),E?.();return}let P=async R=>{let I=C=>{T=void 0,clearTimeout(M),S?.(),C(),E?.()},B=R;try{if(w){if(n>1&&(!w.blockNumber||B-w.blockNumber+1nU instanceof nu?null:void 0);if(C===void 0)return;if(!C){w=void 0,x||(y=void 0),x=void 0;return}if(w=C,n>1&&(!C.blockNumber||B-C.blockNumber+1n{A&&L.onReplaced?.(A),L.resolve(C)});return}if(r&&!y&&(v=!0,await np(async()=>{y=await ue(e,cm,"getTransaction")({hash:o}),y.blockNumber&&(B=y.blockNumber)},{delay:a,retryCount:i,signal:c,shouldRetry:({error:C})=>!(d&&C instanceof Gc)}),v=!1),w=await ue(e,lm,"getTransactionReceipt")({hash:o}),n>1&&(!w.blockNumber||B-w.blockNumber+1nL.resolve(w))}catch(C){if(C instanceof Gc||C instanceof nu){v=!1;let A=y??(r&&d?{...d,hash:o.toLowerCase()}:void 0);if(!A||A.blockNumber)return;try{if(!y){v=!0;let F=await ue(e,cm,"getTransaction")({nonce:A.nonce,sender:A.from}).catch(j=>{(j instanceof Jc||j instanceof Aa)&&(y=A)});if(v=!1,F?.hash.toLowerCase()===A.hash){y=F;return}if(F){let j=await ue(e,lm,"getTransactionReceipt")({hash:F.hash}).catch(W=>{if(!(W instanceof nu))throw W});if(!j||(w=j,x={reason:e.chain?.transactionReplacement?.getReason?.({replaced:A,replacement:F})??lue(A,F),replacedTransaction:A,transaction:F,transactionReceipt:w},n>1&&(!w.blockNumber||B-w.blockNumber+1n{L.onReplaced?.(x),L.resolve(w)});return}}v=!0;let U=await np(()=>ue(e,xn,"getBlock")({blockNumber:B,includeTransactions:!0}),{delay:a,retryCount:i,signal:c,shouldRetry:({error:F})=>F instanceof du});v=!1;let H=f(A),k=U.transactions.find(F=>xr(F.from,A.from)&&F.hash!==A.hash&&f(F)===H);if(!k||(w=await ue(e,lm,"getTransactionReceipt")({hash:k.hash}),x={reason:e.chain?.transactionReplacement?.getReason?.({replaced:A,replacement:k})??lue(A,k),replacedTransaction:A,transaction:k,transactionReceipt:w},n>1&&(!w.blockNumber||B-w.blockNumber+1n{L.onReplaced?.(x),L.resolve(w)})}catch(U){I(()=>L.reject(U))}}else I(()=>L.reject(C))}};S=ue(e,n_,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:p,async onBlockNumber(R){for(T=R;T!==void 0&&!v;){let I=T;T=void 0,await P(I)}}})}),_.finally(()=>{c?.removeEventListener("abort",N),clearTimeout(M),E?.()})}function lue(e,t){return(t.to&&e.to?xr(t.to,e.to):t.to===e.to)&&t.value===e.value&&t.input===e.input?"repriced":t.from===t.to&&t.value===0n?"cancelled":"replaced"}var ZM=b(()=>{l();J4();Lf();zn();oc();Oi();_t();rp();A9();v3();so();A3();fu();YT();LM();KM()});function uue(e,{onBlockHeader:t,onError:r}){let n,o=bt(["watchBlockHeaders",e.uid]);return Io(o,{onBlockHeader:t,onError:r},s=>{let i=!0,a=!1,c=()=>i=!1;return(async()=>{try{let u=gu(e),{unsubscribe:d}=await u.subscribe({params:["newHeads"],onData(f){if(!i)return;let p=(e.chain?.formatters?.block?.format||qf)(f.result,"watchBlockHeaders");for(let h of KMe)delete p[h];s.onBlockHeader(p,n),n=p},onError(f){a&&s.onError?.(f)}});a=!0,c=d,i||c()}catch(u){s.onError?.(u)}})(),()=>c()})}var KMe,due=b(()=>{l();X4();rp();so();Zb();KMe=["size","totalDifficulty","transactions","uncles","withdrawals"]});function fue(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r,emitOnBegin:n=!1,onBlock:o,onError:s,includeTransactions:i,poll:a,pollingInterval:c=e.pollingInterval}){let u=typeof a<"u"?a:Q0(e),d=i??!1,f=e.chain?.blockTime,p=r??((t==="latest"||t==="pending")&&f!==void 0&&c>f/2),h=r===void 0?100:Number.POSITIVE_INFINITY,y;return u?(()=>{let v=bt(["watchBlocks",e.uid,t,p,n,d,h,c]);return Io(v,{onBlock:o,onError:s},T=>dc(async()=>{try{let E=await ue(e,xn,"getBlock")({blockTag:t,includeTransactions:d});if(E.number!==null&&y?.number!=null){if(E.number===y.number)return;let S=Number(E.number-y.number)-1;if(S>0&&S<=h&&p){let O=y.number+1n;for(let D=0;Due(e,xn,"getBlock")({blockNumber:O+BigInt(D+L),includeTransactions:d})));for(let N of M)T.onBlock(N,y),y=N}}}(y?.number==null||t==="pending"&&E?.number==null||E.number!==null&&E.number>y.number)&&(T.onBlock(E,y),y=E)}catch(E){T.onError?.(E)}},{emitOnBegin:n,interval:c}))})():(()=>{let v=!0,T=!0,E=()=>v=!1;return(async()=>{try{n&&ue(e,xn,"getBlock")({blockTag:t,includeTransactions:d}).then(O=>{v&&T&&(o(O,void 0),T=!1)}).catch(s);let S=gu(e),{unsubscribe:_}=await S.subscribe({params:["newHeads"],async onData(O){if(!v)return;let D=await ue(e,xn,"getBlock")({blockNumber:O.result?.number,includeTransactions:d}).catch(()=>{});v&&(o(D,y),T=!1,y=D)},onError(O){s?.(O)}});E=_,v||E()}catch(S){s?.(S)}})(),()=>E()})()}var pue=b(()=>{l();_t();rp();Fg();so();fu();Zb()});function hue(e,{address:t,args:r,batch:n=!0,event:o,events:s,fromBlock:i,onError:a,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:f}){let p=typeof u<"u"?u:typeof i=="bigint"?!0:Q0(e),h=f??!1;return p?(()=>{let x=bt(["watchEvent",t,r,n,e.uid,o,s,d,h,i]);return Io(x,{onLogs:c,onError:a},v=>{let T=!0,E=i===void 0?void 0:i-1n,S,_=!1,O=N=>{if(N.length!==0)if(n)v.onLogs(N);else for(let L of N)v.onLogs([L])},D=(N,L)=>ue(e,F0,"getLogs")({address:t,args:r,event:o,events:s,fromBlock:N,strict:h,toBlock:L}),M=dc(async()=>{if(!_){try{S=await ue(e,sT,"createEventFilter")({address:t,args:r,event:o,events:s,strict:h,fromBlock:i})}catch{}if(_=!0,S)return}try{if(S){let P=await ue(e,J0,"getFilterChanges")({filter:S});O(P);return}let N=await ue(e,Ta,"getBlockNumber")({});E??=N;let L=N-E;for(;E{if(P===I||!Bb(C))throw C});if(!T)return;if(!B){L=(I-P+1n)/2n;continue}E=I,O(B)}}catch(N){S&&N instanceof Ti&&(_=!1),v.onError?.(N)}},{emitOnBegin:!0,interval:d});return async()=>{T=!1,S&&await ue(e,X0,"uninstallFilter")({filter:S}),M()}})})():(()=>{let x=!0,v=()=>x=!1;return(async()=>{try{let T=gu(e),E=s??(o?[o]:void 0),S=[];E&&(S=[E.flatMap(D=>nc({abi:[D],eventName:D.name,args:r}))],o&&(S=S[0]));let{unsubscribe:_}=await T.subscribe({params:["logs",{address:t,topics:S}],onData(O){if(!x)return;let D=O.result;try{let{eventName:M,args:N}=Yf({abi:E??[],data:D.data,topics:D.topics,strict:h}),L=qn(D,{args:N,eventName:M});c([L])}catch(M){if((E||f)&&(M instanceof Gf||M instanceof Yl||M instanceof Jl))return;let N,L;if(M instanceof jc||M instanceof Ql){if(f)return;N=M.abiItem.name,L=M.abiItem.inputs?.some(R=>!("name"in R&&R.name))}let P=qn(D,{args:L?[]:{},eventName:N});c([P])}},onError(O){a?.(O)}});v=_,x||v()}catch(T){a?.(T)}})(),()=>v()})()}var mue=b(()=>{l();Qr();Lf();a3();Cg();hu();_t();rp();Fg();so();$L();zg();y3();c3();n9();Zb();w3()});function gue(e,{batch:t=!0,onError:r,onTransactions:n,poll:o,pollingInterval:s=e.pollingInterval}){return(typeof o<"u"?o:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let u=bt(["watchPendingTransactions",e.uid,t,s]);return Io(u,{onTransactions:n,onError:r},d=>{let f,p=dc(async()=>{try{if(!f)try{f=await ue(e,iT,"createPendingTransactionFilter")({});return}catch(y){throw p(),y}let h=await ue(e,J0,"getFilterChanges")({filter:f});if(h.length===0)return;if(t)d.onTransactions(h);else for(let y of h)d.onTransactions([y])}catch(h){d.onError?.(h)}},{emitOnBegin:!0,interval:s});return async()=>{f&&await ue(e,X0,"uninstallFilter")({filter:f}),p()}})})():(()=>{let u=!0,d=()=>u=!1;return(async()=>{try{let{unsubscribe:f}=await e.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;let h=p.result;n([h])},onError(p){r?.(p)}});d=f,u||d()}catch(f){r?.(f)}})(),()=>d()})()}var yue=b(()=>{l();_t();rp();Fg();so();FL();y3();w3()});function GMe(e){return ZMe.test(e)?!Number.isNaN(new Date(e).getTime()):!1}function GM(e){return GMe(e)?new Date(e):new Date(Number.NaN)}function wue(e){let{scheme:t,statement:r,...n}=e.match(YMe)?.groups??{},{chainId:o,expirationTime:s,issuedAt:i,notBefore:a,requestId:c,resources:u,...d}=e.match(JMe)?.groups??{},f=u?.split(` +- `).slice(1);return{...n,...d,...o?{chainId:Number(o)}:{},...s?{expirationTime:GM(s)}:{},...i?{issuedAt:GM(i)}:{},...a?{notBefore:GM(a)}:{},...c?{requestId:c}:{},...f?{resources:f}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var ZMe,YMe,JMe,bue=b(()=>{l();ZMe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;YMe=/^(?:(?[a-zA-Z][a-zA-Z0-9+\-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,JMe=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.*))?(?:\nResources:(?(?:\n- .+)*))?/});function xue(e){let{address:t,domain:r,message:n,nonce:o,scheme:s,time:i=new Date}=e;if(r&&n.domain!==r||o&&n.nonce!==o||s&&n.scheme!==s||n.nonce!==void 0&&!QMe.test(n.nonce)||n.version!==void 0&&n.version!=="1"||Number.isNaN(i.getTime())||n.expirationTime&&(Number.isNaN(n.expirationTime.getTime())||i>=n.expirationTime)||n.notBefore&&(Number.isNaN(n.notBefore.getTime())||i{l();Gs();Oi();QMe=/^[a-zA-Z0-9]{8,}$/});async function Eue(e,t){let{address:r,domain:n,message:o,nonce:s,scheme:i,signature:a,time:c=new Date,...u}=t,d=wue(o);if(!d.address||!xue({address:r,domain:n,message:d,nonce:s,scheme:i,time:c}))return!1;let p=im(o);return fm(e,{address:d.address,hash:p,signature:a,...u})}var Aue=b(()=>{l();T3();bue();vue();K3()});function E6(e,t){return{amount:e,decimals:t,formatted:pc(e,t)}}function o_(e,t){if(typeof e=="bigint")return e;let r=e.decimals??t;return GT(e.formatted,XMe(r))}function XMe(e){if(e===void 0)throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function s_(e,t){return typeof e=="bigint"?t:e.decimals??t}function jo(e,t){let{decimals:r,token:n}=t,o=JM(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(Ft(n,{strict:!1}))return{address:n,decimals:r??tHe(e,n)};throw new Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function JM(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=eHe(r,t);if(o)return YM(o,n);if(Ft(t,{strict:!1}))for(let s of r){let i=YM(s,n);if(i&&xr(i.address,t))return i}}function YM(e,t){if(e.addresses[t])return e(t)}function eHe(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n}function tHe(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let s=YM(o,n);if(s&&xr(s.address,t))return s.decimals}}async function A6(e,t){let{address:r,decimals:n}=jo(e,t);return n!==void 0?{address:r,decimals:n}:{address:r,decimals:await er(e,{abi:Hr,address:r,functionName:"decimals"})}}function C6(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:s,nonce:i}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:s,nonce:i}}function Eu(e){return{...e,data:Wt(e),to:e.address}}var ip=b(()=>{l();So();Gs();Oi();DM();z3();UM();oi()});async function ap(e,t){return ap.inner(_a,e,t)}function rHe(e,t){let{amount:r,spender:n,token:o}=t,{address:s,decimals:i}=jo(e,{token:o});return{abi:Hr,address:s,args:[n,o_(r,i)],functionName:"approve"}}var QM=b(()=>{l();So();Dg();i3();g3();Yb();ip();(function(e){async function t(i,a,c){return await i(a,{...c,...e.call(a,c)})}e.inner=t;function r(i,a){return Eu(rHe(i,a))}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:r,writable:!0});async function n(i,a){return $0(i,{...C6(a),...e.call(i,a)})}e.estimateGas=n;async function o(i,a){return Y0(i,{...C6(a),...e.call(i,a)})}e.simulate=o;function s(i){let[a]=cc({abi:Hr,logs:i,eventName:"Approval",strict:!0});if(!a)throw new Error("`Approval` event not found.");return a}e.extractEvent=s})(ap||(ap={}))});async function S6(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),i=(e.chain?.formatters?.transactionReceipt?.format||op)(o);if(i.status==="reverted"&&r)throw new Zh({receipt:i});return i}var i_=b(()=>{l();zn();Qb()});async function a_(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:s,authorizationList:i,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,pollingInterval:x,throwOnReceiptRevert:v,type:T,value:E,...S}=t,_=t.timeout??Math.max((o?.blockTime??0)*3,5e3);if(typeof r>"u")throw new kn({docsPath:"/docs/actions/wallet/sendTransactionSync"});let O=r?ft(r):null,D;try{jn(t);let M=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await b0({authorization:i[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if(O?.type==="json-rpc"||O===null){let N;o!==null&&(N=await ue(e,hs,"getChainId")({}),n&&em({currentChainId:N,chain:o}));let L=e.chain?.formatters?.transactionRequest?.format,R=(L||Bn)({...Ri(S,{format:L}),accessList:s,account:O,authorizationList:i,blobs:a,chainId:N,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,to:M,type:T,value:E},"sendTransaction"),I=XM.get(e.uid),B=I?"wallet_sendTransaction":"eth_sendTransaction",C=await(async()=>{try{return await e.request({method:B,params:[R]},{retryCount:0})}catch(U){if(I===!1)throw U;let H=U;if(H.name==="InvalidInputRpcError"||H.name==="InvalidParamsRpcError"||H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[R]},{retryCount:0}).then(k=>(XM.set(e.uid,!0),k)).catch(k=>{let F=k;throw F.name==="MethodNotFoundRpcError"||F.name==="MethodNotSupportedRpcError"?(XM.set(e.uid,!1),H):F});throw H}})(),A=await ue(e,Z3,"waitForTransactionReceipt")({checkReplacement:!1,hash:C,pollingInterval:x,timeout:_});if(v&&A.status==="reverted")throw new Zh({receipt:A});return A}if(O?.type==="local"){let N=(()=>{if(!O.nonceManager||typeof w<"u")return O.nonceManager;let A=O.nonceManager;return{async consume(U){D={address:U.address,chainId:U.chainId};let H=await A.consume(U);return D={...D,nonce:H},H},get(U){return A.get(U)},increment(U){return A.increment(U)},reset(U){return A.reset(U)}}})(),L=await ue(e,pu,"prepareTransactionRequest")({account:O,accessList:s,authorizationList:i,blobs:a,chain:o,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,nonceManager:N,parameters:[...s3,"sidecars"],type:T,value:E,...S,to:M}),P=o?.serializers?.transaction,R=await O.signTransaction(L,{serializer:P}),I=(o??e.chain)?.serializers?.transactionEnvelope,B=I?await I({serializedTransaction:R,transaction:L}):R,C=Date.now();try{return await ue(e,S6,"sendRawTransactionSync")({serializedTransaction:B,throwOnReceiptRevert:v,timeout:t.timeout})}catch(A){let U=A instanceof G?A.walk(j=>j?.code===4):null;if(!U)throw A;D=void 0;let H=(()=>{let{data:j}=U;if(typeof j=="string"&&i6(j))return j;if(xa(B,0,1)==="0x03"){let W=Wg(xa(B,1));if(W.length===4&&Array.isArray(W[0]))return Pt(en(["0x03",Vo(W[0])]))}return Pt(B)})(),k=_-(Date.now()-C);if(k<=0)throw new Gh({hash:H});let F=await ue(e,Z3,"waitForTransactionReceipt")({checkReplacement:!1,hash:H,pollingInterval:x,timeout:k});if(v&&F.status==="reverted")throw new Zh({receipt:F});return F}}throw O?.type==="smart"?new fc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new fc({docsPath:"/docs/actions/wallet/sendTransactionSync",type:O?.type})}catch(M){throw M instanceof fc?M:(D&&!(M instanceof Zh)&&O?.nonceManager?.reset(D),H0(M,{...t,account:O,chain:t.chain||void 0}))}}var XM,eH=b(()=>{l();tn();yu();nt();zn();Z4();b3();Fn();Si();mT();wb();o3();P0();rl();_t();gT();Ks();_f();nl();Zf();ZM();Rb();i_();XM=new xo(128)});async function I6(e,t){return _a.internal(e,a_,"sendTransactionSync",t)}var c_=b(()=>{l();eH();Yb()});async function tH(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:s}=jo(e,{token:n}),i=s_(r,s),a=await ap.inner(I6,e,{...t,throwOnReceiptRevert:o}),{args:c}=ap.extractEvent(a.logs);return{...c,...i===void 0?{}:{decimals:i,formatted:pc(c.value,i)},receipt:a}}var Cue=b(()=>{l();z3();c_();QM();ip()});async function T6(e,t){let{account:r,decimals:n,spender:o,token:s,...i}=t,[a,{decimals:c}]=await Promise.all([er(e,{...i,...T6.call(e,{account:r,spender:o,token:s})}),A6(e,{decimals:n,token:s})]);return E6(a,c)}var Sue=b(()=>{l();So();oi();ip();(function(e){function t(r,n){return Eu({address:jo(r,n).address,abi:Hr,functionName:"allowance",args:[n.account,n.spender]})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(T6||(T6={}))});async function _6(e,t){let{account:r=e.account,decimals:n,token:o,...s}=t;if(!r)throw new kn;let i=ft(r).address,[a,{decimals:c}]=await Promise.all([er(e,{...s,..._6.call(e,{account:i,token:o})}),A6(e,{decimals:n,token:o})]);return E6(a,c)}var Iue=b(()=>{l();tn();So();yu();oi();ip();(function(e){function t(r,n){let o=n.account??r.account;if(!o)throw new kn;let s=ft(o).address;return Eu({address:jo(r,n).address,abi:Hr,functionName:"balanceOf",args:[s]})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(_6||(_6={}))});async function rH(e,t){let{token:r,...n}=t,{address:o}=jo(e,{token:r}),s=JM(e,r),[i,a,c]=await Promise.all([s?.decimals??er(e,{...n,abi:Hr,address:o,functionName:"decimals"}),s?.name??er(e,{...n,abi:Hr,address:o,functionName:"name"}),s?.symbol??er(e,{...n,abi:Hr,address:o,functionName:"symbol"})]);return{decimals:i,name:a,symbol:c}}var Tue=b(()=>{l();So();oi();ip()});async function P6(e,t){let{decimals:r,token:n,...o}=t,[s,{decimals:i}]=await Promise.all([er(e,{...o,...P6.call(e,{token:n})}),A6(e,{decimals:r,token:n})]);return E6(s,i)}var _ue=b(()=>{l();So();oi();ip();(function(e){function t(r,n){return Eu({address:jo(r,n).address,abi:Hr,args:[],functionName:"totalSupply"})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(P6||(P6={}))});async function cp(e,t){return cp.inner(_a,e,t)}function nHe(e,t){let{amount:r,from:n,to:o,token:s}=t,{address:i,decimals:a}=jo(e,{token:s}),c=o_(r,a);return n?{abi:Hr,address:i,args:[n,o,c],functionName:"transferFrom"}:{abi:Hr,address:i,args:[o,c],functionName:"transfer"}}var nH=b(()=>{l();So();Dg();i3();g3();Yb();ip();(function(e){async function t(i,a,c){return await i(a,{...c,...e.call(a,c)})}e.inner=t;function r(i,a){return Eu(nHe(i,a))}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:r,writable:!0});async function n(i,a){return $0(i,{...C6(a),...e.call(i,a)})}e.estimateGas=n;async function o(i,a){return Y0(i,{...C6(a),...e.call(i,a)})}e.simulate=o;function s(i){let[a]=cc({abi:Hr,logs:i,eventName:"Transfer",strict:!0});if(!a)throw new Error("`Transfer` event not found.");return a}e.extractEvent=s})(cp||(cp={}))});async function oH(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:s}=jo(e,{token:n}),i=s_(r,s),a=await cp.inner(I6,e,{...t,throwOnReceiptRevert:o}),{args:c}=cp.extractEvent(a.logs);return{...c,...i===void 0?{}:{decimals:i,formatted:pc(c.value,i)},receipt:a}}var Pue=b(()=>{l();z3();c_();ip();nH()});var sH=b(()=>{l();QM();Cue();Sue();Iue();Tue();_ue();nH();Pue()});function l_(e){return{call:t=>ms(e,t),createAccessList:t=>rae(e,t),createBlockFilter:()=>oae(e),createContractEventFilter:t=>Zw(e,t),createEventFilter:t=>sT(e,t),createPendingTransactionFilter:()=>iT(e),estimateContractGas:t=>$0(e,t),estimateGas:t=>Ob(e,t),getBalance:t=>iae(e,t),getBlobBaseFee:()=>cae(e),getBlock:t=>xn(e,t),getBlockNumber:t=>Ta(e,t),getBlockReceipts:t=>uae(e,t),getBlockTransactionCount:t=>fae(e,t),getBytecode:t=>jg(e,t),getChainId:()=>hs(e),getCode:t=>jg(e,t),getContractEvents:t=>kb(e,t),getDelegation:t=>hae(e,t),getEip712Domain:t=>yae(e,t),getEnsAddress:t=>Die(e,t),getEnsAvatar:t=>Yie(e,t),getEnsName:t=>Qie(e,t),getEnsResolver:t=>eae(e,t),getEnsText:t=>oT(e,t),getFeeHistory:t=>vae(e,t),estimateFeesPerGas:t=>Mse(e,t),getFilterChanges:t=>J0(e,t),getFilterLogs:t=>Aae(e,t),getGasPrice:()=>Cb(e),getLogs:t=>F0(e,t),getProof:t=>Sle(e,t),estimateMaxPriorityFeePerGas:t=>Lse(e,t),fillTransaction:t=>Nb(e,t),getRawTransaction:t=>Tle(e,t),getStorageAt:t=>Ple(e,t),getStorageValues:t=>Rle(e,t),getTransaction:t=>cm(e,t),getTransactionConfirmations:t=>Ble(e,t),getTransactionCount:t=>k0(e,t),getTransactionReceipt:t=>lm(e,t),iterateLogs:t=>o9(e,t),multicall:t=>Ule(e,t),prepareTransactionRequest:t=>pu(e,t),readContract:t=>er(e,t),sendRawTransaction:t=>Gb(e,t),sendRawTransactionSync:t=>S6(e,t),simulate:t=>w6(e,t),simulateBlocks:t=>w6(e,t),simulateCalls:t=>eue(e,t),simulateContract:t=>Y0(e,t),verifyHash:t=>fm(e,t),verifyMessage:t=>sue(e,t),verifySiweMessage:t=>Eue(e,t),verifyTypedData:t=>aue(e,t),uninstallFilter:t=>X0(e,t),waitForTransactionReceipt:t=>Z3(e,t),watchBlockHeaders:t=>uue(e,t),watchBlocks:t=>fue(e,t),watchBlockNumber:t=>n_(e,t),watchContractEvent:t=>M9(e,t),watchEvent:t=>hue(e,t),watchPendingTransactions:t=>gue(e,t),token:oHe(e)}}function oHe(e){return{getAllowance:bu(e,T6),getBalance:bu(e,_6),getMetadata:bu(e,rH),getTotalSupply:bu(e,P6)}}var iH=b(()=>{l();Lie();Jie();Xie();tae();HL();G0();nae();sae();II();$L();FL();i3();ZD();r9();KD();t9();aae();lae();fu();zg();dae();pae();Zf();aT();s9();mae();wae();Eae();y3();Cae();qI();c3();Ile();_le();Nle();Ole();YT();kle();e3();LM();eL();Dle();oi();MM();tue();g3();w3();K3();iue();cue();ZM();due();KM();pue();IL();mue();yue();Aue();sH();Rb();H9();i_();nm()});function Nue(e){let{key:t="public",name:r="Public Client"}=e;return wu({...e,key:t,name:r,type:"publicClient"}).extend(l_)}var Rue=b(()=>{l();nm();iH()});async function Oue(e,{hash:t}){await e.request({method:`${e.mode}_dropTransaction`,params:[t]})}var Bue=b(()=>{l()});async function kue(e){return e.request({method:`${e.mode}_dumpState`})}var Uue=b(()=>{l()});async function Due(e){return e.mode==="ganache"?await e.request({method:"eth_mining"}):await e.request({method:`${e.mode}_getAutomine`})}var Lue=b(()=>{l()});async function Mue(e){return await e.request({method:"txpool_content"})}var Hue=b(()=>{l()});async function $ue(e){let{pending:t,queued:r}=await e.request({method:"txpool_status"});return{pending:wt(t),queued:wt(r)}}var Fue=b(()=>{l();Xr()});async function zue(e,{address:t}){await e.request({method:`${e.mode}_impersonateAccount`,params:[t]})}var Vue=b(()=>{l()});async function jue(e,{seconds:t}){return await e.request({method:"evm_increaseTime",params:[oe(t)]})}var que=b(()=>{l();qe()});async function Wue(e){return await e.request({method:"txpool_inspect"})}var Kue=b(()=>{l()});async function Zue(e,{state:t}){await e.request({method:`${e.mode}_loadState`,params:[t]})}var Gue=b(()=>{l()});async function Yue(e,{blocks:t,interval:r}){e.mode==="ganache"?await e.request({method:"evm_mine",params:[{blocks:oe(t)}]}):await e.request({method:`${e.mode}_mine`,params:[oe(t),oe(r||0)]})}var Jue=b(()=>{l();qe()});async function Que(e){await e.request({method:`${e.mode}_removeBlockTimestampInterval`})}var Xue=b(()=>{l()});async function ede(e,{blockNumber:t,jsonRpcUrl:r}={}){await e.request({method:`${e.mode}_reset`,params:[{forking:{blockNumber:Number(t),jsonRpcUrl:r}}]})}var tde=b(()=>{l()});async function rde(e,{id:t}){await e.request({method:"evm_revert",params:[t]})}var nde=b(()=>{l()});async function ode(e,t){let{accessList:r,data:n,from:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:f,...p}=t,h=e.chain?.formatters?.transactionRequest?.format,w=(h||Bn)({...Ri(p,{format:h}),accessList:r,data:n,from:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:f},"sendUnsignedTransaction");return await e.request({method:"eth_sendUnsignedTransaction",params:[w]})}var sde=b(()=>{l();P0();rl()});async function ide(e,t){e.mode==="ganache"?t?await e.request({method:"miner_start"}):await e.request({method:"miner_stop"}):await e.request({method:"evm_setAutomine",params:[t]})}var ade=b(()=>{l()});async function cde(e,{address:t,value:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountBalance",params:[t,oe(r)]}):await e.request({method:`${e.mode}_setBalance`,params:[t,oe(r)]})}var lde=b(()=>{l();qe()});async function ude(e,{gasLimit:t}){await e.request({method:"evm_setBlockGasLimit",params:[oe(t)]})}var dde=b(()=>{l();qe()});async function fde(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:`${e.mode}_setBlockTimestampInterval`,params:[r]})}var pde=b(()=>{l()});async function hde(e,{address:t,bytecode:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountCode",params:[t,r]}):await e.request({method:`${e.mode}_setCode`,params:[t,r]})}var mde=b(()=>{l()});async function gde(e,{address:t}){await e.request({method:`${e.mode}_setCoinbase`,params:[t]})}var yde=b(()=>{l()});async function wde(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:"evm_setIntervalMining",params:[r]})}var bde=b(()=>{l()});async function xde(e,t){await e.request({method:`${e.mode}_setLoggingEnabled`,params:[t]})}var vde=b(()=>{l()});async function Ede(e,{gasPrice:t}){await e.request({method:`${e.mode}_setMinGasPrice`,params:[oe(t)]})}var Ade=b(()=>{l();qe()});async function Cde(e,{baseFeePerGas:t}){await e.request({method:`${e.mode}_setNextBlockBaseFeePerGas`,params:[oe(t)]})}var Sde=b(()=>{l();qe()});async function Ide(e,{timestamp:t}){await e.request({method:"evm_setNextBlockTimestamp",params:[oe(t)]})}var Tde=b(()=>{l();qe()});async function _de(e,{address:t,nonce:r}){await e.request({method:`${e.mode}_setNonce`,params:[t,oe(r)]})}var Pde=b(()=>{l();qe()});async function Nde(e,t){await e.request({method:`${e.mode}_setRpcUrl`,params:[t]})}var Rde=b(()=>{l()});async function Ode(e,{address:t,index:r,value:n}){await e.request({method:`${e.mode}_setStorageAt`,params:[t,typeof r=="number"?oe(r):r,n]})}var Bde=b(()=>{l();qe()});async function kde(e){return await e.request({method:"evm_snapshot"})}var Ude=b(()=>{l()});async function Dde(e,{address:t}){await e.request({method:`${e.mode}_stopImpersonatingAccount`,params:[t]})}var Lde=b(()=>{l()});function u_({mode:e}){return t=>{let r=t.extend(()=>({mode:e}));return{dropTransaction:n=>Oue(r,n),dumpState:()=>kue(r),getAutomine:()=>Due(r),getTxpoolContent:()=>Mue(r),getTxpoolStatus:()=>$ue(r),impersonateAccount:n=>zue(r,n),increaseTime:n=>jue(r,n),inspectTxpool:()=>Wue(r),loadState:n=>Zue(r,n),mine:n=>Yue(r,n),removeBlockTimestampInterval:()=>Que(r),reset:n=>ede(r,n),revert:n=>rde(r,n),sendUnsignedTransaction:n=>ode(r,n),setAutomine:n=>ide(r,n),setBalance:n=>cde(r,n),setBlockGasLimit:n=>ude(r,n),setBlockTimestampInterval:n=>fde(r,n),setCode:n=>hde(r,n),setCoinbase:n=>gde(r,n),setIntervalMining:n=>wde(r,n),setLoggingEnabled:n=>xde(r,n),setMinGasPrice:n=>Ede(r,n),setNextBlockBaseFeePerGas:n=>Cde(r,n),setNextBlockTimestamp:n=>Ide(r,n),setNonce:n=>_de(r,n),setRpcUrl:n=>Nde(r,n),setStorageAt:n=>Ode(r,n),snapshot:()=>kde(r),stopImpersonatingAccount:n=>Dde(r,n)}}}var aH=b(()=>{l();Bue();Uue();Lue();Hue();Fue();Vue();que();Kue();Gue();Jue();Xue();tde();nde();sde();ade();lde();dde();pde();mde();yde();bde();vde();Ade();Sde();Tde();Pde();Rde();Bde();Ude();Lde()});function Mde(e){let{key:t="test",name:r="Test Client",mode:n}=e;return wu({...e,key:t,name:r,type:"testClient"}).extend(s=>({mode:n,...u_({mode:n})(s)}))}var Hde=b(()=>{l();nm();aH()});async function $de(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:s,blockExplorers:i}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:oe(r),chainName:n,nativeCurrency:o,rpcUrls:s.default.http,blockExplorerUrls:i?Object.values(i).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}var Fde=b(()=>{l();qe()});function zde(e,t){let{abi:r,args:n,bytecode:o,...s}=t,i=tp({abi:r,args:n,bytecode:o});return ue(e,tm,"sendTransaction")({...s,...s.authorizationList?{to:null}:{},data:i})}var Vde=b(()=>{l();p3();_t();x3()});async function jde(e){return e.account?.type==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(r=>Kc(r))}var qde=b(()=>{l();Zs()});async function Wde(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?ft(r):void 0,s=n?[o?.address,[oe(n)]]:[o?.address],i=await e.request({method:"wallet_getCapabilities",params:s}),a={};for(let[c,u]of Object.entries(i)){a[Number(c)]={};for(let[d,f]of Object.entries(u))d==="addSubAccount"&&(d="unstable_addSubAccount"),a[Number(c)][d]=f}return typeof n=="number"?a[n]:a}var Kde=b(()=>{l();tn();qe()});async function Zde(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}var Gde=b(()=>{l()});async function d_(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new kn({docsPath:"/docs/eip7702/prepareAuthorization"});let s=ft(r),i=(()=>{if(t.executor)return t.executor==="self"?t.executor:ft(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};return typeof a.chainId>"u"&&(a.chainId=e.chain?.id??await ue(e,hs,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ue(e,k0,"getTransactionCount")({address:s.address,blockTag:"pending"}),(i==="self"||i?.address&&xr(i.address,s.address))&&(a.nonce+=1)),a}var cH=b(()=>{l();tn();yu();Oi();_t();Zf();e3()});async function Yde(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Gr(r))}var Jde=b(()=>{l();Zs()});async function Qde(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}var Xde=b(()=>{l()});async function efe(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5e3),o=await ue(e,F9,"sendCalls")(t);return await ue(e,j9,"waitForCallsStatus")({...t,id:o.id,timeout:n})}var tfe=b(()=>{l();_t();z9();q9()});async function rfe(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}var nfe=b(()=>{l()});async function ofe(e,t){let{account:r=e.account}=t;if(!r)throw new kn({docsPath:"/docs/eip7702/signAuthorization"});let n=ft(r);if(!n.signAuthorization)throw new fc({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await ue(e,d_,"prepareAuthorization")(t);return n.signAuthorization(o)}var sfe=b(()=>{l();tn();yu();_t();cH()});async function ife(e,{account:t=e.account,message:r}){if(!t)throw new kn({docsPath:"/docs/actions/wallet/signMessage"});let n=ft(t);if(n.signMessage)return n.signMessage({message:r});let o=typeof r=="string"?ec(r):r.raw instanceof Uint8Array?wr(r.raw):r.raw;return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}var afe=b(()=>{l();tn();yu();qe()});async function cfe(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new kn({docsPath:"/docs/actions/wallet/signTransaction"});let s=ft(r);jn({account:s,...t});let i=await ue(e,hs,"getChainId")({});n!==null&&em({currentChainId:i,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||Bn;return s.signTransaction?s.signTransaction({...o,account:s,chainId:i},{serializer:e.chain?.serializers?.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...o,account:s},"signTransaction"),chainId:oe(i),from:s.address}]},{retryCount:0})}var lfe=b(()=>{l();tn();yu();b3();qe();rl();_t();nl();Zf()});async function ufe(e,t){let{account:r=e.account,domain:n,message:o,primaryType:s}=t;if(!r)throw new kn({docsPath:"/docs/actions/wallet/signTypedData"});let i=ft(r),a={EIP712Domain:Zg({domain:n}),...t.types};if(f6({domain:n,message:o,primaryType:s,types:a}),i.signTypedData)return i.signTypedData({domain:n,message:o,primaryType:s,types:a});let c=vT({domain:n,message:o,primaryType:s,types:a});return e.request({method:"eth_signTypedData_v4",params:[i.address,c]},{retryCount:0})}var dfe=b(()=>{l();tn();yu();ET()});async function ffe(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:oe(t)}]},{retryCount:0})}var pfe=b(()=>{l();qe()});async function hfe(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}var mfe=b(()=>{l()});function f_(e){return{addChain:t=>$de(e,t),deployContract:t=>zde(e,t),fillTransaction:t=>Nb(e,t),getAddresses:()=>jde(e),getCallsStatus:t=>V9(e,t),getCapabilities:t=>Wde(e,t),getChainId:()=>hs(e),getPermissions:()=>Zde(e),prepareAuthorization:t=>d_(e,t),prepareTransactionRequest:t=>pu(e,t),requestAddresses:()=>Yde(e),requestPermissions:t=>Qde(e,t),sendCalls:t=>F9(e,t),sendCallsSync:t=>efe(e,t),sendRawTransaction:t=>Gb(e,t),sendRawTransactionSync:t=>S6(e,t),sendTransaction:t=>tm(e,t),sendTransactionSync:t=>a_(e,t),showCallsStatus:t=>rfe(e,t),signAuthorization:t=>ofe(e,t),signMessage:t=>ife(e,t),signTransaction:t=>cfe(e,t),signTypedData:t=>ufe(e,t),switchChain:t=>ffe(e,t),waitForCallsStatus:t=>j9(e,t),watchAsset:t=>hfe(e,t),writeContract:t=>_a(e,t),writeContractSync:t=>I6(e,t),token:{approve:bu(e,ap),approveSync:bu(e,tH),transfer:bu(e,cp),transferSync:bu(e,oH)}}}var lH=b(()=>{l();t9();Zf();sH();Fde();Vde();qde();BL();Kde();Gde();cH();Rb();Jde();Xde();z9();tfe();H9();i_();x3();eH();nfe();sfe();afe();lfe();dfe();pfe();q9();mfe();Yb();c_();nm()});function gfe(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return wu({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(f_)}var yfe=b(()=>{l();nm();lH()});function Au({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:s=150,timeout:i,type:a},c){let u=rm();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:s,timeout:i,type:a},request:Dae(n,{methods:t,retryCount:o,retryDelay:s,uid:u}),value:c}}var N6=b(()=>{l();Mae();A3()});function wfe(e,t={}){let{key:r="custom",methods:n,name:o="Custom Provider",retryDelay:s}=t;return({retryCount:i})=>Au({key:r,methods:n,name:o,request:e.request.bind(e),retryCount:t.retryCount??i,retryDelay:s,type:"custom"})}var bfe=b(()=>{l();N6()});function G3(e,t={}){let{key:r="fallback",name:n="Fallback",rank:o=!1,shouldThrow:s=uH,retryCount:i,retryDelay:a}=t;return(({chain:c,pollingInterval:u=4e3,timeout:d,...f})=>{let p=e,h=()=>{},y=Au({key:r,name:n,async request({method:w,params:x},v){let T,E=async(S=0)=>{let _=p[S]({...f,chain:c,retryCount:0,timeout:d});try{let O=await _.request({method:w,params:x},v);return h({method:w,params:x,response:O,transport:_,status:"success"}),O}catch(O){if(h({error:O,method:w,params:x,transport:_,status:"error"}),s(O)||w==="eth_sendRawTransactionSync"&&O instanceof G&&O.walk(D=>D?.code===4)||S===p.length-1||(T??=p.slice(S+1).some(D=>{let{include:M,exclude:N}=D({chain:c}).config.methods||{};return M?M.includes(w):N?!N.includes(w):!0}),!T))throw O;return E(S+1)}};return E()},retryCount:i,retryDelay:a,type:"fallback"},{onResponse:w=>h=w,transports:p.map(w=>w({chain:c,retryCount:0}))});if(o){let w=typeof o=="object"?o:{};sHe({chain:c,interval:w.interval??u,onTransports:x=>p=x,ping:w.ping,sampleCount:w.sampleCount,timeout:w.timeout,transports:p,weights:w.weights})}return y})}function uH(e){return!!("code"in e&&typeof e.code=="number"&&(e.code===iu.code||e.code===Xc.code||e.code===f0.code||ri.nodeMessage.test(e.message)||e.code===5e3))}function sHe({chain:e,interval:t=4e3,onTransports:r,ping:n,sampleCount:o=10,timeout:s=1e3,transports:i,weights:a={}}){let{stability:c=.7,latency:u=.3}=a,d=[],f=async()=>{let p=await Promise.all(i.map(async w=>{let x=w({chain:e,retryCount:0,timeout:s}),v=Date.now(),T,E;try{await(n?n({transport:x}):x.request({method:"net_listening"})),E=1}catch{E=0}finally{T=Date.now()}return{latency:T-v,success:E}}));d.push(p),d.length>o&&d.shift();let h=Math.max(...d.map(w=>Math.max(...w.map(({latency:x})=>x)))),y=i.map((w,x)=>{let v=d.map(O=>O[x].latency),E=1-v.reduce((O,D)=>O+D,0)/v.length/h,S=d.map(O=>O[x].success),_=S.reduce((O,D)=>O+D,0)/S.length;return _===0?[0,x]:[u*E+c*_,x]}).sort((w,x)=>x[0]-w[0]);r(y.map(([,w])=>i[w])),await $g(t),f()};f()}var xfe=b(()=>{l();nt();tl();Lf();D9();N6()});var pm,p_=b(()=>{l();nt();pm=class extends G{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}});function aHe(e){if(!e)return"default";let t=vfe.get(e);if(t!==void 0)return t;let r=iHe++;return vfe.set(e,r),r}function ry(e,t={}){let{batch:r,fetchFn:n,fetchOptions:o,key:s="http",maxResponseBodySize:i,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:u,onFetchResponse:d,retryDelay:f,raw:p}=t,h=rm();return({chain:y,retryCount:w,timeout:x})=>{let{batchSize:v=1e3,wait:T=0}=typeof r=="object"?r:{},E=t.retryCount??w,S=x??t.timeout??1e4,_=e||y?.rpcUrls.default.http[0];if(!_)throw new pm;let O=mce(_,{fetchFn:n,fetchOptions:o,maxResponseBodySize:i,onRequest:u,onResponse:d,timeout:S});return Au({key:s,methods:a,name:c,async request({method:D,params:M},N){let L={method:D,params:M},P=N?.signal?{signal:N.signal}:void 0,{schedule:R}=Z0({id:`${h}.${_}.${aHe(N?.signal)}`,wait:T,shouldSplitBatch(A){return A.length>v},fn:A=>O.request({body:A,fetchOptions:P}),sort:(A,U)=>A.id-U.id}),I=async A=>r?R(A):[await O.request({body:A,fetchOptions:P})],[{error:B,result:C}]=await I(L).catch(A=>{if(p&&A instanceof Rn)return[{error:A.cause,result:void 0}];throw A});if(p)return{error:B,result:C};if(B)throw new Rn({body:L,error:B,url:_});return C},retryCount:E,retryDelay:f,timeout:S,type:"http"},{fetchOptions:o,url:_})}}var iHe,vfe,Efe=b(()=>{l();fs();p_();h3();gce();A3();N6();iHe=0,vfe=new WeakMap});function Afe(e,t={}){let{keepAlive:r,key:n="webSocket",methods:o,name:s="WebSocket JSON-RPC",reconnect:i,retryDelay:a}=t;return({chain:c,retryCount:u,timeout:d})=>{let f=t.retryCount??u,p=d??t.timeout??1e4,h=e||c?.rpcUrls.default.webSocket?.[0],y={keepAlive:r,reconnect:i};if(!h)throw new pm;return Au({key:n,methods:o,name:s,async request({method:w,params:x}){let v={method:w,params:x},T=await c6(h,y),{error:E,result:S}=await T.requestAsync({body:v,timeout:p});if(E)throw new Rn({body:v,error:E,url:h});return S},retryCount:f,retryDelay:a,timeout:p,type:"webSocket"},{getSocket(){return Cce(h)},getRpcClient(){return c6(h,y)},async subscribe({params:w,onData:x,onError:v}){let T=await c6(h,y),E,S=!1;function _(){return S=!0,new Promise(O=>T.request({body:{method:"eth_unsubscribe",params:[E]},onResponse:O}))}return await new Promise((O,D)=>T.request({body:{method:"eth_subscribe",params:w},onError(M){D(M),v?.(M)},onResponse(M){if(M.error){D(M.error),v?.(M.error);return}if(typeof M.id=="number"){E=M.result,S&&_(),O(M);return}M.method==="eth_subscription"&&x(M.params)}})),{get subscriptionId(){return E},unsubscribe:_}}})}}var Cfe=b(()=>{l();fs();p_();Sce();GL();N6()});var Sfe,Ife,Tfe,_fe=b(()=>{l();Sfe={gwei:9,wei:18},Ife={ether:-9,wei:9},Tfe={ether:-18,gwei:-9}});var h_,Pfe=b(()=>{l();nt();h_=class extends G{constructor({value:t}){super(`Number \`${t}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}}});var m_,Nfe=b(()=>{l();m_=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}}});function Rfe(e){let{abi:t,bytecode:r,data:n}=e;if(n===r)return{bytecode:r};let o=t.find(i=>"type"in i&&i.type==="constructor");if(!o)throw new Oh({docsPath:dH});if(!("inputs"in o))throw new Gl({docsPath:dH});if(!o.inputs||o.inputs.length===0)throw new Gl({docsPath:dH});return{args:Ys(o.inputs,`0x${n.replace(r,"")}`),bytecode:r}}var dH,Ofe=b(()=>{l();Qr();zh();dH="/docs/contract/decodeDeployData"});function Bfe(e){let t=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),r=typeof e.blobs[0]=="string"?e.blobs.map(a=>qt(a)):e.blobs,n=r.reduce((a,c)=>a+c.length,0),o=Zc(new Uint8Array(n)),s=!0;for(let[a,c]of r.entries()){let u=Zc(c),d=a===r.length-1;for(;s&&u.position{l();Jw();Pr();qe()});function Ufe(e){let{sidecars:t,version:r}=e,n=e.to??(typeof t[0].blob=="string"?"hex":"bytes"),o=[];for(let{commitment:s}of t)o.push(Ib({commitment:s,to:n,version:r}));return o}var Dfe=b(()=>{l();ZI()});function Lfe(e){if(e===1)return 60n;if(e>=cHe||e<0)throw new r6({chainId:e});return BigInt((2147483648|e)>>>0)}var cHe,Mfe=b(()=>{l();rT();cHe=2147483648});function g_({blobToKzgCommitment:e,computeBlobKzgProof:t}){return{blobToKzgCommitment:e,computeBlobKzgProof:t}}var fH=b(()=>{l()});function Hfe(e,t){try{e.loadTrustedSetup(t)}catch(r){let n=r;if(!n.message.includes("trusted setup is already loaded"))throw n}return g_(e)}var $fe=b(()=>{l();fH()});function Ffe({r:e,yParityAndS:t}){let r=qt(Zr(t)),n=r[0]&128?1:0,o=r;return n===1&&(o[0]&=127),{r:Zr(e),s:yt(o),yParity:n}}var zfe=b(()=>{l();Xa();Pr();qe()});function pH(e){let{r:t,s:r}=ei.Signature.fromCompact(e.slice(2,130));return{r:oe(t,{size:32}),yParityAndS:oe(r,{size:32})}}var Vfe=b(()=>{l();Bg();qe()});function hH(e){let{r:t,s:r}=ei.Signature.fromCompact(e.slice(2,130)),n=+`0x${e.slice(130)}`,[o,s]=(()=>{if(n===0||n===1)return[void 0,n];if(n===27)return[BigInt(n),0];if(n===28)return[BigInt(n),1];throw new Error("Invalid yParityOrV value")})();return typeof o<"u"?{r:oe(t,{size:32}),s:oe(r,{size:32}),v:o,yParity:s}:{r:oe(t,{size:32}),s:oe(r,{size:32}),yParity:s}}var jfe=b(()=>{l();Bg();qe()});async function qfe(e){let{serializedTransaction:t,signature:r}=e,n=WT(t),o=r??{r:n.r,s:n.s,v:n.v,yParity:n.yParity},s=fT({...n,r:void 0,s:void 0,v:void 0,yParity:void 0,sidecars:void 0});return await ti({hash:Pt(s),signature:o})}var Wfe=b(()=>{l();Ks();kM();pT();w0()});function mH({r:e,yParityAndS:t}){return`0x${new ei.Signature(dt(e),dt(t)).toCompactHex()}`}var Kfe=b(()=>{l();Bg();Xr()});function Zfe(e){let{r:t,s:r,v:n,yParity:o}=e,s=(()=>{if(o===0||o===1)return o;if(n===0n||n===1n)return Number(n);if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),i=qt(Zr(r));if(i[0]&128)throw new Error("Invalid `s` value");return s===1&&(i[0]|=128),{r:Zr(t),yParityAndS:yt(i)}}var Gfe=b(()=>{l();Xa();Pr();qe()});var Yfe={};Te(Yfe,{AbiConstructorNotFoundError:()=>Oh,AbiConstructorParamsNotFoundError:()=>Gl,AbiDecodingDataSizeInvalidError:()=>yI,AbiDecodingDataSizeTooSmallError:()=>Bh,AbiDecodingSizeLimitExceededError:()=>Xw,AbiDecodingZeroDataError:()=>Ci,AbiEncodingArrayLengthMismatchError:()=>Nw,AbiEncodingBytesSizeMismatchError:()=>Rw,AbiEncodingLengthMismatchError:()=>kh,AbiErrorInputsNotFoundError:()=>Ow,AbiErrorNotFoundError:()=>pg,AbiErrorSignatureNotFoundError:()=>Uh,AbiEventAmbiguityError:()=>Gf,AbiEventNotFoundError:()=>hg,AbiEventSignatureEmptyTopicsError:()=>Yl,AbiEventSignatureNotFoundError:()=>Jl,AbiFunctionNotFoundError:()=>wa,AbiFunctionOutputsNotFoundError:()=>Dh,AbiFunctionSignatureNotFoundError:()=>Bw,AccountStateConflictError:()=>tb,AtomicReadyWalletRejectedUpgradeError:()=>d0,AtomicityNotSupportedError:()=>cu,BaseError:()=>G,BaseFeeScalarError:()=>O0,BlockNotFoundError:()=>du,BundleFailedError:()=>Jb,BundleTooLargeError:()=>u0,BytesSizeMismatchError:()=>Lh,CallExecutionError:()=>Yc,ChainDisconnectedError:()=>s0,ChainDoesNotSupportContract:()=>Wf,ChainMismatchError:()=>U0,ChainNotConfiguredError:()=>C3,ChainNotFoundError:()=>Sb,CircularReferenceError:()=>lg,ClientChainNotConfiguredError:()=>kg,ContractFunctionExecutionError:()=>ab,ContractFunctionRevertedError:()=>Uf,ContractFunctionZeroDataError:()=>cb,CounterfactualDeploymentFailedError:()=>lb,DecodeLogDataMismatch:()=>jc,DecodeLogTopicsMismatch:()=>Ql,DuplicateIdError:()=>c0,EIP1193ProviderRpcError:()=>m_,Eip1559FeesNotSupportedError:()=>uu,EnsAvatarInvalidNftUriError:()=>xu,EnsAvatarUnsupportedNamespaceError:()=>t6,EnsAvatarUriResolutionError:()=>om,EnsInvalidChainIdError:()=>r6,EstimateGasExecutionError:()=>bb,ExecutionRevertedError:()=>ri,FeeCapTooHighError:()=>Pi,FeeCapTooLowError:()=>x0,FeeConflictError:()=>BI,FeePayerNonceMismatchError:()=>Wh,FilterTypeNotSupportedError:()=>Lw,HttpRequestError:()=>Nr,InsufficientFundsError:()=>C0,IntegerOutOfRangeError:()=>Xl,InternalRpcError:()=>Qc,IntrinsicGasTooHighError:()=>S0,IntrinsicGasTooLowError:()=>I0,InvalidAbiDecodingTypeError:()=>Uw,InvalidAbiEncodingTypeError:()=>kw,InvalidAbiItemError:()=>Q1,InvalidAbiParameterError:()=>eg,InvalidAbiParametersError:()=>tg,InvalidAbiTypeParameterError:()=>ig,InvalidAddressError:()=>br,InvalidArrayError:()=>Mh,InvalidBytesBooleanError:()=>Mw,InvalidChainIdError:()=>Kf,InvalidDecimalNumberError:()=>h_,InvalidDefinitionTypeError:()=>Pw,InvalidDomainError:()=>l6,InvalidFunctionModifierError:()=>sg,InvalidHexBooleanError:()=>Hw,InvalidHexValueError:()=>$w,InvalidInputRpcError:()=>Ti,InvalidLegacyVError:()=>Kh,InvalidModifierError:()=>og,InvalidParameterError:()=>rg,InvalidParamsRpcError:()=>Qh,InvalidParenthesisError:()=>ug,InvalidPrimaryTypeError:()=>u6,InvalidRequestRpcError:()=>Jh,InvalidSerializableTransactionError:()=>nb,InvalidSerializedTransactionError:()=>ru,InvalidSerializedTransactionTypeError:()=>ob,InvalidSignatureError:()=>ya,InvalidStorageKeySizeError:()=>sb,InvalidStructSignatureError:()=>cg,InvalidStructTypeError:()=>d6,InvalidTypedDataTypeError:()=>Kg,InvalidYParityError:()=>tu,JsonRpcVersionUnsupportedError:()=>t0,LimitExceededRpcError:()=>Df,MaxFeePerGasTooLowError:()=>vb,MethodNotFoundRpcError:()=>Jc,MethodNotSupportedRpcError:()=>Aa,NonceMaxValueError:()=>A0,NonceTooHighError:()=>v0,NonceTooLowError:()=>E0,ParseRpcError:()=>Yh,ProviderDisconnectedError:()=>o0,ProviderRpcError:()=>Ao,RawContractError:()=>sc,ResourceNotFoundRpcError:()=>Xh,ResourceUnavailableRpcError:()=>e0,ResponseBodyTooLargeError:()=>ic,RlpDepthLimitExceededError:()=>Fw,RlpListBoundaryExceededError:()=>zw,RlpTrailingBytesError:()=>Vw,RpcError:()=>Eo,RpcRequestError:()=>Rn,SizeExceedsPaddingSizeError:()=>gg,SizeOverflowError:()=>jw,SliceOffsetOutOfBoundsError:()=>mg,SocketClosedError:()=>su,SolidityProtectedKeywordError:()=>ng,StateAssignmentConflictError:()=>rb,SwitchChainError:()=>i0,TimeoutError:()=>ds,TipAboveFeeCapError:()=>ac,TransactionExecutionError:()=>ib,TransactionNotFoundError:()=>Gc,TransactionReceiptNotFoundError:()=>nu,TransactionRejectedRpcError:()=>iu,TransactionTypeNotSupportedError:()=>T0,TransportNotConfiguredError:()=>S3,UnauthorizedProviderError:()=>r0,UnknownBundleIdError:()=>l0,UnknownNodeError:()=>Ni,UnknownRpcError:()=>ub,UnknownSignatureError:()=>ag,UnknownTypeError:()=>X1,UnsupportedChainIdError:()=>a0,UnsupportedNonOptionalCapabilityError:()=>au,UnsupportedPackedAbiType:()=>Dw,UnsupportedProviderMethodError:()=>n0,UrlRequiredError:()=>pm,UserRejectedRequestError:()=>Xc,WaitForCallsStatusTimeoutError:()=>E3,WaitForTransactionReceiptTimeoutError:()=>Gh,WebSocketRequestError:()=>_g,assertCurrentChain:()=>em,assertRequest:()=>jn,assertTransactionEIP1559:()=>sm,assertTransactionEIP2930:()=>n6,assertTransactionLegacy:()=>o6,blobsToCommitments:()=>D0,blobsToProofs:()=>L0,boolToBytes:()=>KU,boolToHex:()=>wg,bytesToBigInt:()=>B4,bytesToBool:()=>k4,bytesToHex:()=>yt,bytesToNumber:()=>Ea,bytesToRlp:()=>Mne,bytesToString:()=>U4,ccipFetch:()=>Hg,ccipReadTunnel:()=>Hae,ccipRequest:()=>Hg,checksumAddress:()=>Kc,commitmentToVersionedHash:()=>Ib,commitmentsToVersionedHashes:()=>Tb,compactSignatureToHex:()=>mH,compactSignatureToSignature:()=>Ffe,concat:()=>en,concatBytes:()=>eD,concatHex:()=>fr,createClient:()=>wu,createClientResolver:()=>Oie,createNonceManager:()=>WL,createPublicClient:()=>Nue,createTestClient:()=>Mde,createTransport:()=>Au,createWalletClient:()=>gfe,custom:()=>wfe,decodeAbiParameters:()=>Ys,decodeDeployData:()=>Rfe,decodeErrorResult:()=>Vh,decodeEventLog:()=>Yf,decodeFunctionData:()=>T9,decodeFunctionResult:()=>dn,defineBlock:()=>Dse,defineChain:()=>Fae,defineKzg:()=>g_,defineTransaction:()=>Use,defineTransactionReceipt:()=>Sie,defineTransactionRequest:()=>Wne,deploylessCallViaBytecodeBytecode:()=>zb,deploylessCallViaFactoryBytecode:()=>v9,domainSeparator:()=>Ice,encodeAbiParameters:()=>oo,encodeDeployData:()=>tp,encodeErrorResult:()=>m3,encodeEventTopics:()=>nc,encodeFunctionData:()=>Wt,encodeFunctionResult:()=>_9,encodePacked:()=>Sae,erc1155Abi:()=>die,erc20Abi:()=>Hr,erc20Abi_bytes32:()=>uie,erc4626Abi:()=>pie,erc6492SignatureValidatorAbi:()=>Fb,erc6492SignatureValidatorByteCode:()=>f3,erc721Abi:()=>fie,ethAddress:()=>v6,etherUnits:()=>Sfe,extendSchema:()=>zae,extractChain:()=>jae,fallback:()=>G3,formatBlock:()=>qf,formatEther:()=>qh,formatGwei:()=>Pn,formatLog:()=>qn,formatTransaction:()=>jf,formatTransactionReceipt:()=>op,formatTransactionRequest:()=>Bn,formatUnits:()=>pc,fromBlobs:()=>Bfe,fromBytes:()=>zre,fromHex:()=>WU,fromRlp:()=>Wg,getAbiItem:()=>ls,getAddress:()=>Gr,getChainContractAddress:()=>Ui,getContract:()=>Aie,getContractAddress:()=>_ae,getContractError:()=>Js,getCreate2Address:()=>jL,getCreateAddress:()=>VL,getEventSelector:()=>Wc,getEventSignature:()=>Pf,getFunctionSelector:()=>va,getFunctionSignature:()=>Pf,getSerializedTransactionType:()=>qT,getTransactionType:()=>Pb,getTypesForEIP712Domain:()=>Zg,gweiUnits:()=>Ife,hashDomain:()=>_3,hashMessage:()=>im,hashStruct:()=>AT,hashTypedData:()=>p6,hexToBigInt:()=>dt,hexToBool:()=>qw,hexToBytes:()=>qt,hexToCompactSignature:()=>pH,hexToNumber:()=>wt,hexToRlp:()=>Hne,hexToSignature:()=>hH,hexToString:()=>bI,http:()=>ry,isAddress:()=>Ft,isAddressEqual:()=>xr,isBytes:()=>I3,isErc6492Signature:()=>IT,isErc8010Signature:()=>zT,isHash:()=>i6,isHex:()=>We,keccak256:()=>Pt,labelhash:()=>J9,maxInt104:()=>ioe,maxInt112:()=>aoe,maxInt120:()=>coe,maxInt128:()=>loe,maxInt136:()=>uoe,maxInt144:()=>doe,maxInt152:()=>foe,maxInt16:()=>Gne,maxInt160:()=>poe,maxInt168:()=>hoe,maxInt176:()=>moe,maxInt184:()=>goe,maxInt192:()=>yoe,maxInt200:()=>woe,maxInt208:()=>boe,maxInt216:()=>xoe,maxInt224:()=>voe,maxInt232:()=>Eoe,maxInt24:()=>Yne,maxInt240:()=>Aoe,maxInt248:()=>Coe,maxInt256:()=>Soe,maxInt32:()=>Jne,maxInt40:()=>Qne,maxInt48:()=>Xne,maxInt56:()=>eoe,maxInt64:()=>toe,maxInt72:()=>roe,maxInt8:()=>Zne,maxInt80:()=>noe,maxInt88:()=>ooe,maxInt96:()=>soe,maxUint104:()=>gse,maxUint112:()=>yse,maxUint120:()=>wse,maxUint128:()=>bse,maxUint136:()=>xse,maxUint144:()=>vse,maxUint152:()=>Ese,maxUint16:()=>sse,maxUint160:()=>Ase,maxUint168:()=>Cse,maxUint176:()=>Sse,maxUint184:()=>Ise,maxUint192:()=>Tse,maxUint200:()=>_se,maxUint208:()=>Pse,maxUint216:()=>Nse,maxUint224:()=>Rse,maxUint232:()=>Ose,maxUint24:()=>ise,maxUint240:()=>Bse,maxUint248:()=>kse,maxUint256:()=>R0,maxUint32:()=>ase,maxUint40:()=>cse,maxUint48:()=>lse,maxUint56:()=>use,maxUint64:()=>dse,maxUint72:()=>fse,maxUint8:()=>ose,maxUint80:()=>pse,maxUint88:()=>hse,maxUint96:()=>mse,minInt104:()=>Moe,minInt112:()=>Hoe,minInt120:()=>$oe,minInt128:()=>Foe,minInt136:()=>zoe,minInt144:()=>Voe,minInt152:()=>joe,minInt16:()=>Toe,minInt160:()=>qoe,minInt168:()=>Woe,minInt176:()=>Koe,minInt184:()=>Zoe,minInt192:()=>Goe,minInt200:()=>Yoe,minInt208:()=>Joe,minInt216:()=>Qoe,minInt224:()=>Xoe,minInt232:()=>ese,minInt24:()=>_oe,minInt240:()=>tse,minInt248:()=>rse,minInt256:()=>nse,minInt32:()=>Poe,minInt40:()=>Noe,minInt48:()=>Roe,minInt56:()=>Ooe,minInt64:()=>Boe,minInt72:()=>koe,minInt8:()=>Ioe,minInt80:()=>Uoe,minInt88:()=>Doe,minInt96:()=>Loe,multicall3Abi:()=>ki,namehash:()=>Vg,nonceManager:()=>dce,numberToBytes:()=>ZU,numberToHex:()=>oe,offchainLookup:()=>B9,offchainLookupAbiItem:()=>O9,offchainLookupSignature:()=>R9,pad:()=>Zr,padBytes:()=>qU,padHex:()=>cs,parseAbi:()=>Iw,parseAbiItem:()=>Tw,parseAbiParameter:()=>zU,parseAbiParameters:()=>_w,parseCompactSignature:()=>pH,parseErc6492Signature:()=>sle,parseErc8010Signature:()=>ale,parseEther:()=>ble,parseEventLogs:()=>cc,parseGwei:()=>vle,parseSignature:()=>hH,parseTransaction:()=>WT,parseUnits:()=>GT,prepareEncodeFunctionData:()=>TI,presignMessagePrefix:()=>bT,publicActions:()=>l_,recoverAddress:()=>ti,recoverMessageAddress:()=>VT,recoverPublicKey:()=>zI,recoverTransactionAddress:()=>qfe,recoverTypedDataAddress:()=>jT,ripemd160:()=>sce,rpcSchema:()=>Rie,rpcTransactionType:()=>qD,serializeAccessList:()=>qg,serializeCompactSignature:()=>mH,serializeErc6492Signature:()=>lle,serializeErc8010Signature:()=>dle,serializeSignature:()=>W3,serializeTransaction:()=>fT,serializeTypedData:()=>vT,setErrorConfig:()=>cre,setupKzg:()=>Hfe,sha256:()=>KI,shouldThrow:()=>uH,sidecarsToVersionedHashes:()=>Ufe,signatureToCompactSignature:()=>Zfe,signatureToHex:()=>W3,size:()=>gt,slice:()=>vo,sliceBytes:()=>_4,sliceHex:()=>xa,stringToBytes:()=>zo,stringToHex:()=>ec,stringify:()=>bt,testActions:()=>u_,toBlobSidecars:()=>M0,toBlobs:()=>XI,toBytes:()=>un,toCoinType:()=>Lfe,toEventHash:()=>Nf,toEventSelector:()=>Wc,toEventSignature:()=>Pf,toFunctionHash:()=>Nf,toFunctionSelector:()=>va,toFunctionSignature:()=>Pf,toHex:()=>wr,toPrefixedMessage:()=>xT,toRlp:()=>Vo,transactionType:()=>Q4,trim:()=>bn,universalSignatureValidatorAbi:()=>Fb,universalSignatureValidatorByteCode:()=>f3,validateTypedData:()=>f6,verifyHash:()=>ple,verifyMessage:()=>mle,verifyTypedData:()=>yle,walletActions:()=>f_,webSocket:()=>Afe,weiUnits:()=>Tfe,withCache:()=>L9,withRetry:()=>np,withTimeout:()=>sl,zeroAddress:()=>dm,zeroHash:()=>Nce});var R6=b(()=>{l();fg();Cie();q9();nm();Bie();Rue();Hde();yfe();iH();aH();lH();N6();bfe();xfe();Efe();Cfe();So();t_();ST();Vb();jI();YL();_fe();Qr();tc();nt();J4();PL();Ug();ou();C4();yg();rT();jD();Eb();jU();tl();fs();Lf();OI();zn();p_();QL();Pfe();Nfe();zh();Ofe();L4();a3();gL();lc();rc();p3();wL();Cg();us();xL();Tae();Bf();Dg();iD();Zs();Pae();Gs();Oi();t3();r3();GI();ZI();kfe();Dfe();n3();JD();k9();$ae();b3();Vae();qae();K0();Fn();zL();qs();Xa();Fo();Si();Hh();cD();Xr();mT();Pr();qe();wb();UL();Y9();Mfe();p0();X4();hu();Ab();Qb();rl();gT();Ks();ice();GD();ace();Kw();cce();lce();Ag();uce();fH();$fe();fce();SL();v3();Kb();zfe();T3();P3();XL();NM();Vfe();ile();cle();jfe();w0();RM();VD();Wfe();OM();Kfe();ule();fle();WM();Gfe();JL();hle();gle();wle();so();nl();dT();BM();e9();kM();qL();pT();ET();M4();Ig();z3();xle();Ele();UM()});async function Y3(...e){let t=await fetch(...e);if(!t.ok)throw new Error(`HTTP status code: ${t.status}`,{cause:t});return t}var Di,O6=b(()=>{l();Di=class{constructor({baseUrl:t,clientId:r}){this.baseUrl=t,this.clientId=r}async get({headers:t,signal:r,cache:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"GET",headers:t,signal:r,cache:n})).json()}async getBlob({headers:t,signal:r,...n}){let o=this.createUrl(n);return(await Y3(o,{method:"GET",headers:t,signal:r})).blob()}async post({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"POST",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}async put({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"PUT",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}async delete({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"DELETE",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}createUrl({path:t,params:r}){let n=new URL(t,this.baseUrl);return r&&Object.entries(r).forEach(([o,s])=>{s&&n.searchParams.append(o,s)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:t,...r}){let n=this.createUrl(r);return navigator.sendBeacon(n.toString(),t?JSON.stringify(t):void 0)}}});var J3,gH=b(()=>{l();Un();ha();$n();J3={getFeatureValue(e,t){let r=t?.[e];return r===void 0?Ye.DEFAULT_FEATURES[e]:r},filterSocialsByPlatform(e){if(!e||!e.length)return e;let t=e;return se.isTelegram()&&(se.isIos()&&(t=t.filter(r=>r!=="google")),se.isMac()&&(t=t.filter(r=>r!=="x")),se.isAndroid()&&(t=t.filter(r=>!["facebook","x"].includes(r)))),se.isMobile()&&(t=t.filter(r=>r!=="facebook")),t},isSocialsEnabled(){return Array.isArray(Y.state.features?.socials)&&Y.state.features?.socials.length>0||Array.isArray(Y.state.remoteFeatures?.socials)&&Y.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(Y.state.features?.email||Y.state.remoteFeatures?.email)}}});var Ze,Y,Un=b(()=>{l();Lr();Hn();ha();$n();gH();Ze=rt({features:Ye.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ye.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),Y={state:Ze,subscribeKey(e,t){return Tt(Ze,e,t)},setOptions(e){Object.assign(Ze,e)},setRemoteFeatures(e){if(!e)return;let t={...Ze.remoteFeatures,...e};Ze.remoteFeatures=t,Ze.remoteFeatures?.socials&&(Ze.remoteFeatures.socials=J3.filterSocialsByPlatform(Ze.remoteFeatures.socials)),Ze.features?.pay&&(Ze.remoteFeatures.email=!1,Ze.remoteFeatures.socials=!1)},setFeatures(e){if(!e)return;Ze.features||(Ze.features=Ye.DEFAULT_FEATURES);let t={...Ze.features,...e};Ze.features=t,Ze.features?.pay&&Ze.remoteFeatures&&(Ze.remoteFeatures.email=!1,Ze.remoteFeatures.socials=!1)},setProjectId(e){Ze.projectId=e},setCustomRpcUrls(e){Ze.customRpcUrls=e},setAllWallets(e){Ze.allWallets=e},setIncludeWalletIds(e){Ze.includeWalletIds=e},setExcludeWalletIds(e){Ze.excludeWalletIds=e},setFeaturedWalletIds(e){Ze.featuredWalletIds=e},setTokens(e){Ze.tokens=e},setTermsConditionsUrl(e){Ze.termsConditionsUrl=e},setPrivacyPolicyUrl(e){Ze.privacyPolicyUrl=e},setCustomWallets(e){Ze.customWallets=e},setIsSiweEnabled(e){Ze.isSiweEnabled=e},setIsUniversalProvider(e){Ze.isUniversalProvider=e},setSdkVersion(e){Ze.sdkVersion=e},setMetadata(e){Ze.metadata=e},setDisableAppend(e){Ze.disableAppend=e},setEIP6963Enabled(e){Ze.enableEIP6963=e},setDebug(e){Ze.debug=e},setEnableWalletGuide(e){Ze.enableWalletGuide=e},setEnableAuthLogger(e){Ze.enableAuthLogger=e},setEnableWallets(e){Ze.enableWallets=e},setPreferUniversalLinks(e){Ze.experimental_preferUniversalLinks=e},setSIWX(e){if(e)for(let[t,r]of Object.entries(Ye.SIWX_DEFAULTS))e[t]??=r;Ze.siwx=e},setConnectMethodsOrder(e){Ze.features={...Ze.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){Ze.features={...Ze.features,walletFeaturesOrder:e}},setSocialsOrder(e){Ze.remoteFeatures={...Ze.remoteFeatures,socials:e}},setCollapseWallets(e){Ze.features={...Ze.features,collapseWallets:e}},setEnableEmbedded(e){Ze.enableEmbedded=e},setAllowUnsupportedChain(e){Ze.allowUnsupportedChain=e},setManualWCControl(e){Ze.manualWCControl=e},setEnableNetworkSwitch(e){Ze.enableNetworkSwitch=e},setEnableMobileFullScreen(e){Ze.enableMobileFullScreen=se.isMobile()&&e},setEnableReconnect(e){Ze.enableReconnect=e},setCoinbasePreference(e){Ze.coinbasePreference=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([t,r])=>{r&&(Ze.defaultAccountTypes[t]=r)})},setUniversalProviderConfigOverride(e){Ze.universalProviderConfigOverride=e},getUniversalProviderConfigOverride(){return Ze.universalProviderConfigOverride},getSnapshot(){return Kl(Ze)}}});var ny,ao,lHe,Je,hm=b(()=>{l();Lr();Hn();$n();ny=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ao=rt({...ny}),lHe={state:ao,subscribeKey(e,t){return Tt(ao,e,t)},showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){let t=se.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){ao.message=ny.message,ao.variant=ny.variant,ao.svg=ny.svg,ao.open=ny.open,ao.autoClose=ny.autoClose},_showMessage({message:e,svg:t,variant:r="success",autoClose:n=ny.autoClose}){ao.open?(ao.open=!1,setTimeout(()=>{ao.message=e,ao.variant=r,ao.svg=t,ao.open=!0,ao.autoClose=n},150)):(ao.message=e,ao.variant=r,ao.svg=t,ao.open=!0,ao.autoClose=n)}},Je=lHe});var uHe,Jfe,si,ze,lp=b(()=>{l();Lr();ha();$n();O6();ma();$r();Un();hm();uHe={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Jfe=se.getBlockchainApiUrl(),si=rt({clientId:null,api:new Di({baseUrl:Jfe,clientId:null}),supportedChains:{http:[],ws:[]}}),ze={state:si,async get(e){let{st:t,sv:r}=ze.getSdkProperties(),n=Y.state.projectId,o={...e.params||{},st:t,sv:r,projectId:n};return si.api.get({...e,params:o})},getSdkProperties(){let{sdkType:e,sdkVersion:t}=Y.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{si.supportedChains.http.length||await ze.getSupportedNetworks()}catch{return!1}return si.supportedChains.http.includes(e)},async getSupportedNetworks(){try{let e=await ze.get({path:"v1/supported-chains"});return si.supportedChains=e,e}catch{return si.supportedChains}},async fetchIdentity({address:e}){let t=de.getIdentityFromCacheForAddress(e);if(t)return t;let r=await ze.get({path:`/v1/identity/${e}`,params:{sender:$.state.activeCaipAddress?se.getPlainAddress($.state.activeCaipAddress):void 0}});return de.updateIdentityCache({address:e,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:e,cursor:t,signal:r,cache:n,chainId:o}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};let i=de.getTransactionsCacheForAddress({address:e,chainId:o});if(i)return i;let a=await ze.get({path:`/v1/account/${e}/history`,params:{cursor:t,chainId:o},signal:r,cache:n});return de.updateTransactionsCache({address:e,chainId:o,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:e,userAddress:t,from:r,to:n,gasPrice:o}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:r,to:n,gasPrice:o}}):{quotes:[]}},async fetchSwapTokens({chainId:e}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]}},async getAddressBalance({caipNetworkId:e,address:t}){return si.api.post({path:`/v1?chainId=${e}&projectId=${Y.state.projectId}`,body:{id:"1",jsonrpc:"2.0",method:"getAddressBalance",params:{address:t}}}).then(r=>r.result)},async fetchTokenPrice({addresses:e,caipNetworkId:t=$.state.activeCaipNetwork?.caipNetworkId}){if(!await ze.isNetworkSupported(t))return{fungibles:[]};let n=de.getTokenPriceCacheForAddresses(e);if(n)return n;let o=await si.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:Y.state.projectId},headers:{"Content-Type":"application/json"}});return de.updateTokenPriceCache({addresses:e,timestamp:Date.now(),tokenPrice:o}),o},async fetchSwapAllowance({tokenAddress:e,userAddress:t}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:e}){let{st:t,sv:r}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return ze.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:t,sv:r}})},async generateSwapCalldata({amount:e,from:t,to:r,userAddress:n,disableEstimate:o}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return si.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:Ye.CONVERT_SLIPPAGE_TOLERANCE},projectId:Y.state.projectId,from:t,to:r,userAddress:n,disableEstimate:o}})},async generateApproveCalldata({from:e,to:t,userAddress:r}){let{st:n,sv:o}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ze.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:r,from:e,to:t,st:n,sv:o}})},async getBalance(e,t,r){let{st:n,sv:o}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return Je.showError("Token Balance Unavailable"),{balances:[]};let i=`${t}:${e}`,a=de.getBalanceCacheForCaipAddress(i);if(a)return a;let c=await ze.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:r,st:n,sv:o}});return de.updateBalanceCache({caipAddress:i,balance:c,timestamp:Date.now()}),c},async lookupEnsName(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:e}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return[];let r=$.getAccountData()?.address;return ze.get({path:`/v1/profile/reverse/${e}`,params:{sender:r,apiVersion:"2"}})},async getEnsNameSuggestions(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:e,address:t,message:r,signature:n}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?si.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:r,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:e,partnerUserId:t,defaultNetwork:r,purchaseAmount:n,paymentAmount:o}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?(await si.api.post({path:"/v1/generators/onrampurl",params:{projectId:Y.state.projectId},body:{destinationWallets:e,defaultNetwork:r,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:o}})).url:""},async getOnrampOptions(){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await ze.get({path:"/v1/onramp/options"})}catch{return uHe}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:r,network:n}){try{return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?await si.api.post({path:"/v1/onramp/quote",params:{projectId:Y.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:r,network:n}}):null}catch{return{networkFee:{amount:r,currency:t.id},paymentSubtotal:{amount:r,currency:t.id},paymentTotal:{amount:r,currency:t.id},purchaseAmount:{amount:r,currency:t.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/sessions/${e}`}):[]},async revokeSmartSession(e,t,r){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?si.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:Y.state.projectId},body:{pci:t,signature:r}}):{success:!1}},setClientId(e){si.clientId=e,si.api=new Di({baseUrl:Jfe,clientId:e})}}});var mm=b(()=>{l();g4()});var dHe,fHe,pHe,hHe,gm,Qfe,Xfe=b(()=>{l();Lr();Hn();$n();O6();Un();dHe=Object.freeze({enabled:!0,events:[]}),fHe=new Di({baseUrl:se.getAnalyticsUrl(),clientId:null}),pHe=5,hHe=60*1e3,gm=rt({...dHe}),Qfe={state:gm,subscribeKey(e,t){return Tt(gm,e,t)},async sendError(e,t){if(!gm.enabled)return;let r=Date.now();if(gm.events.filter(s=>{let i=new Date(s.properties.timestamp||"").getTime();return r-i=pHe)return;let o={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:new Date().toISOString()}};gm.events.push(o);try{if(typeof window>"u")return;let{projectId:s,sdkType:i,sdkVersion:a}=Y.state;await fHe.post({path:"/e",params:{projectId:s,st:i,sv:a||"html-wagmi-4.2.2"},body:{eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){gm.enabled=!0},disable(){gm.enabled=!1},clearEvents(){gm.events=[]}}});function epe(e,t){let r="";try{e instanceof Error?r=e.message:typeof e=="string"?r=e:typeof e=="object"&&e!==null?Object.keys(e).length===0?r="Unknown error":r=e?.message||JSON.stringify(e):r=String(e)}catch(o){r="Unknown error",console.error("Error parsing error message",o)}let n=e instanceof hc?e:new hc(r,t,e);throw Qfe.sendError(n,n.category),n}function vr(e,t="INTERNAL_SDK_ERROR"){let r={};return Object.keys(e).forEach(n=>{let o=e[n];if(typeof o=="function"){let s=o;o.constructor.name==="AsyncFunction"?s=async(...i)=>{try{return await o(...i)}catch(a){return epe(a,t)}}:s=(...i)=>{try{return o(...i)}catch(a){return epe(a,t)}},r[n]=s}else r[n]=o}),r}var hc,gs=b(()=>{l();Xfe();hc=class e extends Error{constructor(t,r,n){super(t),this.originalName="AppKitError",this.name="AppKitError",this.category=r,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,e.prototype);let o=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){let s=n.stack,i=s.indexOf(` +`);if(i>-1){let a=s.substring(i+1);this.stack=`${this.name}: ${this.message} +${a}`,o=!0}}o||(Error.captureStackTrace?Error.captureStackTrace(this,e):this.stack||(this.stack=`${this.name}: ${this.message}`))}}});var Pa,mHe,Wn,y_=b(()=>{l();Lr();Hn();gs();Pa=rt({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),mHe={state:Pa,subscribeNetworkImages(e){return Dt(Pa.networkImages,()=>e(Pa.networkImages))},subscribeKey(e,t){return Tt(Pa,e,t)},subscribe(e){return Dt(Pa,()=>e(Pa))},setWalletImage(e,t){Pa.walletImages[e]=t},setNetworkImage(e,t){Pa.networkImages[e]=t},setChainImage(e,t){Pa.chainImages[e]=t},setConnectorImage(e,t){Pa.connectorImages={...Pa.connectorImages,[e]:t}},setTokenImage(e,t){Pa.tokenImages[e]=t},setCurrencyImage(e,t){Pa.currencyImages[e]=t}},Wn=vr(mHe)});var tpe,B6,St,yH=b(()=>{l();Lr();ut();Cu();y_();Un();tpe={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:"",ton:"20f673c0-095e-49b2-07cf-eb5049dcf600"},B6=rt({networkImagePromises:{},tokenImagePromises:{}}),St={async fetchWalletImage(e){if(e)return await ge._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;let t=this.getNetworkImageById(e);return t||(B6.networkImagePromises[e]||(B6.networkImagePromises[e]=ge._fetchNetworkImage(e)),await B6.networkImagePromises[e],this.getNetworkImageById(e))},async fetchTokenImage(e){if(e)return B6.tokenImagePromises[e]||(B6.tokenImagePromises[e]=ge._fetchTokenImage(e)),await B6.tokenImagePromises[e],this.getTokenImage(e)},getWalletImageById(e){if(e)return Wn.state.walletImages[e]},getWalletImage(e){if(e?.image_url)return e?.image_url;if(e?.image_id)return Wn.state.walletImages[e.image_id]},getNetworkImage(e){if(e?.assets?.imageUrl)return e?.assets?.imageUrl;if(e?.assets?.imageId)return Wn.state.networkImages[e.assets.imageId]},getNetworkImageById(e){if(e)return Wn.state.networkImages[e]},getConnectorImage(e){if(e?.imageUrl)return e.imageUrl;if(e?.info?.icon)return e.info.icon;if(e?.imageId)return Wn.state.connectorImages[e.imageId]},getChainImage(e){return Wn.state.networkImages[tpe[e]]},getTokenImage(e){if(e)return Wn.state.tokenImages[e]},getWalletImageUrl(e){if(!e)return"";let{projectId:t,sdkType:r,sdkVersion:n}=Y.state,o=new URL(`${Z.W3M_API_URL}/getWalletImage/${e}`);return o.searchParams.set("projectId",t),o.searchParams.set("st",r),o.searchParams.set("sv",n),o.toString()},getAssetImageUrl(e){if(!e)return"";let{projectId:t,sdkType:r,sdkVersion:n}=Y.state,o=new URL(`${Z.W3M_API_URL}/public/getAssetImage/${e}`);return o.searchParams.set("projectId",t),o.searchParams.set("st",r),o.searchParams.set("sv",n),o.toString()},getChainNamespaceImageUrl(e){return this.getAssetImageUrl(tpe[e])},async getImageByToken(e,t){if(e==="native"){let n=Z.NATIVE_IMAGE_IDS_BY_NAMESPACE[t]??null;return n?St.fetchNetworkImage(n):void 0}let[,r]=Object.entries(Z.TOKEN_SYMBOLS_BY_ADDRESS).find(([n])=>n.toLowerCase()===e.toLowerCase())??[];if(r)return St.fetchTokenImage(r)}}});var Na,rpe,wH=b(()=>{l();ut();$r();Na={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},rpe={handleMobileDeeplinkRedirect(e,t){let r=window.location.href,n=encodeURIComponent(r);if(e===Na.PHANTOM.id&&!("phantom"in window)){let o=r.startsWith("https")?"https":"http",s=r.split("/")[2],i=encodeURIComponent(`${o}://${s}`);window.location.href=`${Na.PHANTOM.url}/ul/browse/${n}?ref=${i}`}if(e===Na.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Na.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),t===Z.CHAIN.SOLANA&&e===Na.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Na.COINBASE.url}/dapp?cb_url=${n}`),t===Z.CHAIN.BITCOIN&&e===Na.BINANCE.id&&!("binancew3w"in window)){let o=$.state.activeCaipNetwork,s=window.btoa("/pages/browser/index"),i=window.btoa(`url=${n}&defaultChainId=${o?.id??1}`),a=new URL(Na.BINANCE.deeplink);a.searchParams.set("appId",Na.BINANCE.appId),a.searchParams.set("startPagePath",s),a.searchParams.set("startPageQuery",i);let c=new URL(Na.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}}});var gHe,yHe,wHe,bHe,npe,En,Ae,mc=b(()=>{l();Lr();$n();O6();$r();Un();gHe=se.getAnalyticsUrl(),yHe=new Di({baseUrl:gHe,clientId:null}),wHe=["MODAL_CREATED"],bHe=45,npe=1e3*10,En=rt({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),Ae={state:En,subscribe(e){return Dt(En,()=>e(En))},getSdkProperties(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t,sv:r||"html-wagmi-4.2.2"}},shouldFlushEvents(){let e=JSON.stringify(En.pendingEvents).length/1024>bHe,t=En.lastFlush+npe"u")return;let r=$.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t,properties:{..."properties"in e.data?e.data.properties:{},caipNetworkId:r}}}),En.reportedErrors.FORBIDDEN=!1,Ae.shouldFlushEvents()&&Ae._submitPendingEvents()}catch(t){console.warn("_setPendingEvent",t)}},sendEvent(e){En.timestamp=Date.now(),En.data=e;let t=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];(Y.state.features?.analytics||t.includes(e.event))&&Ae._setPendingEvent(En),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(e){En.walletImpressions.push(e)},_transformPendingEventsForBatch(e){try{return e.filter(t=>t.props.event!=="WALLET_IMPRESSION_V2")}catch{return e}},_submitPendingEvents(){if(En.lastFlush=Date.now(),!(En.pendingEvents.length===0&&En.walletImpressions.length===0))try{let e=Ae._transformPendingEventsForBatch(En.pendingEvents);En.walletImpressions.length&&e.push({eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...En.walletImpressions]}}),yHe.sendBeacon({path:"/batch",params:Ae.getSdkProperties(),body:e}),En.reportedErrors.FORBIDDEN=!1,En.pendingEvents=[],En.walletImpressions=[]}catch{En.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){En.subscribedToVisibilityChange||typeof document>"u"||(En.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",()=>{document.visibilityState==="hidden"&&Ae._submitPendingEvents()}),document?.addEventListener?.("freeze",()=>{Ae._submitPendingEvents()}),window?.addEventListener?.("pagehide",()=>{Ae._submitPendingEvents()}),setInterval(()=>{Ae._submitPendingEvents()},npe))}}});var xHe,ii,vHe,ope,EHe,mt,ge,Cu=b(()=>{l();Lr();Hn();ut();yH();$n();O6();wH();ma();y_();$r();To();mc();Un();xHe=se.getApiUrl(),ii=new Di({baseUrl:xHe,clientId:null}),vHe=40,ope=4,EHe=20,mt=rt({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[],plan:{tier:"none",hasExceededUsageLimit:!1,limits:{isAboveRpcLimit:!1,isAboveMauLimit:!1}}}),ge={state:mt,subscribeKey(e,t){return Tt(mt,e,t)},_getSdkProperties(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t||"appkit",sv:r||"html-wagmi-4.2.2"}},_filterOutExtensions(e){return Y.state.isUniversalProvider?e.filter(t=>!!(t.mobile_link||t.desktop_link||t.webapp_link)):e},async _fetchWalletImage(e){let t=`${ii.baseUrl}/getWalletImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setWalletImage(e,URL.createObjectURL(r))},async _fetchNetworkImage(e){let t=`${ii.baseUrl}/public/getAssetImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setNetworkImage(e,URL.createObjectURL(r))},async _fetchConnectorImage(e){let t=`${ii.baseUrl}/public/getAssetImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setConnectorImage(e,URL.createObjectURL(r))},async _fetchCurrencyImage(e){let t=`${ii.baseUrl}/public/getCurrencyImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setCurrencyImage(e,URL.createObjectURL(r))},async _fetchTokenImage(e){let t=`${ii.baseUrl}/public/getTokenImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setTokenImage(e,URL.createObjectURL(r))},_filterWalletsByPlatform(e){let t=e.length,r=se.isMobile()?e?.filter(o=>o.mobile_link||o.webapp_link?!0:Object.values(Na).map(i=>i.id).includes(o.id)):e,n=t-r.length;return{filteredWallets:r,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await ii.get({path:"/appkit/v1/config",params:ge._getSdkProperties()})).features},async fetchUsage(){try{let e=await ii.get({path:"/appkit/v1/project-limits",params:ge._getSdkProperties()}),{tier:t,isAboveMauLimit:r,isAboveRpcLimit:n}=e.planLimits,o=t==="starter",s=r||n;ge.state.plan={tier:t,hasExceededUsageLimit:o&&s,limits:{isAboveRpcLimit:n,isAboveMauLimit:r}}}catch(e){console.warn("Failed to fetch usage",e)}},async fetchAllowedOrigins(){try{let{allowedOrigins:e}=await ii.get({path:"/projects/v1/origins",params:ge._getSdkProperties()});return e}catch(e){if(e instanceof Error&&e.cause instanceof Response){let t=e.cause.status;if(t===Z.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:e});if(t>=Z.HTTP_STATUS_CODES.SERVER_ERROR&&t<600)throw new Error("SERVER_ERROR",{cause:e});return[]}return[]}},async fetchNetworkImages(){let t=$.getAllRequestedCaipNetworks()?.map(({assets:r})=>r?.imageId).filter(Boolean).filter(r=>!St.getNetworkImageById(r));t&&await Promise.allSettled(t.map(r=>ge._fetchNetworkImage(r)))},async fetchConnectorImages(){let{connectors:e}=re.state,t=e.map(({imageId:r})=>r).filter(Boolean);await Promise.allSettled(t.map(r=>ge._fetchConnectorImage(r)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(t=>ge._fetchCurrencyImage(t)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(t=>ge._fetchTokenImage(t)))},async fetchWallets(e){let t=e.exclude??[];ge._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(Na).map(i=>i.id));let n=await ii.get({path:"/getWallets",params:{...ge._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}}),{filteredWallets:o,mobileFilteredOutWalletsLength:s}=ge._filterWalletsByPlatform(n?.data);return{data:o||[],count:n?.count,mobileFilteredOutWalletsLength:s}},async prefetchWalletRanks(){let e=re.state.connectors;if(!e?.length)return;let t={page:1,entries:20,badge:"certified"};if(t.names=e.map(o=>o.name).join(","),$.state.activeChain===Z.CHAIN.EVM){let o=[...e.flatMap(s=>s.connectors?.map(i=>i.info?.rdns)||[]),...e.map(s=>s.info?.rdns)].filter(s=>typeof s=="string"&&s.length>0);o.length&&(t.rdns=o.join(","))}let{data:r}=await ge.fetchWallets(t);mt.explorerWallets=r,re.extendConnectorsWithExplorerWallets(r);let n=$.getRequestedCaipNetworkIds().join(",");mt.explorerFilteredWallets=r.filter(o=>o.chains?.some(s=>n.includes(s)))},async fetchFeaturedWallets(){let{featuredWalletIds:e}=Y.state;if(e?.length){let t={...ge._getSdkProperties(),page:1,entries:e?.length??ope,include:e},{data:r}=await ge.fetchWallets(t),n=[...r].sort((s,i)=>e.indexOf(s.id)-e.indexOf(i.id)),o=n.map(s=>s.image_id).filter(Boolean);await Promise.allSettled(o.map(s=>ge._fetchWalletImage(s))),mt.featured=n,mt.allFeatured=n}},async fetchRecommendedWallets(){try{mt.isFetchingRecommendedWallets=!0;let{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:r}=Y.state,n=[...t??[],...r??[]].filter(Boolean),o=$.getRequestedCaipNetworkIds().join(","),s={page:1,entries:ope,include:e,exclude:n,chains:o},{data:i,count:a}=await ge.fetchWallets(s),c=de.getRecentWallets(),u=i.map(f=>f.image_id).filter(Boolean),d=c.map(f=>f.image_id).filter(Boolean);await Promise.allSettled([...u,...d].map(f=>ge._fetchWalletImage(f))),mt.recommended=i,mt.allRecommended=i,mt.count=a??0}catch{}finally{mt.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){let{includeWalletIds:t,excludeWalletIds:r,featuredWalletIds:n}=Y.state,o=$.getRequestedCaipNetworkIds().join(","),s=[...mt.recommended.map(({id:f})=>f),...r??[],...n??[]].filter(Boolean),i={page:e,entries:vHe,include:t,exclude:s,chains:o},{data:a,count:c,mobileFilteredOutWalletsLength:u}=await ge.fetchWallets(i);mt.mobileFilteredOutWalletsLength=u+(mt.mobileFilteredOutWalletsLength??0);let d=a.slice(0,EHe).map(f=>f.image_id).filter(Boolean);await Promise.allSettled(d.map(f=>ge._fetchWalletImage(f))),mt.wallets=se.uniqueBy([...mt.wallets,...ge._filterOutExtensions(a)],"id").filter(f=>f.chains?.some(p=>o.includes(p))),mt.count=c>mt.count?c:mt.count,mt.page=e},async initializeExcludedWallets({ids:e}){let t={page:1,entries:e.length,include:e},{data:r}=await ge.fetchWallets(t);r&&r.forEach(n=>{mt.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:e,badge:t}){let{includeWalletIds:r,excludeWalletIds:n}=Y.state,o=$.getRequestedCaipNetworkIds().join(",");mt.search=[];let s={page:1,entries:100,search:e?.trim(),badge_type:t,include:r,exclude:n,chains:o},{data:i}=await ge.fetchWallets(s);Ae.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});let a=i.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>ge._fetchWalletImage(c)),se.wait(300)]),mt.search=ge._filterOutExtensions(i)},initPromise(e,t){let r=mt.promises[e];return r||(mt.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:r=!0,fetchNetworkImages:n=!0,fetchWalletRanks:o=!0}={}){let s=[e&&ge.initPromise("connectorImages",ge.fetchConnectorImages),t&&ge.initPromise("featuredWallets",ge.fetchFeaturedWallets),r&&ge.initPromise("recommendedWallets",ge.fetchRecommendedWallets),n&&ge.initPromise("networkImages",ge.fetchNetworkImages),o&&ge.initPromise("walletRanks",ge.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(s)},prefetchAnalyticsConfig(){Y.state.features?.analytics&&ge.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{let{isAnalyticsEnabled:e}=await ii.get({path:"/getAnalyticsConfig",params:ge._getSdkProperties()});Y.setFeatures({analytics:e})}catch{Y.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length){mt.featured=mt.allFeatured,mt.recommended=mt.allRecommended;return}let t=$.getRequestedCaipNetworkIds().join(",");mt.featured=mt.allFeatured.filter(r=>r.chains?.some(n=>t.includes(n))),mt.recommended=mt.allRecommended.filter(r=>r.chains?.some(n=>t.includes(n))),mt.filteredWallets=mt.wallets.filter(r=>r.chains?.some(n=>t.includes(n)))},clearFilterByNamespaces(){mt.filteredWallets=[]},setFilterByNamespace(e){if(!e){mt.featured=mt.allFeatured,mt.recommended=mt.allRecommended;return}let t=$.getRequestedCaipNetworkIds().join(",");mt.featured=mt.allFeatured.filter(r=>r.chains?.some(n=>t.includes(n))),mt.recommended=mt.allRecommended.filter(r=>r.chains?.some(n=>t.includes(n))),mt.filteredWallets=mt.wallets.filter(r=>r.chains?.some(n=>t.includes(n)))}}});var ys,bH=b(()=>{l();ut();Cu();ai();To();Un();w_();ha();$n();ma();ys={filterOutDuplicatesByRDNS(e){let t=Y.state.enableEIP6963?re.state.connectors:[],r=de.getRecentWallets(),n=t.map(a=>a.info?.rdns).filter(Boolean),o=r.map(a=>a.rdns).filter(Boolean),s=n.concat(o);if(s.includes("io.metamask.mobile")&&se.isMobile()){let a=s.indexOf("io.metamask.mobile");s[a]="io.metamask"}return e.filter(a=>!(a?.rdns&&s.includes(String(a.rdns))||!a?.rdns&&t.some(u=>u.name===a.name)))},filterOutDuplicatesByIds(e){let t=re.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"||a.type==="MULTI_CHAIN"),r=de.getRecentWallets(),n=t.map(a=>a.explorerId||a.explorerWallet?.id||a.id),o=r.map(a=>a.id),s=n.concat(o);return e.filter(a=>!s.includes(a?.id))},filterOutDuplicateWallets(e){let t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){let{connectors:t}=re.state,{featuredWalletIds:r}=Y.state,n=t.filter(i=>i.type==="ANNOUNCED").reduce((i,a)=>(a.info?.rdns&&(i[a.info.rdns]=!0),i),{});return e.map(i=>({...i,installed:!!i.rdns&&!!n[i.rdns??""]})).sort((i,a)=>{let c=Number(a.installed)-Number(i.installed);if(c!==0)return c;if(r?.length){let u=r.indexOf(i.id),d=r.indexOf(a.id);if(u!==-1&&d!==-1)return u-d;if(u!==-1)return-1;if(d!==-1)return 1}return 0})},getConnectOrderMethod(e,t){let r=e?.connectMethodsOrder||Y.state.features?.connectMethodsOrder,n=t||re.state.connectors;if(r)return r;let{injected:o,announced:s}=Dn.getConnectorsByType(n,ge.state.recommended,ge.state.featured),i=o.filter(Dn.showConnector),a=s.filter(Dn.showConnector);return i.length||a.length?["wallet","email","social"]:Ye.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){let t=!!e.rdns&&ge.state.excludedWallets.some(n=>n.rdns===e.rdns),r=!!e.name&&ge.state.excludedWallets.some(n=>l4.isLowerCaseMatch(n.name,e.name));return t||r},markWalletsWithDisplayIndex(e){return e.map((t,r)=>({...t,display_index:r}))},filterWalletsByWcSupport(e){return ee.state.wcBasic?e.filter(t=>t.supports_wc):se.isMobile()?e.filter(t=>t.supports_wc||Ye.MANDATORY_WALLET_IDS_ON_MOBILE.includes(t.id)):e},getWalletConnectWallets(e){let t=[...ge.state.featured,...ge.state.recommended];ge.state.filteredWallets?.length>0?t.push(...ge.state.filteredWallets):t.push(...e);let r=se.uniqueBy(t,"id"),n=ys.markWalletsAsInstalled(r),o=ys.filterWalletsByWcSupport(n);return ys.markWalletsWithDisplayIndex(o)}}});var Dn,w_=b(()=>{l();ut();Cu();$r();ai();To();Un();$n();gH();ma();bH();Dn={getConnectorsByType(e,t,r){let{customWallets:n}=Y.state,o=de.getRecentWallets(),s=ys.filterOutDuplicateWallets(t),i=ys.filterOutDuplicateWallets(r),a=e.filter(f=>f.type==="MULTI_CHAIN"),c=e.filter(f=>f.type==="ANNOUNCED"),u=e.filter(f=>f.type==="INJECTED"),d=e.filter(f=>f.type==="EXTERNAL");return{custom:n,recent:o,external:d,multiChain:a,announced:c,injected:u,recommended:s,featured:i}},showConnector(e){let t=e.info?.rdns,r=!!t&&ge.state.excludedWallets.some(o=>!!o.rdns&&o.rdns===t),n=!!e.name&&ge.state.excludedWallets.some(o=>l4.isLowerCaseMatch(o.name,e.name));return!(e.type==="INJECTED"&&(e.name==="Browser Wallet"&&(!se.isMobile()||se.isMobile()&&!t&&!ee.checkInstalled())||r||n)||(e.type==="ANNOUNCED"||e.type==="EXTERNAL")&&(r||n))},getIsConnectedWithWC(){return Array.from($.state.chains.values()).some(r=>re.getConnectorId(r.namespace)===Z.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:e,featured:t,custom:r,recent:n,announced:o,injected:s,multiChain:i,external:a,overriddenConnectors:c=Y.state.features?.connectorTypeOrder??[]}){let d=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...s,...o,...i].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:r&&r.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter(y=>y.isEnabled),f=new Set(d.map(y=>y.type)),p=c.filter(y=>f.has(y)).map(y=>({type:y,isEnabled:!0})),h=d.filter(({type:y})=>!p.some(({type:x})=>x===y));return Array.from(new Set([...p,...h].map(({type:y})=>y)))},sortConnectorsByExplorerWallet(e){return[...e].sort((t,r)=>t.explorerWallet&&r.explorerWallet?(t.explorerWallet.order??0)-(r.explorerWallet.order??0):t.explorerWallet?-1:r.explorerWallet?1:0)},getPriority(e){return e.id===Z.CONNECTOR_ID.BASE_ACCOUNT?0:e.id===Z.CONNECTOR_ID.COINBASE||e.id===Z.CONNECTOR_ID.COINBASE_SDK?1:2},sortConnectorsByPriority(e){return[...e].sort((t,r)=>Dn.getPriority(t)-Dn.getPriority(r))},getAuthName({email:e,socialUsername:t,socialProvider:r}){return t?r&&r==="discord"&&t.endsWith("0")?t.slice(0,-1):t:e.length>30?`${e.slice(0,-3)}...`:e},async fetchProviderData(e){try{if(e.name==="Browser Wallet"&&!se.isMobile())return{accounts:[],chainId:void 0};if(e.id===Z.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};let[t,r]=await Promise.all([e.provider?.request({method:"eth_accounts"}),e.provider?.request({method:"eth_chainId"}).then(n=>Number(n))]);return{accounts:t,chainId:r}}catch(t){return console.warn(`Failed to fetch provider data for ${e.name}`,t),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(e){let t=de.getRecentWallets(),r=re.state.connectors.map(i=>i.info?.rdns).filter(Boolean),n=t.map(i=>i.rdns).filter(Boolean),o=r.concat(n);if(o.includes("io.metamask.mobile")&&se.isMobile()){let i=o.indexOf("io.metamask.mobile");o[i]="io.metamask"}return e.filter(i=>!o.includes(String(i?.rdns)))},hasWalletConnector(e){return re.state.connectors.some(t=>t.id===e.id||t.name===e.name)},isWalletCompatibleWithCurrentChain(e){let t=$.state.activeChain;return t&&e.chains?e.chains.some(r=>{let n=r.split(":")[0];return t===n}):!0},getFilteredRecentWallets(){return de.getRecentWallets().filter(r=>!ys.isExcluded(r)).filter(r=>!this.hasWalletConnector(r)).filter(r=>this.isWalletCompatibleWithCurrentChain(r))},getCappedRecommendedWallets(e){let{connectors:t}=re.state,{customWallets:r,featuredWalletIds:n}=Y.state,o=t.find(T=>T.id==="walletConnect"),s=t.filter(T=>T.type==="INJECTED"||T.type==="ANNOUNCED"||T.type==="MULTI_CHAIN");if(!o&&!s.length&&!r?.length)return[];let i=J3.isEmailEnabled(),a=J3.isSocialsEnabled(),c=s.filter(T=>T.name!=="Browser Wallet"&&T.name!=="WalletConnect"),u=n?.length||0,d=r?.length||0,f=c.length||0,p=i?1:0,h=a?1:0,y=u+d+f+p+h,x=Math.max(0,4-y);return x<=0?[]:ys.filterOutDuplicateWallets(e).slice(0,x)},processConnectorsByType(e,t=!0){let r=Dn.sortConnectorsByExplorerWallet([...e]);return t?r.filter(Dn.showConnector):r},connectorList(){let e=Dn.getConnectorsByType(re.state.connectors,ge.state.recommended,ge.state.featured),t=this.processConnectorsByType(e.announced.filter(h=>h.id!=="walletConnect")),r=this.processConnectorsByType(e.injected),n=this.processConnectorsByType(e.multiChain.filter(h=>h.name!=="WalletConnect"),!1),o=e.custom,s=e.recent,i=this.processConnectorsByType(e.external.filter(h=>h.id!==Z.CONNECTOR_ID.COINBASE_SDK&&h.id!==Z.CONNECTOR_ID.BASE_ACCOUNT)),a=e.recommended,c=e.featured,u=Dn.getConnectorTypeOrder({custom:o,recent:s,announced:t,injected:r,multiChain:n,recommended:a,featured:c,external:i}),d=re.state.connectors.find(h=>h.id==="walletConnect"),f=se.isMobile(),p=[];for(let h of u)switch(h){case"walletConnect":{!f&&d&&p.push({kind:"connector",subtype:"walletConnect",connector:d});break}case"recent":{Dn.getFilteredRecentWallets().forEach(w=>p.push({kind:"wallet",subtype:"recent",wallet:w}));break}case"injected":{n.forEach(y=>p.push({kind:"connector",subtype:"multiChain",connector:y})),t.forEach(y=>p.push({kind:"connector",subtype:"announced",connector:y})),r.forEach(y=>p.push({kind:"connector",subtype:"injected",connector:y}));break}case"featured":{c.forEach(y=>p.push({kind:"wallet",subtype:"featured",wallet:y}));break}case"custom":{Dn.getFilteredCustomWallets(o??[]).forEach(w=>p.push({kind:"wallet",subtype:"custom",wallet:w}));break}case"external":{i.forEach(y=>p.push({kind:"connector",subtype:"external",connector:y}));break}case"recommended":{Dn.getCappedRecommendedWallets(a).forEach(w=>p.push({kind:"wallet",subtype:"recommended",wallet:w}));break}default:console.warn(`Unknown connector type: ${h}`)}return p},hasInjectedConnectors(){return re.state.connectors.filter(e=>(e.type==="INJECTED"||e.type==="ANNOUNCED"||e.type==="MULTI_CHAIN")&&e.name!=="Browser Wallet"&&e.name!=="WalletConnect").length}}});var AHe,pr,CHe,J,gc=b(()=>{l();Lr();Hn();gs();Cu();$r();To();up();Un();AHe=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],pr=rt({view:"Connect",history:["Connect"],transactionStack:[]}),CHe={state:pr,subscribeKey(e,t){return Tt(pr,e,t)},pushTransactionStack(e){pr.transactionStack.push(e)},popTransactionStack(e){let t=pr.transactionStack.pop();if(!t)return;let{onSuccess:r,onError:n,onCancel:o}=t;switch(e){case"success":r?.();break;case"error":n?.(),J.goBack();break;case"cancel":o?.(),J.goBack();break;default:}},push(e,t){let r=e,n=t;ge.state.plan.hasExceededUsageLimit&&AHe.includes(e)&&(r="UsageExceeded",n=void 0),r!==pr.view&&(pr.view=r,pr.history.push(r),pr.data=n)},reset(e,t){pr.view=e,pr.history=[e],pr.data=t},replace(e,t){pr.history.at(-1)===e||(pr.view=e,pr.history[pr.history.length-1]=e,pr.data=t)},goBack(){let e=$.state.activeCaipAddress,t=J.state.view==="ConnectingFarcaster",r=!e&&t;if(pr.history.length>1){pr.history.pop();let[n]=pr.history.slice(-1);n&&(e&&n==="Connect"?pr.view="Account":pr.view=n)}else De.close();pr.data?.wallet&&(pr.data.wallet=void 0),pr.data?.redirectView&&(pr.data.redirectView=void 0),setTimeout(()=>{if(r){$.setAccountProp("farcasterUrl",void 0,$.state.activeChain);let n=re.getAuthConnector();n?.provider?.reload();let o=Kl(Y.state);n?.provider?.syncDappData?.({metadata:o.metadata,sdkVersion:o.sdkVersion,projectId:o.projectId,sdkType:o.sdkType})}},100)},goBackToIndex(e){if(pr.history.length>1){pr.history=pr.history.slice(0,e+1);let[t]=pr.history.slice(-1);t&&(pr.view=t)}},goBackOrCloseModal(){J.state.history.length>1?J.goBack():De.close()}},J=vr(CHe)});var dp,xH,nn,vH=b(()=>{l();Lr();ut();gs();To();dp=rt({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),xH={state:dp,subscribe(e){return Dt(dp,()=>e(dp))},setThemeMode(e){dp.themeMode=e;try{let t=re.getAuthConnector();if(t){let r=xH.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:r,w3mThemeVariables:Y1(r,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){dp.themeVariables={...dp.themeVariables,...e};try{let t=re.getAuthConnector();if(t){let r=xH.getSnapshot().themeVariables;t.provider.syncTheme({themeVariables:r,w3mThemeVariables:Y1(dp.themeVariables,dp.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Kl(dp)}},nn=vr(xH)});var spe,SHe,Kt,IHe,re,To=b(()=>{l();Lr();Hn();ut();mm();yc();w_();wH();ma();gs();Cu();$r();up();Un();gc();vH();spe=Object.fromEntries(sI.map(e=>[e,void 0])),SHe=Object.fromEntries(sI.map(e=>[e,!0])),Kt=rt({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:spe,filterByNamespaceMap:SHe}),IHe={state:Kt,subscribe(e){return Dt(Kt,()=>{e(Kt)})},subscribeKey(e,t){return Tt(Kt,e,t)},initialize(e){e.forEach(t=>{let r=de.getConnectedConnectorId(t);r&&re.setConnectorId(r,t)})},setActiveConnector(e){e&&(Kt.activeConnector=vf(e))},setConnectors(e){e.filter(o=>!Kt.allConnectors.some(s=>s.id===o.id&&re.getConnectorName(s.name)===re.getConnectorName(o.name)&&s.chain===o.chain)).forEach(o=>{o.type!=="MULTI_CHAIN"&&Kt.allConnectors.push(vf(o))});let r=re.getEnabledNamespaces(),n=re.getEnabledConnectors(r);Kt.connectors=re.mergeMultiChainConnectors(n)},filterByNamespaces(e){Object.keys(Kt.filterByNamespaceMap).forEach(t=>{Kt.filterByNamespaceMap[t]=!1}),e.forEach(t=>{Kt.filterByNamespaceMap[t]=!0}),re.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){Kt.filterByNamespaceMap[e]=t,re.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){let e=re.getEnabledNamespaces(),t=re.getEnabledConnectors(e),r=re.areAllNamespacesEnabled();Kt.connectors=re.mergeMultiChainConnectors(t),r?ge.clearFilterByNamespaces():ge.filterByNamespaces(e)},getEnabledNamespaces(){return Object.entries(Kt.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e)},getEnabledConnectors(e){return Kt.allConnectors.filter(t=>e.includes(t.chain))},areAllNamespacesEnabled(){return Object.values(Kt.filterByNamespaceMap).every(e=>e)},mergeMultiChainConnectors(e){let t=re.generateConnectorMapByName(e),r=[];return t.forEach(n=>{let o=n[0],s=o?.id===Z.CONNECTOR_ID.AUTH;n.length>1&&o?r.push({name:o.name,imageUrl:o.imageUrl,imageId:o.imageId,connectors:[...n],type:s?"AUTH":"MULTI_CHAIN",chain:"eip155",id:o?.id||""}):o&&r.push(o)}),r},generateConnectorMapByName(e){let t=new Map;return e.forEach(r=>{let{name:n}=r,o=re.getConnectorName(n);if(!o)return;let s=t.get(o)||[];s.find(a=>a.chain===r.chain)||s.push(r),t.set(o,s)}),t},getConnectorName(e){return e&&({"Trust Wallet":"Trust"}[e]||e)},getUniqueConnectorsByName(e){let t=[];return e.forEach(r=>{t.find(n=>n.chain===r.chain)||t.push(r)}),t},addConnector(e){if(e.id===Z.CONNECTOR_ID.AUTH){let t=e,r=Kl(Y.state),n=nn.getSnapshot().themeMode,o=nn.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType}),t?.provider?.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Y1(o,n)}),re.setConnectors([e])}else re.setConnectors([e])},getAuthConnector(e){let t=e||$.state.activeChain,r=Kt.connectors.find(n=>n.id===Z.CONNECTOR_ID.AUTH);if(r)return r?.connectors?.length?r.connectors.find(o=>o.chain===t):r},getAnnouncedConnectorRdns(){return Kt.connectors.filter(e=>e.type==="ANNOUNCED").map(e=>e.info?.rdns)},getConnectorById(e){return Dn.sortConnectorsByPriority(Kt.allConnectors).find(r=>r.id===e)},getConnector({id:e,namespace:t}){let r=t||$.state.activeChain,n=Kt.allConnectors.filter(i=>i.chain===r);return Dn.sortConnectorsByPriority(n).find(i=>i.id===e||i.explorerId===e)},syncIfAuthConnector(e){if(e.id!=="AUTH")return;let t=e,r=Kl(Y.state),n=nn.getSnapshot().themeMode,o=nn.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,sdkType:r.sdkType,projectId:r.projectId}),t.provider.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Y1(o,n)})},getConnectorsByNamespace(e){let t=Kt.allConnectors.filter(r=>r.chain===e);return re.mergeMultiChainConnectors(t)},canSwitchToSmartAccount(e){return $.checkIfSmartAccountEnabled()&&Fr(e)===Kr.ACCOUNT_TYPES.EOA},selectWalletConnector(e){let t=J.state.data?.redirectView,r=$.state.activeChain,n=r?re.getConnector({id:e.id,namespace:r}):void 0;rpe.handleMobileDeeplinkRedirect(n?.explorerId||e.id,$.state.activeChain),n?J.push("ConnectingExternal",{connector:n,wallet:e,redirectView:t}):J.push("ConnectingWalletConnect",{wallet:e,redirectView:t})},getConnectors(e){return e?re.getConnectorsByNamespace(e):re.mergeMultiChainConnectors(Kt.allConnectors)},setFilterByNamespace(e){Kt.filterByNamespace=e,Kt.connectors=re.getConnectors(e),ge.setFilterByNamespace(e)},setConnectorId(e,t){e&&(Kt.activeConnectorIds={...Kt.activeConnectorIds,[t]:e},de.setConnectedConnectorId(t,e))},removeConnectorId(e){Kt.activeConnectorIds={...Kt.activeConnectorIds,[e]:void 0},de.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return Kt.activeConnectorIds[e]},isConnected(e){return e?!!Kt.activeConnectorIds[e]:Object.values(Kt.activeConnectorIds).some(t=>!!t)},resetConnectorIds(){Kt.activeConnectorIds={...spe}},extendConnectorsWithExplorerWallets(e){Kt.allConnectors.forEach(n=>{let o=e.find(s=>s.id===n.id||s.rdns&&s.rdns===n.info?.rdns);o&&(n.explorerWallet=o)});let t=re.getEnabledNamespaces(),r=re.getEnabledConnectors(t);Kt.connectors=re.mergeMultiChainConnectors(r)},async connect(e={}){let{namespace:t}=e;return re.setFilterByNamespace(t),J.push("Connect",{addWalletForNamespace:t}),new Promise((r,n)=>{if(t){let o=$.subscribeChainProp("accountState",i=>{i?.caipAddress&&(r({caipAddress:i?.caipAddress}),o())},t),s=De.subscribeKey("open",i=>{i||(n(new Error("Modal closed")),s())})}else{let o=$.subscribeKey("activeCaipAddress",i=>{i&&(r({caipAddress:i}),o())}),s=De.subscribeKey("open",i=>{i||(n(new Error("Modal closed")),s())})}})}},re=vr(IHe)});var THe,k6,ipe=b(()=>{l();ut();ut();mm();$r();ai();To();mc();up();gc();yc();ha();$n();ma();THe=1e3,k6={checkNamespaceConnectorId(e,t){return re.getConnectorId(e)===t},isSocialProvider(e){return Ye.DEFAULT_REMOTE_FEATURES.socials.includes(e)},connectWalletConnect({walletConnect:e,connector:t,closeModalOnConnect:r=!0,redirectViewOnModalClose:n="Connect",onOpen:o,onConnect:s}){return new Promise((i,a)=>{if(e&&re.setActiveConnector(t),o?.(se.isMobile()&&e),n){let u=De.subscribeKey("open",d=>{d||(J.state.view!==n&&J.replace(n),u(),a(new Error("Modal closed")))})}let c=$.subscribeKey("activeCaipAddress",u=>{u&&(s?.(),r&&De.close(),c(),i(lt.parseCaipAddress(u)))})})},connectExternal(e){return new Promise((t,r)=>{let n=$.subscribeKey("activeCaipAddress",o=>{o&&(De.close(),n(),t(lt.parseCaipAddress(o)))});ee.connectExternal(e,e.chain).catch(()=>{n(),r(new Error("Connection rejected"))})})},connectSocial({social:e,namespace:t,closeModalOnConnect:r=!0,onOpenFarcaster:n,onConnect:o}){let s,i=!1,a=null,c=t||$.state.activeChain,u=$.subscribeKey("activeCaipAddress",d=>{d&&(r&&De.close(),u())});return new Promise((d,f)=>{async function p(y){if(y.data?.resultUri)if(y.origin===Z.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",p,!1);try{let w=re.getAuthConnector(c);if(w&&!i){s&&s.close(),i=!0;let x=y.data.resultUri;Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:e}}),de.setConnectedSocialProvider(e),await ee.connectExternal({id:w.id,type:w.type,socialUri:x},w.chain);let v=$.state.activeCaipAddress;if(!v){f(new Error("Failed to connect"));return}d(lt.parseCaipAddress(v)),Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:e}})}}catch(w){Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:se.parseError(w)}}),f(new Error("Failed to connect"))}}else Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:"Untrusted Origin"}})}async function h(){if(Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:e}}),e==="farcaster"){n?.();let y=De.subscribeKey("open",x=>{!x&&e==="farcaster"&&(f(new Error("Popup closed")),o?.(),y())}),w=re.getAuthConnector();if(w&&!$.getAccountData(c)?.farcasterUrl)try{let{url:v}=await w.provider.getFarcasterUri();$.setAccountProp("farcasterUrl",v,c)}catch{f(new Error("Failed to connect to farcaster"))}}else{let y=re.getAuthConnector();a=se.returnOpenHref(`${Z.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(y){let{uri:w}=await y.provider.getSocialRedirectUri({provider:e});if(a&&w){a.location.href=w,s=a;let x=setInterval(()=>{s?.closed&&!i&&(f(new Error("Popup closed")),clearInterval(x))},1e3);window.addEventListener("message",p,!1)}else a?.close(),f(new Error("Failed to initiate social connection"))}}catch{f(new Error("Failed to initiate social connection")),a?.close()}}}h()})},connectEmail({closeModalOnConnect:e=!0,redirectViewOnModalClose:t="Connect",onOpen:r,onConnect:n}){return new Promise((o,s)=>{if(r?.(),t){let a=De.subscribeKey("open",c=>{c||(J.state.view!==t&&J.replace(t),a(),s(new Error("Modal closed")))})}let i=$.subscribeKey("activeCaipAddress",a=>{a&&(n?.(),e&&De.close(),i(),o(lt.parseCaipAddress(a)))})})},async updateEmail(){let e=de.getConnectedConnectorId($.state.activeChain),t=re.getAuthConnector();if(!t)throw new Error("No auth connector found");if(e!==Z.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");let r=t.provider.getEmail()??"";return await De.open({view:"UpdateEmailWallet",data:{email:r,redirectView:void 0}}),new Promise((n,o)=>{let s=setInterval(()=>{let a=t.provider.getEmail()??"";a!==r&&(De.close(),clearInterval(s),i(),n({email:a}))},THe),i=De.subscribeKey("open",a=>{a||(J.state.view!=="Connect"&&J.push("Connect"),clearInterval(s),i(),o(new Error("Modal closed")))})})},canSwitchToSmartAccount(e){return $.checkIfSmartAccountEnabled()&&Fr(e)===Kr.ACCOUNT_TYPES.EOA}}});function U6(){let e=$.state.activeCaipNetwork?.chainNamespace||"eip155",t=$.state.activeCaipNetwork?.id||1,r=Ye.NATIVE_TOKEN_ADDRESS[e];return`${e}:${t}:${r}`}function EH(e){return Ye.NATIVE_TOKEN_ADDRESS[e]}function Fr(e){return $.getAccountData(e)?.preferredAccountType}function oy(e){return e?$.state.chains.get(e)?.networkState?.caipNetwork:$.state.activeCaipNetwork}var yc=b(()=>{l();$r();ha()});var fp,AH=b(()=>{l();ai();To();mc();Un();$n();fp={getConnectionStatus(e,t){let r=re.state.activeConnectorIds[t],n=ee.getConnections(t);return!!r&&e.connectorId===r?"connected":n.some(i=>i.connectorId.toLowerCase()===e.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:e,connectorId:t,addresses:r}){return e.map(n=>{if((t?n.connectorId.toLowerCase()===t.toLowerCase():!1)&&r){let s=n.accounts.filter(i=>!r.some(c=>c.toLowerCase()===i.address.toLowerCase()));return{...n,accounts:s}}return n})},excludeExistingConnections(e,t){let r=new Set(e);return t.filter(n=>!r.has(n.connectorId))},getConnectionsByConnectorId(e,t){return e.filter(r=>r.connectorId.toLowerCase()===t.toLowerCase())},getConnectionsData(e){let t=!!Y.state.remoteFeatures?.multiWallet,r=re.state.activeConnectorIds[e],n=ee.getConnections(e),s=(ee.state.recentConnections.get(e)??[]).filter(a=>re.getConnectorById(a.connectorId)),i=fp.excludeExistingConnections([...n.map(a=>a.connectorId),...r?[r]:[]],s);return t?{connections:n,recentConnections:i}:{connections:n.filter(a=>a.connectorId.toLowerCase()===r?.toLowerCase()),recentConnections:[]}},onConnectMobile(e){let t=ee.state.wcUri;if(e?.mobile_link&&t)try{ee.setWcError(!1);let{mobile_link:r,link_mode:n,name:o}=e,{redirect:s,redirectUniversalLink:i,href:a}=se.formatNativeUrl(r,t,n),c=s,u=i,d=se.isIframe()?"_top":"_self";ee.setWcLinking({name:o,href:a}),ee.setRecentWallet(e),Y.state.experimental_preferUniversalLinks&&u?se.openHref(u,d):se.openHref(c,d)}catch(r){Ae.sendEvent({type:"track",event:"CONNECT_PROXY_ERROR",properties:{message:r instanceof Error?r.message:"Error parsing the deep link",uri:t,mobile_link:e.mobile_link,name:e.name}}),ee.setWcError(!0)}}}});var D6,ws,Q3=b(()=>{l();Lr();Hn();D6=rt({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1,connectingWallet:void 0}),ws={state:D6,subscribe(e){return Dt(D6,()=>e(D6))},subscribeOpen(e){return Tt(D6,"open",e)},set(e){Object.assign(D6,{...D6,...e})}}});var on,_He,X3,ape=b(()=>{l();Lr();mm();yc();gs();lp();$r();mc();Un();hm();on=rt({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),_He={state:on,subscribe(e){return Dt(on,()=>e(on))},setLastNetworkInView(e){on.lastNetworkInView=e},async fetchTransactions(e){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");on.loading=!0;try{let t=await ze.fetchTransactions({account:e,cursor:on.next,chainId:$.state.activeCaipNetwork?.caipNetworkId}),r=X3.filterSpamTransactions(t.data),n=X3.filterByConnectedChain(r),o=[...on.transactions,...n];on.loading=!1,on.transactions=o,on.transactionsByYear=X3.groupTransactionsByYearAndMonth(on.transactionsByYear,n),on.empty=o.length===0,on.next=t.next?t.next:void 0}catch{let r=$.state.activeChain;Ae.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:Y.state.projectId,cursor:on.next,isSmartAccount:Fr(r)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),Je.showError("Failed to fetch transactions"),on.loading=!1,on.empty=!0,on.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){let r=e;return t.forEach(n=>{let o=new Date(n.metadata.minedAt).getFullYear(),s=new Date(n.metadata.minedAt).getMonth(),i=r[o]??{},c=(i[s]??[]).filter(u=>u.id!==n.id);r[o]={...i,[s]:[...c,n].sort((u,d)=>new Date(d.metadata.minedAt).getTime()-new Date(u.metadata.minedAt).getTime())}}),r},filterSpamTransactions(e){return e.filter(t=>!t.transfers?.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(e){let t=$.state.activeCaipNetwork?.caipNetworkId;return e.filter(n=>n.metadata.chain===t)},clearCursor(){on.next=void 0},resetTransactions(){on.transactions=[],on.transactionsByYear={},on.lastNetworkInView=void 0,on.loading=!1,on.empty=!1,on.next=void 0}},X3=vr(_He,"API_ERROR")});var Lt,sy,PHe,ee,ai=b(()=>{l();Lr();Hn();ut();yc();AH();ipe();$n();ma();gs();$r();To();mc();up();Q3();gc();ape();Lt=rt({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,wcFetchingUri:!1,buffering:!1,status:"disconnected"}),PHe={state:Lt,subscribe(e){return Dt(Lt,()=>e(Lt))},subscribeKey(e,t){return Tt(Lt,e,t)},_getClient(){return Lt._client},setClient(e){Lt._client=vf(e)},initialize(e){let t=e.filter(r=>!!r.namespace).map(r=>r.namespace);ee.syncStorageConnections(t)},syncStorageConnections(e){let t=de.getConnections(),r=e??Array.from($.state.chains.keys());for(let n of r){let o=t[n]??[],s=new Map(Lt.recentConnections);s.set(n,o),Lt.recentConnections=s}},getConnections(e){return e?Lt.connections.get(e)??[]:[]},hasAnyConnection(e){let t=ee.state.connections;return Array.from(t.values()).flatMap(r=>r).some(({connectorId:r})=>r===e)},async connectWalletConnect({cache:e="auto"}={}){Lt.wcFetchingUri=!0;let t=se.isTelegram()||se.isSafari()&&se.isIos();if(e==="always"||e==="auto"&&t){if(sy){await sy,sy=void 0;return}if(!se.isPairingExpired(Lt?.wcPairingExpiry)){let r=Lt.wcUri;Lt.wcUri=r;return}sy=ee._getClient()?.connectWalletConnect?.().catch(()=>{}),ee.state.status="connecting",await sy,sy=void 0,Lt.wcPairingExpiry=void 0,ee.state.status="connected"}else await ee._getClient()?.connectWalletConnect?.()},async connectExternal(e,t,r=!0){let n=await ee._getClient()?.connectExternal?.(e);r&&$.setActiveNamespace(t);let o=re.state.allConnectors.find(i=>i.id===e?.id),s=e.type==="AUTH"?"email":"browser";return Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s,name:o?.name||"Unknown",view:J.state.view,walletRank:o?.explorerWallet?.order}}),n},async reconnectExternal(e){await ee._getClient()?.reconnectExternal?.(e);let t=e.chain||$.state.activeChain;t&&re.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){if(!t)return;De.setLoading(!0,$.state.activeChain);let r=re.getAuthConnector();r&&($.setAccountProp("preferredAccountType",e,t),await r.provider.setPreferredAccount(e),de.setPreferredAccountTypes(Object.entries($.state.chains).reduce((n,[o,s])=>{let i=o,a=Fr(i);return a!==void 0&&(n[i]=a),n},{})),await ee.reconnectExternal(r),De.setLoading(!1,$.state.activeChain),Ae.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:$.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(e){return ee._getClient()?.signMessage(e)},parseUnits(e,t){return ee._getClient()?.parseUnits(e,t)},formatUnits(e,t){return ee._getClient()?.formatUnits(e,t)},updateBalance(e){return ee._getClient()?.updateBalance(e)},async sendTransaction(e){return ee._getClient()?.sendTransaction(e)},async getCapabilities(e){return ee._getClient()?.getCapabilities(e)},async grantPermissions(e){return ee._getClient()?.grantPermissions(e)},async walletGetAssets(e){return ee._getClient()?.walletGetAssets(e)??{}},async estimateGas(e){return ee._getClient()?.estimateGas(e)},async writeContract(e){return ee._getClient()?.writeContract(e)},async writeSolanaTransaction(e){return ee._getClient()?.writeSolanaTransaction(e)},async getEnsAddress(e){return ee._getClient()?.getEnsAddress(e)},async getEnsAvatar(e){return ee._getClient()?.getEnsAvatar(e)},checkInstalled(e){return ee._getClient()?.checkInstalled?.(e)||!1},resetWcConnection(){Lt.wcUri=void 0,Lt.wcPairingExpiry=void 0,Lt.wcLinking=void 0,Lt.recentWallet=void 0,Lt.wcFetchingUri=!1,Lt.status="disconnected",X3.resetTransactions(),de.deleteWalletConnectDeepLink(),de.deleteRecentWallet(),ws.set({connectingWallet:void 0})},resetUri(){Lt.wcUri=void 0,Lt.wcPairingExpiry=void 0,sy=void 0,Lt.wcFetchingUri=!1,ws.set({connectingWallet:void 0})},finalizeWcConnection(e){let{wcLinking:t,recentWallet:r}=ee.state;t&&de.setWalletConnectDeepLink(t),r&&de.setAppKitRecent(r),e&&Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:t?"mobile":"qrcode",name:J.state.data?.wallet?.name||"Unknown",view:J.state.view,walletRank:r?.order}})},setWcBasic(e){Lt.wcBasic=e},setUri(e){Lt.wcUri=e,Lt.wcFetchingUri=!1,Lt.wcPairingExpiry=se.getPairingExpiry()},setWcLinking(e){Lt.wcLinking=e},setWcError(e){Lt.wcError=e,Lt.wcFetchingUri=!1,Lt.buffering=!1},setRecentWallet(e){Lt.recentWallet=e},setBuffering(e){Lt.buffering=e},setStatus(e){Lt.status=e},setIsSwitchingConnection(e){Lt.isSwitchingConnection=e},async disconnect({id:e,namespace:t,initialDisconnect:r}={}){try{await ee._getClient()?.disconnect({id:e,chainNamespace:t,initialDisconnect:r})}catch(n){throw new hc("Failed to disconnect","INTERNAL_SDK_ERROR",n)}},async disconnectConnector({id:e,namespace:t}){try{await ee._getClient()?.disconnectConnector({id:e,namespace:t})}catch(r){throw new hc("Failed to disconnect connector","INTERNAL_SDK_ERROR",r)}},setConnections(e,t){let r=new Map(Lt.connections);r.set(t,e),Lt.connections=r},async handleAuthAccountSwitch({address:e,namespace:t}){let n=$.getAccountData(t)?.user?.accounts?.find(s=>s.type==="smartAccount"),o=n&&n.address.toLowerCase()===e.toLowerCase()&&k6.canSwitchToSmartAccount(t)?"smartAccount":"eoa";await ee.setPreferredAccountType(o,t)},async handleActiveConnection({connection:e,namespace:t,address:r}){let n=re.getConnectorById(e.connectorId),o=e.connectorId===Z.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${e.connectorId}`);if(o)r&&await ee.handleAuthAccountSwitch({address:r,namespace:t});else return(await ee.connectExternal({id:n.id,type:n.type,provider:n.provider,address:r,chain:t},t))?.address;return r},async handleDisconnectedConnection({connection:e,namespace:t,address:r,closeModalOnConnect:n}){let o=re.getConnectorById(e.connectorId),s=e.auth?.name?.toLowerCase(),i=e.connectorId===Z.CONNECTOR_ID.AUTH,a=e.connectorId===Z.CONNECTOR_ID.WALLET_CONNECT;if(!o)throw new Error(`No connector found for connection: ${e.connectorId}`);let c;if(i)if(s&&k6.isSocialProvider(s)){let{address:u}=await k6.connectSocial({social:s,closeModalOnConnect:n,onOpenFarcaster(){De.open({view:"ConnectingFarcaster"})},onConnect(){J.replace("ProfileWallets")}});c=u}else{let{address:u}=await k6.connectEmail({closeModalOnConnect:n,onOpen(){De.open({view:"EmailLogin"})},onConnect(){J.replace("ProfileWallets")}});c=u}else if(a){let{address:u}=await k6.connectWalletConnect({walletConnect:!0,connector:o,closeModalOnConnect:n,onOpen(d){let f=d?"AllWallets":"ConnectingWalletConnect";De.state.open?J.push(f):De.open({view:f})},onConnect(){J.replace("ProfileWallets")}});c=u}else{let u=await ee.connectExternal({id:o.id,type:o.type,provider:o.provider,chain:t},t);u&&(c=u.address)}return i&&r&&await ee.handleAuthAccountSwitch({address:r,namespace:t}),c},async switchConnection({connection:e,address:t,namespace:r,closeModalOnConnect:n,onChange:o}){let s,i=$.getAccountData(r)?.caipAddress;if(i){let{address:c}=lt.parseCaipAddress(i);s=c}let a=fp.getConnectionStatus(e,r);switch(a){case"connected":case"active":{let c=await ee.handleActiveConnection({connection:e,namespace:r,address:t});if(s&&c){let u=c.toLowerCase()!==s.toLowerCase();o?.({address:c,namespace:r,hasSwitchedAccount:u,hasSwitchedWallet:a==="active"})}break}case"disconnected":{let c=await ee.handleDisconnectedConnection({connection:e,namespace:r,address:t,closeModalOnConnect:n});c&&o?.({address:c,namespace:r,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},ee=vr(PHe)});var b_,cpe=b(()=>{l();R6();b_={createBalance(e,t){let r={name:e.metadata.name||"",symbol:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:r.name,symbol:r.symbol,chainId:t,address:e.address==="native"?void 0:this.convertAddressToCAIP10Address(e.address,t),value:r.value,price:r.price,quantity:{decimals:r.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:r.decimals})},iconUrl:r.iconUrl}},convertHexToBalance({hex:e,decimals:t}){return pc(BigInt(e),t)},convertAddressToCAIP10Address(e,t){return`${t}:${e}`},createCAIP2ChainId(e,t){return`${t}:${parseInt(e,16)}`},getChainIdHexFromCAIP2ChainId(e){let t=e.split(":");if(t.length<2||!t[1])return"0x0";let r=t[1],n=parseInt(r,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(e){return typeof e!="object"||e===null?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(r=>this.isValidAsset(r)))},isValidAsset(e){return typeof e=="object"&&e!==null&&typeof e.address=="string"&&typeof e.balance=="string"&&(e.type==="ERC20"||e.type==="NATIVE")&&typeof e.metadata=="object"&&e.metadata!==null&&typeof e.metadata.name=="string"&&typeof e.metadata.symbol=="string"&&typeof e.metadata.decimals=="number"&&typeof e.metadata.price=="number"&&typeof e.metadata.iconUrl=="string"}}});async function lpe(){if(!CH){let{createPublicClient:e,http:t,defineChain:r}=await Promise.resolve().then(()=>(R6(),Yfe));CH={createPublicClient:e,http:t,defineChain:r}}return CH}var CH,x_,upe=b(()=>{l();ut();Un();x_={getBlockchainApiRpcUrl(e,t){let r=new URL("https://rpc.walletconnect.org/v1/");return r.searchParams.set("chainId",e),r.searchParams.set("projectId",t),r.toString()},async getViemChain(e){let{defineChain:t}=await lpe(),{chainId:r}=lt.parseCaipNetworkId(e.caipNetworkId);return t({...e,id:Number(r)})},async createViemPublicClient(e){let{createPublicClient:t,http:r}=await lpe(),n=Y.state.projectId,o=await x_.getViemChain(e);if(!o)throw new Error(`Chain ${e.caipNetworkId} not found in viem/chains`);return t({chain:o,transport:r(x_.getBlockchainApiRpcUrl(e.caipNetworkId,n))})}}});var al,L6=b(()=>{l();R6();ut();lp();$r();ai();To();cpe();ma();upe();al={async getMyTokensWithBalance(e={forceUpdate:void 0,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address}){let{forceUpdate:t,caipNetwork:r,address:n}=e,o=re.getConnectorId("eip155")===Z.CONNECTOR_ID.AUTH;if(!n)return[];let s=r?`${r.caipNetworkId}:${n}`:n,i=de.getBalanceCacheForCaipAddress(s);if(i)return i.balances;if(r&&r.chainNamespace===Z.CHAIN.EVM&&o){let c=await this.getEIP155Balances(n,r);if(c)return this.filterLowQualityTokens(c)}let a=await ze.getBalance(n,r?.caipNetworkId,t);return this.filterLowQualityTokens(a.balances)},async getEIP155Balances(e,t){try{let r=b_.getChainIdHexFromCAIP2ChainId(t.caipNetworkId);if(!(await ee.getCapabilities(e))?.[r]?.assetDiscovery?.supported)return null;let o=await ee.walletGetAssets({account:e,chainFilter:[r]});if(!b_.isWalletGetAssetsResponse(o))return null;let i=(o[r]||[]).map(a=>b_.createBalance(a,t.caipNetworkId));return de.updateBalanceCache({caipAddress:`${t.caipNetworkId}:${e}`,balance:{balances:i},timestamp:Date.now()}),i}catch{return null}},filterLowQualityTokens(e){return e.filter(t=>t.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:e,assetAddress:t,caipNetwork:r}){let n=await x_.createViemPublicClient(r),{address:o}=lt.parseCaipAddress(e),[{result:s},{result:i},{result:a},{result:c}]=await n.multicall({contracts:[{address:t,functionName:"name",args:[],abi:Hr},{address:t,functionName:"symbol",args:[],abi:Hr},{address:t,functionName:"balanceOf",args:[o],abi:Hr},{address:t,functionName:"decimals",args:[],abi:Hr}]});return{name:s,symbol:i,decimals:c,balance:a&&c?pc(a,c):"0"}}}});var SH,iy,IH=b(()=>{l();SH={adapters:{}},iy={state:SH,initialize(e){SH.adapters={...e}},get(e){return SH.adapters[e]}}});var v_,Li,ar,E_=b(()=>{l();Lr();Hn();v_={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:void 0},Li=rt({providers:{...v_},providerIds:{...v_}}),ar={state:Li,subscribeKey(e,t){return Tt(Li,e,t)},subscribe(e){return Dt(Li,()=>{e(Li)})},subscribeProviders(e){return Dt(Li.providers,()=>e(Li.providers))},setProvider(e,t){e&&t&&(Li.providers[e]=vf(t))},getProvider(e){if(e)return Li.providers[e]},setProviderId(e,t){t&&(Li.providerIds[e]=t)},getProviderId(e){if(e)return Li.providerIds[e]},reset(){Li.providers={...v_},Li.providerIds={...v_}},resetChain(e){Li.providers[e]=void 0,Li.providerIds[e]=void 0}}});var ym,TH=b(()=>{l();lp();$r();ai();L6();yc();ym={async getTokenList(e){return(await ze.fetchSwapTokens({chainId:e}))?.tokens?.map(n=>({...n,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){let e=$.state.activeCaipNetwork;if(!e)return null;try{if(e.chainNamespace==="solana"){let t=(await ee?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:t,fast:t,instant:t}}else return await ze.fetchGasPrice({chainId:e.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:e,userAddress:t,sourceTokenAmount:r,sourceTokenDecimals:n}){let o=await ze.fetchSwapAllowance({tokenAddress:e,userAddress:t});if(o?.allowance&&r&&n){let s=ee.parseUnits(r,n)||0;return BigInt(o.allowance)>=s}return!1},async getMyTokensWithBalance(e){let t=await al.getMyTokensWithBalance({forceUpdate:e,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address});return $.setAccountProp("tokenBalance",t,$.state.activeChain),this.mapBalancesToSwapTokens(t)},mapBalancesToSwapTokens(e){return e?.map(t=>({...t,address:t?.address?t.address:U6(),decimals:parseInt(t.quantity.decimals,10),logoUri:t.iconUrl,eip2612:!1}))||[]},async handleSwapError(e){try{let t=e?.cause;return t?.json&&(await t.json())?.reasons?.[0]?.description?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}}});var Zt,NHe,xt,_H=b(()=>{l();Lr();Hn();ut();ut();mm();L6();yc();ha();$n();TH();gs();$r();ai();mc();gc();hm();Zt=rt({tokenBalances:[],loading:!1}),NHe={state:Zt,subscribe(e){return Dt(Zt,()=>e(Zt))},subscribeKey(e,t){return Tt(Zt,e,t)},setToken(e){e&&(Zt.token=vf(e))},setTokenAmount(e){Zt.sendTokenAmount=e},setReceiverAddress(e){Zt.receiverAddress=e},setReceiverProfileImageUrl(e){Zt.receiverProfileImageUrl=e},setReceiverProfileName(e){Zt.receiverProfileName=e},setNetworkBalanceInUsd(e){Zt.networkBalanceInUSD=e},setLoading(e){Zt.loading=e},getSdkEventProperties(e){return{message:se.parseError(e),isSmartAccount:Fr($.state.activeChain)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:Zt.token?.symbol||"",amount:Zt.sendTokenAmount??0,network:$.state.activeCaipNetwork?.caipNetworkId||""}},async sendToken(){try{switch(xt.setLoading(!0),$.state.activeCaipNetwork?.chainNamespace){case"eip155":await xt.sendEvmToken();return;case"solana":await xt.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw js.isUserRejectedRequestError(e)?new Z1(e):e}finally{xt.setLoading(!1)}},async sendEvmToken(){let e=$.state.activeChain;if(!e)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");let t=Fr(e);if(!xt.state.sendTokenAmount||!xt.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!xt.state.token)throw new Error("A token is required");if(xt.state.token?.address){Ae.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token.address,amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||""}});let{hash:r}=await xt.sendERC20Token({receiverAddress:xt.state.receiverAddress,tokenAddress:xt.state.token.address,sendTokenAmount:xt.state.sendTokenAmount,decimals:xt.state.token.quantity.decimals});r&&(Zt.hash=r)}else{Ae.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token.symbol||"",amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||""}});let{hash:r}=await xt.sendNativeToken({receiverAddress:xt.state.receiverAddress,sendTokenAmount:xt.state.sendTokenAmount,decimals:xt.state.token.quantity.decimals});r&&(Zt.hash=r)}},async fetchTokenBalance(e){Zt.loading=!0;let t=$.state.activeChain,r=$.state.activeCaipNetwork?.caipNetworkId,n=$.state.activeCaipNetwork?.chainNamespace,o=$.getAccountData(t)?.caipAddress??$.state.activeCaipAddress,s=o?se.getPlainAddress(o):void 0;if(Zt.lastRetry&&!se.isAllowedRetry(Zt.lastRetry,30*Ye.ONE_SEC_MS))return Zt.loading=!1,[];try{if(s&&r&&n){let i=await al.getMyTokensWithBalance();return Zt.tokenBalances=i,Zt.lastRetry=void 0,i}}catch(i){Zt.lastRetry=Date.now(),e?.(i),Je.showError("Token Balance Unavailable")}finally{Zt.loading=!1}return[]},fetchNetworkBalance(){if(Zt.tokenBalances.length===0)return;let e=ym.mapBalancesToSwapTokens(Zt.tokenBalances);if(!e)return;let t=e.find(r=>r.address===U6());t&&(Zt.networkBalanceInUSD=t?ht.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){J.pushTransactionStack({});let t=e.receiverAddress,r=$.getAccountData()?.address,n=ee.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),s=await ee.sendTransaction({chainNamespace:Z.CHAIN.EVM,to:t,address:r,data:"0x",value:n??BigInt(0)});return Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Fr("eip155")===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token?.symbol||"",amount:e.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:s||""}}),ee._getClient()?.updateBalance("eip155"),xt.resetSend(),{hash:s}},async sendERC20Token(e){J.pushTransactionStack({onSuccess(){J.replace("Account")}});let t=ee.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),r=$.getAccountData()?.address;if(r&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){let n=se.getPlainAddress(e.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");let o=await ee.writeContract({fromAddress:r,tokenAddress:n,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:f4.getERC20Abi(n),chainNamespace:Z.CHAIN.EVM});return Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Fr("eip155")===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token?.symbol||"",amount:e.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:o||""}}),xt.resetSend(),{hash:o}}return{hash:void 0}},async sendSolanaToken(){if(!xt.state.sendTokenAmount||!xt.state.receiverAddress)throw new Error("An amount and receiver address are required");J.pushTransactionStack({onSuccess(){J.replace("Account")}});let e;xt.state.token&&xt.state.token.address!==Ye.SOLANA_NATIVE_TOKEN_ADDRESS&&(se.isCaipAddress(xt.state.token.address)?e=se.getPlainAddress(xt.state.token.address):e=xt.state.token.address);let t=await ee.sendTransaction({chainNamespace:"solana",tokenMint:e,to:xt.state.receiverAddress,value:xt.state.sendTokenAmount});t&&(Zt.hash=t),ee._getClient()?.updateBalance("solana"),Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:xt.state.token?.symbol||"",amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:t||""}}),xt.resetSend()},resetSend(){Zt.token=void 0,Zt.sendTokenAmount=void 0,Zt.receiverAddress=void 0,Zt.receiverProfileImageUrl=void 0,Zt.receiverProfileName=void 0,Zt.loading=!1,Zt.tokenBalances=[]}},xt=vr(NHe)});var PH,A_,Oe,dpe,$,$r=b(()=>{l();Lr();Hn();ut();_te();L6();ha();$n();ma();gs();IH();ai();To();mc();up();Un();E_();Q3();_H();hm();PH={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},A_={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},Oe=rt({chains:Cte(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),dpe={state:Oe,subscribe(e){return Dt(Oe,()=>{e(Oe)})},subscribeKey(e,t){return Tt(Oe,e,t)},subscribeAccountStateProp(e,t,r){let n=r||Oe.activeChain;return n?Tt(Oe.chains.get(n)?.accountState||{},e,t):()=>{}},subscribeChainProp(e,t,r){let n;return Dt(Oe.chains,()=>{let o=r||Oe.activeChain;if(o){let s=Oe.chains.get(o)?.[e];n!==s&&(n=s,t(s))}})},initialize(e,t,r){let{chainId:n,namespace:o}=de.getActiveNetworkProps(),s=t?.find(d=>d.id.toString()===n?.toString()),a=e.find(d=>d?.namespace===o)||e?.[0],c=e.map(d=>d.namespace).filter(d=>d!==void 0),u=Y.state.enableEmbedded?new Set([...c]):new Set([...t?.map(d=>d.chainNamespace)??[]]);(e?.length===0||!a)&&(Oe.noAdapters=!0),Oe.noAdapters||(Oe.activeChain=a?.namespace,Oe.activeCaipNetwork=s,$.setChainNetworkData(a?.namespace,{caipNetwork:s}),Oe.activeChain&&ws.set({activeChain:a?.namespace})),u.forEach(d=>{let f=t?.filter(y=>y.chainNamespace===d),p=de.getPreferredAccountTypes()||{},h={...Y.state.defaultAccountTypes,...p};$.state.chains.set(d,{namespace:d,networkState:rt({...A_,caipNetwork:f?.[0]}),accountState:rt({...PH,preferredAccountType:h[d]}),caipNetworks:f??[],...r}),$.setRequestedCaipNetworks(f??[],d)})},removeAdapter(e){if(Oe.activeChain===e){let t=Array.from(Oe.chains.entries()).find(([r])=>r!==e);if(t){let r=t[1]?.caipNetworks?.[0];r&&$.setActiveCaipNetwork(r)}}Oe.chains.delete(e)},addAdapter(e,{connectionControllerClient:t},r){if(!e.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");Oe.chains.set(e.namespace,{namespace:e.namespace,networkState:{...A_,caipNetwork:r[0]},accountState:{...PH},caipNetworks:r,connectionControllerClient:t}),$.setRequestedCaipNetworks(r?.filter(n=>n.chainNamespace===e.namespace)??[],e.namespace)},addNetwork(e){let t=Oe.chains.get(e.chainNamespace);if(t){let r=[...t.caipNetworks||[]];t.caipNetworks?.find(n=>n.id===e.id)||r.push(e),Oe.chains.set(e.chainNamespace,{...t,caipNetworks:r}),$.setRequestedCaipNetworks(r,e.chainNamespace),re.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){let r=Oe.chains.get(e);if(r){let n=Oe.activeCaipNetwork?.id===t,o=[...r.caipNetworks?.filter(s=>s.id!==t)||[]];n&&r?.caipNetworks?.[0]&&$.setActiveCaipNetwork(r.caipNetworks[0]),Oe.chains.set(e,{...r,caipNetworks:o}),$.setRequestedCaipNetworks(o||[],e),o.length===0&&re.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){let r=Oe.chains.get(e);r&&(r.networkState={...r.networkState||A_,...t},Oe.chains.set(e,r))},setChainAccountData(e,t,r=!0){if(!e)throw new Error("Chain is required to update chain account data");let n=Oe.chains.get(e);if(n){let o={...n.accountState||PH,...t};Oe.chains.set(e,{...n,accountState:o}),(Oe.chains.size===1||Oe.activeChain===e)&&t.caipAddress&&(Oe.activeCaipAddress=t.caipAddress)}},setChainNetworkData(e,t){if(!e)return;let r=Oe.chains.get(e);if(r){let n={...r.networkState||A_,...t};Oe.chains.set(e,{...r,networkState:n})}},setAccountProp(e,t,r,n=!0){$.setChainAccountData(r,{[e]:t},n)},setActiveNamespace(e){Oe.activeChain=e;let t=e?Oe.chains.get(e):void 0,r=t?.networkState?.caipNetwork;r?.id&&e&&(Oe.activeCaipAddress=t?.accountState?.caipAddress,Oe.activeCaipNetwork=r,$.setChainNetworkData(e,{caipNetwork:r}),de.setActiveCaipNetworkId(r?.caipNetworkId),ws.set({activeChain:e,selectedNetworkId:r?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;let t=Oe.activeChain===e.chainNamespace;t||$.setIsSwitchingNamespace(!0);let r=Oe.chains.get(e.chainNamespace);Oe.activeChain=e.chainNamespace,Oe.activeCaipNetwork=e,$.setChainNetworkData(e.chainNamespace,{caipNetwork:e});let n=r?.accountState?.address;if(n)Oe.activeCaipAddress=`${e.chainNamespace}:${e.id}:${n}`;else if(t&&Oe.activeCaipAddress){let{address:s}=lt.parseCaipAddress(Oe.activeCaipAddress);n=s,Oe.activeCaipAddress=`${e.caipNetworkId}:${n}`}else Oe.activeCaipAddress=void 0;$.setChainAccountData(e.chainNamespace,{address:n,caipAddress:Oe.activeCaipAddress}),xt.resetSend(),ws.set({activeChain:Oe.activeChain,selectedNetworkId:Oe.activeCaipNetwork?.caipNetworkId}),de.setActiveCaipNetworkId(e.caipNetworkId),!$.checkIfSupportedNetwork(e.chainNamespace)&&Y.state.enableNetworkSwitch&&!Y.state.allowUnsupportedChain&&!ee.state.wcBasic&&$.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;let t=Oe.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;let t=e!==$.state.activeChain,r=$.getNetworkData(e)?.caipNetwork,n=$.getCaipNetworkByNamespace(e,r?.id);t&&n&&await $.switchActiveNetwork(n)},async switchActiveNetwork(e,{throwOnFailure:t=!1}={}){let r=$.state.activeChain;if(!r)throw new Error("ChainController:switchActiveNetwork - namespace is required");let n=ar.getProviderId(Oe.activeChain)==="AUTH",o=$.getAccountData(r)?.address,s=Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e.chainNamespace);try{if(o&&e.chainNamespace===r||n&&s){let i=iy.get(e.chainNamespace);if(!i)throw new Error("Adapter not found");await i.switchNetwork({caipNetwork:e})}$.setActiveCaipNetwork(e)}catch(i){if(t)throw i}Ae.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})},getConnectionControllerClient(e){let t=e||Oe.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");let r=Oe.chains.get(t);if(!r?.connectionControllerClient)throw new Error("ConnectionController client not set");return r.connectionControllerClient},getNetworkProp(e,t){let r=Oe.chains.get(t)?.networkState;if(r)return r[e]},getRequestedCaipNetworks(e){let t=Oe.chains.get(e),{approvedCaipNetworkIds:r=[],requestedCaipNetworks:n=[]}=t?.networkState||{};return se.sortRequestedNetworks(r,n).filter(i=>i?.id)},getAllRequestedCaipNetworks(){let e=[];return Oe.chains.forEach(t=>{if(!t.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");let r=$.getRequestedCaipNetworks(t.namespace);e.push(...r)}),e},setRequestedCaipNetworks(e,t){$.setAdapterNetworkState(t,{requestedCaipNetworks:e});let n=$.getAllRequestedCaipNetworks().map(s=>s.chainNamespace),o=Array.from(new Set(n));re.filterByNamespaces(o)},getAllApprovedCaipNetworkIds(){let e=[];return Oe.chains.forEach(t=>{if(!t.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");let r=$.getApprovedCaipNetworkIds(t.namespace);e.push(...r)}),e},getActiveCaipNetwork(e){return e?Oe.chains.get(e)?.networkState?.caipNetwork:Oe.activeCaipNetwork},getActiveCaipAddress(){return Oe.activeCaipAddress},getApprovedCaipNetworkIds(e){return Oe.chains.get(e)?.networkState?.approvedCaipNetworkIds||[]},setApprovedCaipNetworksData(e,t){$.setAdapterNetworkState(e,t)},checkIfSupportedNetwork(e,t){let r=t||Oe.activeCaipNetwork?.caipNetworkId,n=$.getRequestedCaipNetworks(e);return n.length?n?.some(o=>o.caipNetworkId===r):!0},checkIfSupportedChainId(e){return Oe.activeChain?$.getRequestedCaipNetworks(Oe.activeChain)?.some(r=>r.id===e):!0},checkIfSmartAccountEnabled(){let e=V1.caipNetworkIdToNumber(Oe.activeCaipNetwork?.caipNetworkId);return!Oe.activeChain||!e?!1:!!(Ew.get(Qa.SMART_ACCOUNT_ENABLED_NETWORKS)?.split(",")||[])?.includes(e.toString())},showUnsupportedChainUI(){De.open({view:"UnsupportedChain"})},checkIfNamesSupported(){let e=Oe.activeCaipNetwork;return!!(e?.chainNamespace&&Ye.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){$.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(e){let t=e;if(!t)throw new Error("Chain is required to set account prop");let r=$.state.chains.get(t)?.accountState?.preferredAccountType,n=Y.state.defaultAccountTypes[t];Oe.activeCaipAddress=void 0,$.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:n||r,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),re.removeConnectorId(t)},setIsSwitchingNamespace(e){Oe.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){let e=[],t;if(Oe.chains.forEach(r=>{Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&e.push(r.namespace)}),e.length>0){let r=e[0];return t=r?Oe.chains.get(r)?.caipNetworks?.[0]:void 0,t}},getAccountData(e){let t=e||Oe.activeChain;if(t)return $.state.chains.get(t)?.accountState},getNetworkData(e){let t=e||Oe.activeChain;if(t)return $.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;let r=$.state.chains.get(e),n=r?.caipNetworks?.find(o=>o.id.toString()===t?.toString());return n||r?.networkState?.caipNetwork||r?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){let e=re.state.filterByNamespace;return(e?[Oe.chains.get(e)]:Array.from(Oe.chains.values())).flatMap(r=>r?.caipNetworks||[]).map(r=>r.caipNetworkId)},getCaipNetworks(e){return e?$.getRequestedCaipNetworks(e):$.getAllRequestedCaipNetworks()},getCaipNetworkById(e,t){return dpe.getCaipNetworks(t).find(r=>r.id.toString()===e.toString()||r.caipNetworkId.toString()===e.toString())},setLastConnectedSIWECaipNetwork(e){Oe.lastConnectedSIWECaipNetwork=e},getLastConnectedSIWECaipNetwork(){return Oe.lastConnectedSIWECaipNetwork},async fetchTokenBalance(e){let t=$.getAccountData();if(!t)return[];let r=$.state.activeCaipNetwork?.caipNetworkId,n=$.state.activeCaipNetwork?.chainNamespace,o=$.state.activeCaipAddress,s=o?se.getPlainAddress(o):void 0;if($.setAccountProp("balanceLoading",!0,n),t.lastRetry&&!se.isAllowedRetry(t.lastRetry,30*Ye.ONE_SEC_MS))return $.setAccountProp("balanceLoading",!1,n),[];try{if(s&&r&&n){let i=await al.getMyTokensWithBalance();return $.setAccountProp("tokenBalance",i,n),$.setAccountProp("lastRetry",void 0,n),$.setAccountProp("balanceLoading",!1,n),i}}catch(i){$.setAccountProp("lastRetry",Date.now(),n),e?.(i),Je.showError("Token Balance Unavailable")}finally{$.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(e){let t=e.chainNamespace,r=!!$.getAccountData(t)?.caipAddress,n=$.getAllApprovedCaipNetworkIds(),o=$.getNetworkProp("supportsAllNetworks",t)!==!1,s=re.getConnectorId(t),i=re.getAuthConnector(),a=s===Z.CONNECTOR_ID.AUTH&&i;return!r||o||a?!1:!n?.includes(e.caipNetworkId)}},$=vr(dpe)});var fpe,ppe=b(()=>{l();ut();$r();To();gc();fpe={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){let r=$.state.activeCaipNetwork,n=$.state.activeChain,o=J.state.data;if(e.id===r?.id)return;let i=!!$.getAccountData(n)?.address,a=!!$.getAccountData(e.chainNamespace)?.address,c=e.chainNamespace!==n,d=re.getConnectorId(n)===Z.CONNECTOR_ID.AUTH,f=Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(p=>p===e.chainNamespace);t||d&&f?J.push("SwitchNetwork",{...o,network:e}):i&&c&&!a?J.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):J.push("SwitchNetwork",{...o,network:e})}}});var Mi,RHe,De,up=b(()=>{l();Lr();Hn();$n();ppe();gs();Cu();$r();ai();To();mc();Un();Q3();gc();Mi=rt({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),RHe={state:Mi,subscribe(e){return Dt(Mi,()=>e(Mi))},subscribeKey(e,t){return Tt(Mi,e,t)},async open(e){let t=e?.namespace,r=$.state.activeChain,n=t&&t!==r,o=$.getAccountData(e?.namespace)?.caipAddress,s=$.state.noAdapters;if(ee.state.wcBasic?ge.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await ge.prefetch(),re.setFilterByNamespace(e?.namespace),De.setLoading(!0,t),t&&n){let i=$.getNetworkData(t)?.caipNetwork||$.getRequestedCaipNetworks(t)[0];i&&(s?(await $.switchActiveNetwork(i),J.push("ConnectingWalletConnectBasic")):fpe.onSwitchNetwork({network:i,ignoreSwitchConfirmation:!0}))}else Y.state.manualWCControl||s&&!o?se.isMobile()?J.reset("AllWallets"):J.reset("ConnectingWalletConnectBasic"):e?.view?J.reset(e.view,e.data):o?J.reset("Account"):J.reset("Connect");Mi.open=!0,ws.set({open:!0}),Ae.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!o}})},close(){let e=Y.state.enableEmbedded,t=!!$.state.activeCaipAddress;Mi.open&&Ae.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),Mi.open=!1,J.reset("Connect"),De.clearLoading(),e?t?J.replace("Account"):J.push("Connect"):ws.set({open:!1}),ee.resetUri()},setLoading(e,t){t&&Mi.loadingNamespaceMap.set(t,e),Mi.loading=e,ws.set({loading:e})},clearLoading(){Mi.loadingNamespaceMap.clear(),Mi.loading=!1,ws.set({loading:!1})},shake(){Mi.shake||(Mi.shake=!0,setTimeout(()=>{Mi.shake=!1},500))}},De=vr(RHe)});var e5,NH,OHe,Jt,BHe,t5,hpe=b(()=>{l();Lr();Hn();ut();ha();gs();Cu();lp();$r();Un();e5={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},NH={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},OHe={providers:BU,selectedProvider:null,error:null,purchaseCurrency:e5,paymentCurrency:NH,purchaseCurrencies:[e5],paymentCurrencies:[],quotesLoading:!1},Jt=rt(OHe),BHe={state:Jt,subscribe(e){return Dt(Jt,()=>e(Jt))},subscribeKey(e,t){return Tt(Jt,e,t)},setSelectedProvider(e){if(e&&e.name==="meld"){let t=$.state.activeChain,r=t===Z.CHAIN.SOLANA?"SOL":"USDC",n=t?$.state.chains.get(t)?.accountState?.address??"":"",o=new URL(e.url);o.searchParams.append("publicKey",Ste),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",n),o.searchParams.append("externalCustomerId",Y.state.projectId),Jt.selectedProvider={...e,url:o.toString()}}else Jt.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(t=>typeof t=="string")){let t=e,r=BU.filter(n=>t.includes(n.name));Jt.providers=r}else Jt.providers=[]},setPurchaseCurrency(e){Jt.purchaseCurrency=e},setPaymentCurrency(e){Jt.paymentCurrency=e},setPurchaseAmount(e){t5.state.purchaseAmount=e},setPaymentAmount(e){t5.state.paymentAmount=e},async getAvailableCurrencies(){let e=await ze.getOnrampOptions();Jt.purchaseCurrencies=e.purchaseCurrencies,Jt.paymentCurrencies=e.paymentCurrencies,Jt.paymentCurrency=e.paymentCurrencies[0]||NH,Jt.purchaseCurrency=e.purchaseCurrencies[0]||e5,await ge.fetchCurrencyImages(e.paymentCurrencies.map(t=>t.id)),await ge.fetchTokenImages(e.purchaseCurrencies.map(t=>t.symbol))},async getQuote(){Jt.quotesLoading=!0;try{let e=await ze.getOnrampQuote({purchaseCurrency:Jt.purchaseCurrency,paymentCurrency:Jt.paymentCurrency,amount:Jt.paymentAmount?.toString()||"0",network:Jt.purchaseCurrency?.symbol});return Jt.quotesLoading=!1,Jt.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return Jt.error=e.message,Jt.quotesLoading=!1,null}finally{Jt.quotesLoading=!1}},resetState(){Jt.selectedProvider=null,Jt.error=null,Jt.purchaseCurrency=e5,Jt.paymentCurrency=NH,Jt.purchaseCurrencies=[e5],Jt.paymentCurrencies=[],Jt.paymentAmount=void 0,Jt.purchaseAmount=void 0,Jt.quotesLoading=!1}},t5=vr(BHe)});function kHe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let u=0;u>>0,w=new Uint8Array(y);for(;p!==h;){let T=u[p],E=0;for(let S=y-1;(T!==0||E>>0,w[S]=T%r>>>0,T=T/r>>>0;if(T!==0)throw new Error("Non-zero carry");f=E,p++}let x=y-f;for(;x!==y&&w[x]===0;)x++;let v=n.repeat(d);for(;x>>0,y=new Uint8Array(h);for(;d255)return;let E=t[T];if(E===255)return;let S=0;for(let _=h-1;(E!==0||S>>0,y[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=S,d++}let w=h-p;for(;w!==h&&y[w]===0;)w++;let x=new Uint8Array(f+(h-w)),v=f;for(;w!==h;)x[v++]=y[w++];return x}function c(u){let d=a(u);if(d)return d;throw new Error("Non-base"+r+" character")}return{encode:i,decodeUnsafe:a,decode:c}}var mpe,gpe=b(()=>{l();mpe=kHe});var UHe,wm,RH=b(()=>{l();gpe();UHe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",wm=mpe(UHe)});var DHe,LHe,MHe,Yrr,HHe,Jrr,C_=b(()=>{l();$c();cw();rI();DHe=Ht(ks(),1),LHe="wc",MHe="universal_provider",Yrr=`${LHe}@2:${MHe}:`,HHe="https://rpc.walletconnect.org/v1/",Jrr=`${HHe}bundler`});var ype,wpe=b(()=>{l();ype={convertEVMChainIdToCoinType(e){if(e>=2147483648)throw new Error("Invalid chainId");return(2147483648|e)>>>0}}});var wc,$He,bm,OH=b(()=>{l();Lr();Hn();wpe();ma();gs();lp();$r();ai();To();gc();wc=rt({suggestions:[],loading:!1}),$He={state:wc,subscribe(e){return Dt(wc,()=>e(wc))},subscribeKey(e,t){return Tt(wc,e,t)},async resolveName(e){try{return await ze.lookupEnsName(e)}catch(t){let r=t;throw new Error(r?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await ze.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{wc.loading=!0,wc.suggestions=[];let t=await ze.getEnsNameSuggestions(e);return wc.suggestions=t.suggestions||[],wc.suggestions}catch(t){let r=bm.parseEnsApiError(t,"Error fetching name suggestions");throw new Error(r)}finally{wc.loading=!1}},async getNamesForAddress(e){try{if(!$.state.activeCaipNetwork)return[];let r=de.getEnsFromCacheForAddress(e);if(r)return r;let n=await ze.reverseLookupEnsName({address:e});return de.updateEnsCache({address:e,ens:n,timestamp:Date.now()}),n}catch(t){let r=bm.parseEnsApiError(t,"Error fetching names for address");throw new Error(r)}},async registerName(e){let t=$.state.activeCaipNetwork,r=$.getAccountData(t?.chainNamespace)?.address,n=re.getAuthConnector();if(!t)throw new Error("Network not found");if(!r||!n)throw new Error("Address or auth connector not found");wc.loading=!0;try{let o=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});J.pushTransactionStack({onCancel(){J.replace("RegisterAccountName")}});let s=await ee.signMessage(o);wc.loading=!1;let i=t.id;if(!i)throw new Error("Network not found");let a=ype.convertEVMChainIdToCoinType(Number(i));await ze.registerEnsName({coinType:a,address:r,signature:s,message:o}),$.setAccountProp("profileName",e,t.chainNamespace),de.updateEnsCache({address:r,ens:[{name:e,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),J.replace("RegisterAccountNameSuccess")}catch(o){let s=bm.parseEnsApiError(o,`Error registering name ${e}`);throw J.replace("RegisterAccountName"),new Error(s)}finally{wc.loading=!1}},validateName(e){return/^[a-zA-Z0-9-]{4,}$/u.test(e)},parseEnsApiError(e,t){return e?.reasons?.[0]?.description||t}},bm=vr($He)});function S_(e){try{return new URL(e)}catch{return null}}function FHe(e){let t=e.split("/"),r=t.length>0&&t[0]!==void 0?t[0]:"",n=r.lastIndexOf(":");return n===-1?{host:r}:{host:r.slice(0,n),port:r.slice(n+1)}}function zHe(e){let t=e.indexOf("://");if(t===-1)return null;let r=e.slice(0,t),n=t+3,o=e.indexOf("/",n);o===-1&&(o=e.length);let s=e.slice(n,o),i=s.lastIndexOf(":");return i===-1?{scheme:r,host:s}:{scheme:r,host:s.slice(0,i),port:s.slice(i+1)}}function bpe(e,t){if(t.includes("://")){let i=S_(t);return i?i.origin===e:!1}let{host:r,port:n}=FHe(t),o=e.indexOf("://");if(o!==-1){let i=o+3,a=e.indexOf("/",i);a===-1&&(a=e.length);let c=e.slice(i,a);if(n!==void 0)return`${r}:${n}`===c;let u=c.split(":")[0];return r===u}let s=S_(e);return s?n!==void 0?r===s.hostname&&n===(s.port||void 0):r===s.hostname:!1}function xpe(e,t,r){let n=r,o,s=n.indexOf("://");s!==-1&&(o=n.slice(0,s),n=n.slice(s+3));let i=n.indexOf("/");i!==-1&&(n=n.slice(0,i));let a=n,c,u=a.lastIndexOf(":");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let d=a.split(".");for(let w of d)if(w.includes("*")&&w!=="*")return!1;let f=e.protocol.replace(/:$/u,"");if(o&&o!==f||c!==void 0&&c!=="*"&&c!==e.port)return!1;let p=zHe(t),y=(p?p.host:e.hostname).split(".");if(d.length!==y.length)return!1;for(let w=d.length-1;w>=0;w-=1){let x=d[w],v=y[w];if(x!=="*"&&x!==v)return!1}return!0}var vpe=b(()=>{l()});var VHe,cl,I_=b(()=>{l();ut();OH();vpe();VHe={ton:["ton_sendMessage","ton_signData"],solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},cl={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(e){return VHe[e]||[]},createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};let r={...e},n=new Set;if(t.methods&&Object.keys(t.methods).forEach(o=>n.add(o)),t.chains&&Object.keys(t.chains).forEach(o=>n.add(o)),t.events&&Object.keys(t.events).forEach(o=>n.add(o)),t.rpcMap&&Object.keys(t.rpcMap).forEach(o=>{let[s]=o.split(":");s&&n.add(s)}),n.forEach(o=>{r[o]||(r[o]=this.createDefaultNamespace(o))}),t.methods&&Object.entries(t.methods).forEach(([o,s])=>{r[o]&&(r[o].methods=s)}),t.chains&&Object.entries(t.chains).forEach(([o,s])=>{r[o]&&(r[o].chains=s)}),t.events&&Object.entries(t.events).forEach(([o,s])=>{r[o]&&(r[o].events=s)}),t.rpcMap){let o=new Set;Object.entries(t.rpcMap).forEach(([s,i])=>{let[a,c]=s.split(":");!a||!c||!r[a]||(r[a].rpcMap||(r[a].rpcMap={}),o.has(a)||(r[a].rpcMap={},o.add(a)),r[a].rpcMap[c]=i)})}return r},createNamespaces(e,t){let r=e.reduce((n,o)=>{let{id:s,chainNamespace:i,rpcUrls:a}=o,c=a.default.http[0];n[i]||(n[i]=this.createDefaultNamespace(i));let u=`${i}:${s}`,d=n[i];switch(d.chains.push(u),u){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":d.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":d.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break;default:}return d?.rpcMap&&c&&(d.rpcMap[s]=c),n},{});return this.applyNamespaceOverrides(r,t)},resolveReownName:async e=>{let t=await bm.resolveName(e);return(t?.addresses?Object.values(t.addresses):[])[0]?.address||!1},getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{let r=t.chains||[],n=t.accounts.map(o=>{let[s,i]=o.split(":");return`${s}:${i}`});return Array.from(new Set([...r,...n]))})},isSessionEventData(e){return typeof e=="object"&&e!==null&&"id"in e&&"topic"in e&&"params"in e&&typeof e.params=="object"&&e.params!==null&&"chainId"in e.params&&"event"in e.params&&typeof e.params.event=="object"&&e.params.event!==null},isUserRejectedRequestError(e){try{if(typeof e=="object"&&e!==null){let t=e,r=typeof t.code=="number",n=r&&t.code===cl.RPC_ERROR_CODE.USER_REJECTED_METHODS,o=r&&t.code===cl.RPC_ERROR_CODE.USER_REJECTED;return n||o}return!1}catch{return!1}},isOriginAllowed(e,t,r){let n=[...t,...r];if(t.length===0)return!0;let o=S_(e);if(!o)return n.some(s=>!s.includes("*")&&s===e);if(o.hostname==="localhost"||o.hostname==="127.0.0.1")return!0;for(let s of n)if(s.includes("*")){if(xpe(o,e,s))return!0}else if(bpe(e,s))return!0;return!1},listenWcProvider({universalProvider:e,namespace:t,onConnect:r,onDisconnect:n,onAccountsChanged:o,onChainChanged:s,onDisplayUri:i}){r&&e.on("connect",()=>{let a=cl.getWalletConnectAccounts(e,t);r(a)}),n&&e.on("disconnect",()=>{n()}),o&&e.on("accountsChanged",a=>{try{let c=e.session?.namespaces?.[t]?.accounts||[],u=e.rpcProviders?.[t]?.getDefaultChain(),d=a.map(f=>{let p=c.find(w=>w.includes(`${t}:${u}:${f}`));if(!p)return;let{chainId:h,chainNamespace:y}=lt.parseCaipAddress(p);return{address:f,chainId:h,chainNamespace:y}}).filter(f=>f!==void 0);d.length>0&&o(d)}catch(c){console.warn("Failed to parse accounts for namespace on accountsChanged event",t,a,c)}}),s&&e.on("chainChanged",a=>{s(a)}),i&&e.on("display_uri",a=>{i(a)})},getWalletConnectAccounts(e,t){let r=new Set,n=e?.session?.namespaces?.[t]?.accounts?.map(o=>lt.parseCaipAddress(o)).filter(({address:o})=>r.has(o.toLowerCase())?!1:(r.add(o.toLowerCase()),!0));return n&&n.length>0?n:[]}}});var jHe,r5,Epe=b(()=>{l();C_();ut();yc();$n();I_();$r();To();E_();jHe=[Z.CONNECTOR_ID.AUTH,Z.CONNECTOR_ID.WALLET_CONNECT],r5=class{constructor(t){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=r=>$.getCaipNetworks(r),this.getConnectorId=r=>re.getConnectorId(r),t&&this.construct(t)}construct(t){this.projectId=t.projectId,this.namespace=t.namespace,this.adapterType=t.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:t,chainId:r}){let n=this.getCaipNetworks().filter(o=>o.chainNamespace===this.namespace).find(o=>o.id.toString()===r?.toString());t&&n&&this.addConnection({connectorId:Z.CONNECTOR_ID.AUTH,accounts:t,caipNetwork:n})}setAuthProvider(t){t.onConnect(this.onAuthConnected.bind(this)),t.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:Z.CONNECTOR_ID.AUTH,type:"AUTH",name:Z.CONNECTOR_NAMES.AUTH,provider:t,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...t){let r=new Set;this.availableConnectors=[...t,...this.availableConnectors].filter(n=>r.has(n.id)?!1:(r.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...t){let r=new Set;this.availableConnections=[...t,...this.availableConnections].filter(n=>r.has(n.connectorId.toLowerCase())?!1:(r.add(n.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(t){this.availableConnections=this.availableConnections.filter(r=>r.connectorId.toLowerCase()!==t.toLowerCase()),this.emit("connections",this.availableConnections)}clearConnections(t=!1){this.availableConnections=[],t&&this.emit("connections",this.availableConnections)}setStatus(t,r){$.setAccountProp("status",t,r)}on(t,r){this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t)?.add(r)}off(t,r){let n=this.eventListeners.get(t);n&&n.delete(r)}removeAllEventListeners(){this.eventListeners.forEach(t=>{t.clear()})}emit(t,r){let n=this.eventListeners.get(t);n&&n.forEach(o=>o(r))}async connectWalletConnect(t){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(r){throw cl.isUserRejectedRequestError(r)?new Z1(r):r}}async switchNetwork(t){let{caipNetwork:r}=t,n=ar.getProviderId(r.chainNamespace),o=ar.getProvider(r.chainNamespace);if(!o)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){o.setDefaultChain(r.caipNetworkId);return}if(n==="AUTH"){let s=re.getAuthConnector()?.provider;if(!s)throw new Error("Auth provider not found");let i=Fr(r.chainNamespace);await s.switchNetwork({chainId:r.caipNetworkId});let a=await s.getUser({chainId:r.caipNetworkId,preferredAccountType:i});this.emit("switchNetwork",a)}}getWalletConnectConnector(){let t=this.connectors.find(r=>r.id==="walletConnect");if(!t)throw new Error("WalletConnectConnector not found");return t}onConnect(t,r){if(t.length>0){let{address:n,chainId:o}=se.getAccount(t[0]),s=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===o?.toString()),i=this.connectors.find(a=>a.id===r);n&&(this.emit("accountChanged",{address:n,chainId:o,connector:i}),this.addConnection({connectorId:r,accounts:t.map(a=>{let{address:c}=se.getAccount(a);return{address:c}}),caipNetwork:s}))}}onAccountsChanged(t,r,n=!0){if(t.length>0){let{address:o}=se.getAccount(t[0]),s=this.getConnection({connectorId:r,connections:this.connections,connectors:this.connectors});o&&this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===r.toLowerCase()&&this.emit("accountChanged",{address:o,chainId:s?.caipNetwork?.id,connector:s?.connector}),this.addConnection({connectorId:r,accounts:t.map(i=>{let{address:a}=se.getAccount(i);return{address:a}}),caipNetwork:s?.caipNetwork})}else n&&this.onDisconnect(r)}onDisconnect(t){this.removeProviderListeners(t),this.deleteConnection(t),this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===t.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(t,r){let n=typeof t=="string"&&t.startsWith("0x")?parseInt(t,16).toString():t.toString(),o=this.getConnection({connectorId:r,connections:this.connections,connectors:this.connectors}),s=this.getCaipNetworks().filter(i=>i.chainNamespace===this.namespace).find(i=>i.id.toString()===n);o&&this.addConnection({connectorId:r,accounts:o.accounts,caipNetwork:s}),this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===r.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(t,r){if(jHe.includes(t))return;let n=i=>this.onAccountsChanged(i,t),o=i=>this.onChainChanged(i,t),s=()=>this.onDisconnect(t);this.providerHandlers[t]||(r.on("disconnect",s),r.on("accountsChanged",n),r.on("chainChanged",o),this.providerHandlers[t]={provider:r,disconnect:s,accountsChanged:n,chainChanged:o})}removeProviderListeners(t){if(this.providerHandlers[t]){let{provider:r,disconnect:n,accountsChanged:o,chainChanged:s}=this.providerHandlers[t];r.removeListener("disconnect",n),r.removeListener("accountsChanged",o),r.removeListener("chainChanged",s),this.providerHandlers[t]=null}}emitFirstAvailableConnection(){let t=this.getConnection({connections:this.connections,connectors:this.connectors});if(t){let[r]=t.accounts;this.emit("accountChanged",{address:r?.address,chainId:t.caipNetwork?.id,connector:t.connector})}}getConnection({address:t,connectorId:r,connections:n,connectors:o}){if(r){let i=n.find(u=>u.connectorId.toLowerCase()===r.toLowerCase());if(!i)return null;let a=o.find(u=>u.id.toLowerCase()===i.connectorId.toLowerCase()),c=t?i.accounts.find(u=>u.address.toLowerCase()===t.toLowerCase()):i.accounts[0];return{...i,account:c,connector:a}}let s=n.find(i=>i.accounts.length>0&&o.some(a=>a.id.toLowerCase()===i.connectorId.toLowerCase()));if(s){let[i]=s.accounts,a=o.find(c=>c.id.toLowerCase()===s.connectorId.toLowerCase());return{...s,account:i,connector:a}}return null}}});var ay,_o,T_=b(()=>{l();C_();ut();mm();$r();ai();To();mc();up();Un();gc();hm();yc();$n();ay=null,_o={getSIWX(){return Y.state.siwx},async initializeIfEnabled(e=$.getActiveCaipAddress()){let t=Y.state.siwx;if(!(t&&e))return;let[r,n,o]=e.split(":");if($.checkIfSupportedNetwork(r,`${r}:${n}`))try{if(Y.state.remoteFeatures?.emailCapture){let i=$.getAccountData(r)?.user;await De.open({view:"DataCapture",data:{email:i?.email??void 0}});return}if(ay&&await ay,(await t.getSessions(`${r}:${n}`,o)).length)return;await De.open({view:"SIWXSignMessage"})}catch(s){console.error("SIWXUtil:initializeIfEnabled",s),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(s)}),await ee._getClient()?.disconnect().catch(console.error),J.reset("Connect"),Je.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(e=$.getActiveCaipAddress()){if(!Y.state.siwx||!e)return!0;let{chainNamespace:r,chainId:n,address:o}=lt.parseCaipAddress(e),s=`${r}:${n}`;return(await _o.getSessions({address:o,caipNetworkId:s})).length>0},async requestSignMessage(){let e=Y.state.siwx,t=se.getPlainAddress($.getActiveCaipAddress()),r=oy();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!r)throw new Error("No ActiveCaipNetwork or client found");try{let n=await e.createMessage({chainId:r.caipNetworkId,accountAddress:t}),o=n.toString(),s="";e.signMessage?s=await e.signMessage({message:o,chainId:r.caipNetworkId,accountAddress:t}):(re.getConnectorId(r.chainNamespace)===Z.CONNECTOR_ID.AUTH&&J.pushTransactionStack({}),s=await ee.signMessage(o)||""),await e.addSession({data:n,message:o,signature:s}),$.setLastConnectedSIWECaipNetwork(r),De.close(),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(n){(!De.state.open||J.state.view==="ApproveTransaction")&&await De.open({view:"SIWXSignMessage"}),Je.showError("Error signing message"),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(n)}),console.error("SWIXUtil:requestSignMessage",n)}},async cancelSignMessage(){try{let e=this.getSIWX();if(e?.getRequired?.()){let r=$.getLastConnectedSIWECaipNetwork();if(r){let n=await e?.getSessions(r?.caipNetworkId,se.getPlainAddress($.getActiveCaipAddress())||"");n&&n.length>0?await $.switchActiveNetwork(r):await ee.disconnect()}else await ee.disconnect()}else De.close();De.close(),Ae.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){let e=this.getSIWX(),t=$.getAllRequestedCaipNetworks(),r=[];return await Promise.all(t.map(async n=>{let o=await e?.getSessions(n.caipNetworkId,se.getPlainAddress($.getActiveCaipAddress())||"");o&&r.push(...o)})),r},async getSessions(e){let t=Y.state.siwx,r=e?.address;if(!r){let o=$.getActiveCaipAddress();r=se.getPlainAddress(o)}let n=e?.caipNetworkId;return n||(n=$.getActiveCaipNetwork()?.caipNetworkId),t&&r&&n?t.getSessions(n,r):[]},async isSIWXCloseDisabled(){let e=this.getSIWX();if(e){let t=J.state.view==="ApproveTransaction",r=J.state.view==="SIWXSignMessage";if(t||r)return e.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:e,chainId:t,socialUri:r,preferredAccountType:n,chainNamespace:o}){let s=_o.getSIWX(),i=oy();if(!s||!o.includes(Z.CHAIN.EVM)||Y.state.remoteFeatures?.emailCapture){let f=await e.connect({chainId:t,socialUri:r,preferredAccountType:n});return{address:f.address,chainId:f.chainId,accounts:f.accounts}}let a=`${o}:${t}`,c=await s.createMessage({chainId:a,accountAddress:"<>"}),u={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await e.connect({chainId:t,socialUri:r,siwxMessage:u,preferredAccountType:n});return u.accountAddress=d.address,u.serializedMessage=d.message||"",d.signature&&d.message&&await _o.addEmbeddedWalletSession(u,d.message,d.signature),$.setLastConnectedSIWECaipNetwork(i),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(e,t,r){if(ay)return ay;let n=_o.getSIWX();return n?(ay=n.addSession({data:e,message:t,signature:r}).finally(()=>{ay=null}),ay):Promise.resolve()},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:r}){let n=_o.getSIWX(),o=oy(),s=new Set(t.map(u=>u.split(":")[0]));if(!n||s.size!==1||!s.has("eip155"))return!1;let i=await n.createMessage({chainId:oy()?.caipNetworkId||"",accountAddress:""}),a=await e.authenticate({nonce:i.nonce,domain:i.domain,uri:i.uri,exp:i.expirationTime,iat:i.issuedAt,nbf:i.notBefore,requestId:i.requestId,version:i.version,resources:i.resources,statement:i.statement,chainId:i.chainId,methods:r,chains:[i.chainId,...t.filter(u=>u!==i.chainId)]});Je.showLoading("Authenticating...",{autoClose:!1});let c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if($.setAccountProp("connectedWalletInfo",c,Array.from(s)[0]),a?.auths?.length){let u=a.auths.map(d=>{let f=e.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud??"",version:d.p.version||i.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:f,signature:d.s.s,cacao:d}});try{await n.setSessions(u),o&&$.setLastConnectedSIWECaipNetwork(o),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:_o.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:_o.getSIWXEventProperties(d)}),await e.disconnect().catch(console.error),d}finally{Je.hide()}}return!0},getSIWXEventProperties(e){let t=$.state.activeChain;if(!t)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:$.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Fr(t)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,message:e?se.parseError(e):void 0}},async clearSessions(){let e=this.getSIWX();e&&await e.setSessions([])}}});var n5,qHe,Ape=b(()=>{l();C_();ut();T_();I_();$r();Un();n5=class{constructor({provider:t,namespace:r}){this.id=Z.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=$.getCaipNetworks.bind($),this.caipNetworks=this.getCaipNetworks(),this.provider=t,this.chain=r}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){let r=this.getCaipNetworks(),n=Y.state.universalProviderConfigOverride,o=cl.createNamespaces(r,n);await this.provider.connect({optionalNamespaces:o})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){let t=this.chains.map(r=>r.caipNetworkId);return _o.universalProviderAuthenticate({universalProvider:this.provider,chains:t,methods:qHe})}},qHe=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"]});var pp,Cpe=b(()=>{l();ut();pp={getGasPriceInEther(e,t){let r=t*e;return Number(r)/1e18},getGasPriceInUSD(e,t,r){let n=pp.getGasPriceInEther(t,r);return ht.bigNumber(e).times(n).toNumber()},getPriceImpact({sourceTokenAmount:e,sourceTokenPriceInUSD:t,toTokenPriceInUSD:r,toTokenAmount:n}){let o=ht.bigNumber(e).times(t),s=ht.bigNumber(n).times(r);return o.minus(s).div(o).times(100).toNumber()},getMaxSlippage(e,t){let r=ht.bigNumber(e).div(100);return ht.multiply(t,r).toNumber()},getProviderFee(e,t=.0085){return ht.bigNumber(e).times(t).toString()},isInsufficientNetworkTokenForGas(e,t){let r=t||"0";return ht.bigNumber(e).eq(0)?!0:ht.bigNumber(ht.bigNumber(r)).gt(e)},isInsufficientSourceTokenForSwap(e,t,r){let n=r?.find(s=>s.address===t)?.quantity?.numeric;return ht.bigNumber(n||"0").lt(e)}}});var ll,WHe,sn,BH=b(()=>{l();Lr();Hn();ut();gs();Un();ll=rt({message:"",variant:"info",open:!1}),WHe={state:ll,subscribeKey(e,t){return Tt(ll,e,t)},open(e,t){let{debug:r}=Y.state,{code:n,displayMessage:o,debugMessage:s}=e;if(o&&r&&(ll.message=o,ll.variant=t,ll.open=!0),s){if(!Z.IS_DEVELOPMENT)return;let i=typeof s=="function"?s():s,a=n?{code:n}:void 0;t==="error"?console.error(i,a):t==="warning"?console.warn(i,a):console.info(i,a)}},warn(e,t,r){ll.open=!0,ll.message=e,ll.variant="warning",t&&console.warn(t,r)},close(){ll.open=!1,ll.message="",ll.variant="info"}},sn=vr(WHe)});var Spe,KHe,bs,Q,__,ot,Ipe=b(()=>{l();Lr();Hn();ut();ut();mm();L6();yc();ha();$n();TH();Cpe();gs();BH();lp();$r();ai();To();mc();gc();hm();Spe=15e4,KHe=6,bs={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,switchingTokens:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:Ye.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},Q=rt({...bs}),__={state:Q,subscribe(e){return Dt(Q,()=>e(Q))},subscribeKey(e,t){return Tt(Q,e,t)},getParams(){let e=$.state.activeChain,t=$.getAccountData(e)?.caipAddress??$.state.activeCaipAddress,r=se.getPlainAddress(t),n=U6(),o=re.getConnectorId($.state.activeChain);if(!r)throw new Error("No address found to swap the tokens from.");let s=!Q.toToken?.address||!Q.toToken?.decimals,i=!Q.sourceToken?.address||!Q.sourceToken?.decimals||!ht.bigNumber(Q.sourceTokenAmount).gt(0),a=!Q.sourceTokenAmount;return{networkAddress:n,fromAddress:r,fromCaipAddress:t,sourceTokenAddress:Q.sourceToken?.address,toTokenAddress:Q.toToken?.address,toTokenAmount:Q.toTokenAmount,toTokenDecimals:Q.toToken?.decimals,sourceTokenAmount:Q.sourceTokenAmount,sourceTokenDecimals:Q.sourceToken?.decimals,invalidToToken:s,invalidSourceToken:i,invalidSourceTokenAmount:a,availableToSwap:t&&!s&&!i&&!a,isAuthConnector:o===Z.CONNECTOR_ID.AUTH}},async setSourceToken(e){if(!e){Q.sourceToken=e,Q.sourceTokenAmount="",Q.sourceTokenPriceInUSD=0;return}Q.sourceToken=e,await ot.setTokenPrice(e.address,"sourceToken")},setSourceTokenAmount(e){Q.sourceTokenAmount=e},async setToToken(e){if(!e){Q.toToken=e,Q.toTokenAmount="",Q.toTokenPriceInUSD=0;return}Q.toToken=e,await ot.setTokenPrice(e.address,"toToken")},setToTokenAmount(e){Q.toTokenAmount=e?ht.toFixed(e,KHe):""},async setTokenPrice(e,t){let r=Q.tokensPriceMap[e]||0;r||(Q.loadingPrices=!0,r=await ot.getAddressPrice(e)),t==="sourceToken"?Q.sourceTokenPriceInUSD=r:t==="toToken"&&(Q.toTokenPriceInUSD=r),Q.loadingPrices&&(Q.loadingPrices=!1),ot.getParams().availableToSwap&&!Q.switchingTokens&&ot.swapTokens()},async switchTokens(){if(!(Q.initializing||!Q.initialized||Q.switchingTokens)){Q.switchingTokens=!0;try{let e=Q.toToken?{...Q.toToken}:void 0,t=Q.sourceToken?{...Q.sourceToken}:void 0,r=e&&Q.toTokenAmount===""?"1":Q.toTokenAmount;ot.setSourceTokenAmount(r),ot.setToTokenAmount(""),await ot.setSourceToken(e),await ot.setToToken(t),Q.switchingTokens=!1,ot.swapTokens()}catch(e){throw Q.switchingTokens=!1,e}}},resetState(){Q.myTokensWithBalance=bs.myTokensWithBalance,Q.tokensPriceMap=bs.tokensPriceMap,Q.initialized=bs.initialized,Q.initializing=bs.initializing,Q.switchingTokens=bs.switchingTokens,Q.sourceToken=bs.sourceToken,Q.sourceTokenAmount=bs.sourceTokenAmount,Q.sourceTokenPriceInUSD=bs.sourceTokenPriceInUSD,Q.toToken=bs.toToken,Q.toTokenAmount=bs.toTokenAmount,Q.toTokenPriceInUSD=bs.toTokenPriceInUSD,Q.networkPrice=bs.networkPrice,Q.networkTokenSymbol=bs.networkTokenSymbol,Q.networkBalanceInUSD=bs.networkBalanceInUSD,Q.inputError=bs.inputError},resetValues(){let{networkAddress:e}=ot.getParams(),t=Q.tokens?.find(r=>r.address===e);ot.setSourceToken(t),ot.setToToken(void 0)},getApprovalLoadingState(){return Q.loadingApprovalTransaction},clearError(){Q.transactionError=void 0},async initializeState(){if(!Q.initializing){if(Q.initializing=!0,!Q.initialized)try{await ot.fetchTokens(),Q.initialized=!0}catch{Q.initialized=!1,Je.showError("Failed to initialize swap"),J.goBack()}Q.initializing=!1}},async fetchTokens(){let{networkAddress:e}=ot.getParams();await ot.getNetworkTokenPrice(),await ot.getMyTokensWithBalance();let t=Q.myTokensWithBalance?.find(r=>r.address===e);t&&(Q.networkTokenSymbol=t.symbol,ot.setSourceToken(t),ot.setSourceTokenAmount("0"))},async getTokenList(){let e=$.state.activeCaipNetwork?.caipNetworkId;if(!(Q.caipNetworkId===e&&Q.tokens))try{Q.tokensLoading=!0;let t=await ym.getTokenList(e);Q.tokens=t,Q.caipNetworkId=e,Q.popularTokens=t.sort((i,a)=>i.symbola.symbol?1:0);let n=(e&&Ye.SUGGESTED_TOKENS_BY_CHAIN?.[e]||[]).map(i=>t.find(a=>a.symbol===i)).filter(i=>!!i),s=(Ye.SWAP_SUGGESTED_TOKENS||[]).map(i=>t.find(a=>a.symbol===i)).filter(i=>!!i).filter(i=>!n.some(a=>a.address===i.address));Q.suggestedTokens=[...n,...s]}catch{Q.tokens=[],Q.popularTokens=[],Q.suggestedTokens=[]}finally{Q.tokensLoading=!1}},async getAddressPrice(e){let t=Q.tokensPriceMap[e];if(t)return t;let n=(await ze.fetchTokenPrice({addresses:[e]}))?.fungibles||[],s=[...Q.tokens||[],...Q.myTokensWithBalance||[]]?.find(c=>c.address===e)?.symbol,i=n.find(c=>c.symbol.toLowerCase()===s?.toLowerCase())?.price||0,a=parseFloat(i.toString());return Q.tokensPriceMap[e]=a,a},async getNetworkTokenPrice(){let{networkAddress:e}=ot.getParams(),r=(await ze.fetchTokenPrice({addresses:[e]}).catch(()=>(Je.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],n=r?.price.toString()||"0";Q.tokensPriceMap[e]=parseFloat(n),Q.networkTokenSymbol=r?.symbol||"",Q.networkPrice=n},async getMyTokensWithBalance(e){let t=await al.getMyTokensWithBalance({forceUpdate:e,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address}),r=ym.mapBalancesToSwapTokens(t);r&&(await ot.getInitialGasPrice(),ot.setBalances(r))},setBalances(e){let{networkAddress:t}=ot.getParams(),r=$.state.activeCaipNetwork;if(!r)return;let n=e.find(o=>o.address===t);e.forEach(o=>{Q.tokensPriceMap[o.address]=o.price||0}),Q.myTokensWithBalance=e.filter(o=>o.address.startsWith(r.caipNetworkId)),Q.networkBalanceInUSD=n?ht.multiply(n.quantity.numeric,n.price).toString():"0"},async getInitialGasPrice(){let e=await ym.fetchGasPrice();if(!e)return{gasPrice:null,gasPriceInUSD:null};switch($.state?.activeCaipNetwork?.chainNamespace){case Z.CHAIN.SOLANA:return Q.gasFee=e.standard??"0",Q.gasPriceInUSD=ht.multiply(e.standard,Q.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(Q.gasFee),gasPriceInUSD:Number(Q.gasPriceInUSD)};case Z.CHAIN.EVM:default:let t=e.standard??"0",r=BigInt(t),n=BigInt(Spe),o=pp.getGasPriceInUSD(Q.networkPrice,n,r);return Q.gasFee=t,Q.gasPriceInUSD=o,{gasPrice:r,gasPriceInUSD:o}}},async swapTokens(){let e=$.getAccountData()?.address,t=Q.sourceToken,r=Q.toToken,n=ht.bigNumber(Q.sourceTokenAmount).gt(0);if(n||ot.setToTokenAmount(""),!r||!t||Q.loadingPrices||!n||!e)return;Q.loadingQuote=!0;let o=ht.bigNumber(Q.sourceTokenAmount).times(10**t.decimals).round(0).toFixed(0);try{let s=await ze.fetchSwapQuote({userAddress:e,from:t.address,to:r.address,gasPrice:Q.gasFee,amount:o.toString()});Q.loadingQuote=!1;let i=s?.quotes?.[0]?.toAmount;if(!i){sn.open({displayMessage:"Incorrect amount",debugMessage:"Please enter a valid amount"},"error");return}let a=ht.bigNumber(i).div(10**r.decimals).toString();ot.setToTokenAmount(a),ot.hasInsufficientToken(Q.sourceTokenAmount,t.address)?Q.inputError="Insufficient balance":(Q.inputError=void 0,ot.setTransactionDetails())}catch(s){let i=await ym.handleSwapError(s);Q.loadingQuote=!1,Q.inputError=i||"Insufficient balance"}},async getTransaction(){let{fromCaipAddress:e,availableToSwap:t}=ot.getParams(),r=Q.sourceToken,n=Q.toToken;if(!(!e||!t||!r||!n||Q.loadingQuote))try{Q.loadingBuildTransaction=!0;let o=await ym.fetchSwapAllowance({userAddress:e,tokenAddress:r.address,sourceTokenAmount:Q.sourceTokenAmount,sourceTokenDecimals:r.decimals}),s;return o?s=await ot.createSwapTransaction():s=await ot.createAllowanceTransaction(),Q.loadingBuildTransaction=!1,Q.fetchError=!1,s}catch{J.goBack(),Je.showError("Failed to check allowance"),Q.loadingBuildTransaction=!1,Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}},async createAllowanceTransaction(){let{fromCaipAddress:e,sourceTokenAddress:t,toTokenAddress:r}=ot.getParams();if(!(!e||!r)){if(!t)throw new Error("createAllowanceTransaction - No source token address found.");try{let n=await ze.generateApproveCalldata({from:t,to:r,userAddress:e}),o=se.getPlainAddress(n.tx.from);if(!o)throw new Error("SwapController:createAllowanceTransaction - address is required");let s={data:n.tx.data,to:o,gasPrice:BigInt(n.tx.eip155.gasPrice),value:BigInt(n.tx.value),toAmount:Q.toTokenAmount};return Q.swapTransaction=void 0,Q.approvalTransaction={data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount},{data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount}}catch{J.goBack(),Je.showError("Failed to create approval transaction"),Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}}},async createSwapTransaction(){let{networkAddress:e,fromCaipAddress:t,sourceTokenAmount:r}=ot.getParams(),n=Q.sourceToken,o=Q.toToken;if(!t||!r||!n||!o)return;let s=ee.parseUnits(r,n.decimals)?.toString();try{let i=await ze.generateSwapCalldata({userAddress:t,from:n.address,to:o.address,amount:s,disableEstimate:!0}),a=n.address===e,c=BigInt(i.tx.eip155.gas),u=BigInt(i.tx.eip155.gasPrice),d=se.getPlainAddress(i.tx.to);if(!d)throw new Error("SwapController:createSwapTransaction - address is required");let f={data:i.tx.data,to:d,gas:c,gasPrice:u,value:BigInt(a?s??"0":"0"),toAmount:Q.toTokenAmount};return Q.gasPriceInUSD=pp.getGasPriceInUSD(Q.networkPrice,c,u),Q.approvalTransaction=void 0,Q.swapTransaction=f,f}catch{J.goBack(),Je.showError("Failed to create transaction"),Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}},onEmbeddedWalletApprovalSuccess(){Je.showLoading("Approve limit increase in your wallet"),J.replace("SwapPreview")},async sendTransactionForApproval(e){let{fromAddress:t,isAuthConnector:r}=ot.getParams();Q.loadingApprovalTransaction=!0,r?J.pushTransactionStack({onSuccess:ot.onEmbeddedWalletApprovalSuccess}):Je.showLoading("Approve limit increase in your wallet");try{await ee.sendTransaction({address:t,to:e.to,data:e.data,value:e.value,chainNamespace:Z.CHAIN.EVM}),await ot.swapTokens(),await ot.getTransaction(),Q.approvalTransaction=void 0,Q.loadingApprovalTransaction=!1}catch(o){let s=o;Q.transactionError=s?.displayMessage,Q.loadingApprovalTransaction=!1,Je.showError(s?.displayMessage||"Transaction error"),Ae.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.displayMessage||s?.message||"Unknown",network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(e){if(!e)return;let{fromAddress:t,toTokenAmount:r,isAuthConnector:n}=ot.getParams();Q.loadingTransaction=!0;let o=`Swapping ${Q.sourceToken?.symbol} to ${ht.formatNumberToLocalString(r,3)} ${Q.toToken?.symbol}`,s=`Swapped ${Q.sourceToken?.symbol} to ${ht.formatNumberToLocalString(r,3)} ${Q.toToken?.symbol}`;n?J.pushTransactionStack({onSuccess(){J.replace("Account"),Je.showLoading(o),__.resetState()}}):Je.showLoading("Confirm transaction in your wallet");try{let i=[Q.sourceToken?.address,Q.toToken?.address].join(","),a=await ee.sendTransaction({address:t,to:e.to,data:e.data,value:e.value,chainNamespace:Z.CHAIN.EVM});return Q.loadingTransaction=!1,Je.showSuccess(s),Ae.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),__.resetState(),n||J.replace("Account"),__.getMyTokensWithBalance(i),a}catch(i){let a=i;Q.transactionError=a?.displayMessage,Q.loadingTransaction=!1,Je.showError(a?.displayMessage||"Transaction error"),Ae.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:a?.displayMessage||a?.message||"Unknown",network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(e,t){return pp.isInsufficientSourceTokenForSwap(e,t,Q.myTokensWithBalance)},setTransactionDetails(){let{toTokenAddress:e,toTokenDecimals:t}=ot.getParams();!e||!t||(Q.gasPriceInUSD=pp.getGasPriceInUSD(Q.networkPrice,BigInt(Q.gasFee),BigInt(Spe)),Q.priceImpact=pp.getPriceImpact({sourceTokenAmount:Q.sourceTokenAmount,sourceTokenPriceInUSD:Q.sourceTokenPriceInUSD,toTokenPriceInUSD:Q.toTokenPriceInUSD,toTokenAmount:Q.toTokenAmount}),Q.maxSlippage=pp.getMaxSlippage(Q.slippage,Q.toTokenAmount),Q.providerFee=pp.getProviderFee(Q.sourceTokenAmount))}},ot=vr(__)});var ul,ZHe,ci,Tpe=b(()=>{l();Lr();Hn();gs();ul=rt({message:"",open:!1,triggerRect:{width:0,height:0,top:0,left:0},variant:"shade"}),ZHe={state:ul,subscribe(e){return Dt(ul,()=>e(ul))},subscribeKey(e,t){return Tt(ul,e,t)},showTooltip({message:e,triggerRect:t,variant:r}){ul.open=!0,ul.message=e,ul.triggerRect=t,ul.variant=r},hide(){ul.open=!1,ul.message="",ul.triggerRect={width:0,height:0,top:0,left:0}}},ci=vr(ZHe)});var kH,UH,_pe=b(()=>{l();kH={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},UH={network:"eip155:84532",asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}}});var o5,Ppe=b(()=>{l();ai();up();gc();T_();o5={isUnsupportedChainView(){return J.state.view==="UnsupportedChain"||J.state.view==="SwitchNetwork"&&J.state.history.includes("UnsupportedChain")},async safeClose(){if(this.isUnsupportedChainView()){De.shake();return}if(await _o.isSIWXCloseDisabled()){De.shake();return}(J.state.view==="DataCapture"||J.state.view==="DataCaptureOtpConfirm")&&ee.disconnect(),De.close()}}});var ct=b(()=>{l();up();gc();$r();E_();hpe();IH();Epe();Ape();ai();AH();To();hm();Cu();y_();vH();Un();lp();Q3();mc();Ipe();_H();Tpe();OH();BH();yH();ha();bH();$n();w_();ma();T_();Ppe();gs();_pe();O6();yc();I_()});var Ope,GHe,YHe,Npe,P_,JHe,QHe,XHe,N_,R_,O_,B_,k_,U_,D_,L_,M_,H_,e$e,t$e,Rpe,$_,F_,DH=b(()=>{l();tS();Ope=Ht(ks()),GHe=Object.defineProperty,YHe=(e,t,r)=>t in e?GHe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Npe=(e,t,r)=>YHe(e,typeof t!="symbol"?t+"":t,r),P_=class extends yo{constructor(t){super(),this.opts=t,Npe(this,"protocol","wc"),Npe(this,"version",2)}},JHe=Object.defineProperty,QHe=(e,t,r)=>t in e?JHe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,XHe=(e,t,r)=>QHe(e,typeof t!="symbol"?t+"":t,r),N_=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r,XHe(this,"records",new Map)}},R_=class{constructor(t,r){this.logger=t,this.core=r}},O_=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},B_=class extends yo{constructor(t){super()}},k_=class{constructor(t,r,n,o){this.core=t,this.logger=r,this.name=n}},U_=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},D_=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r}},L_=class{constructor(t,r,n){this.core=t,this.logger=r,this.store=n}},M_=class{constructor(t,r){this.projectId=t,this.logger=r}},H_=class{constructor(t,r,n){this.core=t,this.logger=r,this.telemetryEnabled=n}},e$e=Object.defineProperty,t$e=(e,t,r)=>t in e?e$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Rpe=(e,t,r)=>t$e(e,typeof t!="symbol"?t+"":t,r),$_=class{constructor(t){this.opts=t,Rpe(this,"protocol","wc"),Rpe(this,"version",2)}},F_=class{constructor(t){this.client=t}}});var Bpe=b(()=>{l()});var kpe,Upe=b(()=>{l();kpe="0.1.1"});function Dpe(){return kpe}var Lpe=b(()=>{l();Upe()});function Mpe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?Mpe(e.cause,t):t?null:e}var zt,xm=b(()=>{l();Lpe();zt=class e extends Error{constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=`https://oxlib.sh${o??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0]:[]].filter(c=>typeof c=="string").join(` +`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Dpe()}`}),this.cause=r.cause,this.details=n,this.docs=i,this.docsPath=o,this.shortMessage=t}walk(t){return Mpe(this,t)}}});var ly,Hpe=b(()=>{l();ly=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function n$e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function uy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Su(e,...t){if(!n$e(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function $pe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");uy(e.outputLen),uy(e.blockLen)}function hp(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function z_(e,t){Su(e);let r=t.outputLen;if(e.length>>t}function s$e(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function i$e(e){for(let t=0;te().update(dy(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Vpe(e=32){if(ly&&typeof ly.getRandomValues=="function")return ly.getRandomValues(new Uint8Array(e));if(ly&&typeof ly.randomBytes=="function")return Uint8Array.from(ly.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var o$e,LH,vm,fy=b(()=>{l();Hpe();o$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;LH=o$e?e=>e:i$e;vm=class{}});function c$e(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function jpe(e,t,r){return e&t^~e&r}function qpe(e,t,r){return e&t^e&r^t&r}var q_,mp,Wpe=b(()=>{l();fy();q_=class extends vm{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=V_(this.buffer)}update(t){hp(this),t=dy(t),Su(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>Kpe&W_)}:{h:Number(e>>Kpe&W_)|0,l:Number(e&W_)|0}}function Zpe(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s{l();W_=BigInt(4294967295),Kpe=BigInt(32);Gpe=(e,t,r)=>e<>>32-r,Ype=(e,t,r)=>t<>>32-r,Jpe=(e,t,r)=>t<>>64-r,Qpe=(e,t,r)=>e<>>64-r});function y$e(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=ehe(u,d,1)^r[a],p=the(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=nhe[i],c=ehe(o,s,a),u=the(o,s,a),d=rhe[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=m$e[n],e[1]^=g$e[n]}Iu(r)}var u$e,s5,d$e,f$e,p$e,h$e,rhe,nhe,ohe,she,m$e,g$e,ehe,the,MH,w$e,ihe,ahe=b(()=>{l();Xpe();fy();u$e=BigInt(0),s5=BigInt(1),d$e=BigInt(2),f$e=BigInt(7),p$e=BigInt(256),h$e=BigInt(113),rhe=[],nhe=[],ohe=[];for(let e=0,t=s5,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],rhe.push(2*(5*n+r)),nhe.push((e+1)*(e+2)/2%64);let o=u$e;for(let s=0;s<7;s++)t=(t<>f$e)*h$e)%p$e,t&d$e&&(o^=s5<<(s5<r>32?Jpe(e,t,r):Gpe(e,t,r),the=(e,t,r)=>r>32?Qpe(e,t,r):Ype(e,t,r);MH=class e extends vm{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,uy(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return uy(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(z_(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Iu(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},w$e=(e,t,r)=>j_(()=>new MH(t,e,r)),ihe=w$e(1,136,256/8)});var b$e,Em,HH,che,lhe=b(()=>{l();Wpe();fy();b$e=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Em=new Uint32Array(64),HH=class extends q_{constructor(t=32){super(64,t,8,!1),this.A=mp[0]|0,this.B=mp[1]|0,this.C=mp[2]|0,this.D=mp[3]|0,this.E=mp[4]|0,this.F=mp[5]|0,this.G=mp[6]|0,this.H=mp[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)Em[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=Em[f-15],h=Em[f-2],y=dl(p,7)^dl(p,18)^p>>>3,w=dl(h,17)^dl(h,19)^h>>>10;Em[f]=w+Em[f-7]+y+Em[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=dl(a,6)^dl(a,11)^dl(a,25),h=d+p+jpe(a,c,u)+b$e[f]+Em[f]|0,w=(dl(n,2)^dl(n,13)^dl(n,22))+qpe(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){Iu(Em)}destroy(){this.set(0,0,0,0,0,0,0,0),Iu(this.buffer)}},che=j_(()=>new HH)});function M6(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function jH(e){if(!M6(e))throw new Error("Uint8Array expected")}function H6(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function i5(e){let t=e.toString(16);return t.length&1?"0"+t:t}function fhe(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?VH:BigInt("0x"+e)}function $6(e){if(jH(e),phe)return e.toHex();let t="";for(let r=0;r=gp._0&&e<=gp._9)return e-gp._0;if(e>=gp.A&&e<=gp.F)return e-(gp.A-10);if(e>=gp.a&&e<=gp.f)return e-(gp.a-10)}function a5(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(phe)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oVH;e>>=zH,t+=1);return t}function mhe(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=FH(e),o=FH(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=FH(0))=>{o=a(dhe([0]),f),n=a(),f.length!==0&&(o=a(dhe([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}function gy(e,t,r={}){let n=(o,s,i)=>{let a=v$e[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function KH(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var VH,zH,phe,x$e,gp,$H,my,FH,dhe,v$e,Z_=b(()=>{l();VH=BigInt(0),zH=BigInt(1);phe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",x$e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));gp={_0:48,_9:57,A:65,F:70,a:97,f:102};$H=e=>typeof e=="bigint"&&VH<=e;my=e=>(zH<new Uint8Array(e),dhe=e=>Uint8Array.from(e);v$e={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||M6(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function ghe(e,t){if(ZH(e)>t)throw new G_({givenSize:ZH(e),maxSize:t})}function GH(e){if(e>=wp.zero&&e<=wp.nine)return e-wp.zero;if(e>=wp.A&&e<=wp.F)return e-(wp.A-10);if(e>=wp.a&&e<=wp.f)return e-(wp.a-10)}function yhe(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new Y_({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;s{l();Am();wp={zero:48,nine:57,A:65,F:70,a:97,f:102}});function l5(e,t){if($i(e)>t)throw new J_({givenSize:$i(e),maxSize:t})}function bhe(e,t){if(typeof t=="number"&&t>0&&t>$i(e)-1)throw new u5({offset:t,position:"start",size:$i(e)})}function xhe(e,t,r){if(typeof t=="number"&&typeof r=="number"&&$i(e)!==r-t)throw new u5({offset:r,position:"end",size:$i(e)})}function YH(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new Q_({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function vhe(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;s{l();bp()});function Sm(e,t,r){return JSON.stringify(e,(n,o)=>typeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+A$e:o,r)}var A$e,F6=b(()=>{l();A$e="#__bigint"});function I$e(e,t={}){let{strict:r=!1}=t;if(!e)throw new X_(e);if(typeof e!="string")throw new X_(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new e7(e);if(!e.startsWith("0x"))throw new e7(e)}function wy(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Tu(e){return e instanceof Uint8Array?li(e):Array.isArray(e)?li(new Uint8Array(e)):e}function Ahe(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(l5(r,t.size),f5(r,t.size)):r}function li(e,t={}){let r="";for(let o=0;os||o{l();xm();JH();F6();C$e=new TextEncoder,S$e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));QH=class extends zt{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},X_=class extends zt{constructor(t){super(`Value \`${typeof t=="object"?Sm(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},e7=class extends zt{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},J_=class extends zt{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},u5=class extends zt{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},Q_=class extends zt{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function _$e(e){if(!(e instanceof Uint8Array)){if(!e)throw new z6(e);if(typeof e!="object")throw new z6(e);if(!("BYTES_PER_ELEMENT"in e))throw new z6(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new z6(e)}}function V6(e){return e instanceof Uint8Array?e:typeof e=="string"?h5(e):P$e(e)}function P$e(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function h5(e,t={}){let{size:r}=t,n=e;r&&(l5(e,r),n=p5(e,r));let o=n.slice(2);o.length%2&&(o=`0${o}`);let s=o.length/2,i=new Uint8Array(s);for(let a=0,c=0;a{l();xm();bp();whe();JH();F6();T$e=new TextEncoder;z6=class extends zt{constructor(t){super(`Value \`${typeof t=="object"?Sm(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},G_=class extends zt{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},Y_=class extends zt{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function t$(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=ihe(V6(e));return r==="Bytes"?n:li(n)}var r$=b(()=>{l();ahe();Am();bp()});var t7,_he=b(()=>{l();t7=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});var R$e,r7,n$=b(()=>{l();_he();R$e={checksum:new t7(8192)},r7=R$e.checksum});function Nhe(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new n7({prefix:n,cause:new i$});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new n7({prefix:n,cause:new s$});return}throw new o$({publicKey:e})}function c$(e){let t=(()=>{if(e$(e))return Rhe(e);if(Ihe(e))return O$e(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return Nhe(t),t}function O$e(e){return Rhe(li(e))}function Rhe(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new a$({publicKey:e});if(e.length===130){let n=BigInt(fl(e,0,32)),o=BigInt(fl(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(fl(e,0,1)),o=BigInt(fl(e,1,33)),s=BigInt(fl(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(fl(e,0,1)),r=BigInt(fl(e,1,33));return{prefix:t,x:r}}function Ohe(e,t={}){return h5(m5(e,t))}function m5(e,t={}){Nhe(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return wy(s?ui(r,{size:1}):"0x",ui(n,{size:32}),typeof o=="bigint"?ui(o,{size:32}):"0x")}var o$,n7,s$,i$,a$,o7=b(()=>{l();Am();xm();bp();F6();o$=class extends zt{constructor({publicKey:t}){super(`Value \`${Sm(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},n7=class extends zt{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},s$=class extends zt{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},i$=class extends zt{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},a$=class extends zt{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${$i(Tu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});function j6(e,t={}){let{strict:r=!0}=t;if(!B$e.test(e))throw new s7({address:e,cause:new u$});if(r){if(e.toLowerCase()===e)return;if(Bhe(e)!==e)throw new s7({address:e,cause:new d$})}}function Bhe(e){if(r7.has(e))return r7.get(e);j6(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=t$(She(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return r7.set(e,o),o}function k$e(e,t={}){let{checksum:r=!1}=t;return j6(e),r?Bhe(e):e}function khe(e,t={}){let r=t$(`0x${m5(e).slice(4)}`).substring(26);return k$e(`0x${r}`,t)}function Uhe(e,t){return j6(e,{strict:!1}),j6(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}var B$e,s7,u$,d$,i7=b(()=>{l();Am();n$();xm();r$();o7();B$e=/^0x[a-fA-F0-9]{40}$/;s7=class extends zt{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},u$=class extends zt{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},d$=class extends zt{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});var Dhe=b(()=>{l()});var Lhe,Mhe,Hhe,Hir,$ir,Fir,zir,Vir,jir,qir,Wir,Kir,Zir,Gir,Yir,Jir,Qir,Xir,ear,tar,rar,nar,oar,sar,iar,aar,car,lar,uar,dar,far,par,har,mar,gar,yar,war,bar,xar,Ear,Aar,Car,Sar,Iar,Tar,_ar,Par,Nar,Rar,Oar,Bar,kar,Uar,Dar,Lar,Mar,Har,$ar,Far,zar,Var,jar,qar,War,Kar,Zar,Gar,Yar,Jar,Qar,Xar,ecr,tcr,rcr,ncr,ocr,scr,icr,acr,ccr,lcr,ucr,dcr,fcr,pcr,hcr,mcr,gcr,ycr,wcr,bcr,xcr,vcr,Ecr,Acr,Ccr,Scr,Icr,p$,a7=b(()=>{l();Lhe=/^(.*)\[([0-9]*)\]$/,Mhe=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Hhe=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Hir=2n**(8n-1n)-1n,$ir=2n**(16n-1n)-1n,Fir=2n**(24n-1n)-1n,zir=2n**(32n-1n)-1n,Vir=2n**(40n-1n)-1n,jir=2n**(48n-1n)-1n,qir=2n**(56n-1n)-1n,Wir=2n**(64n-1n)-1n,Kir=2n**(72n-1n)-1n,Zir=2n**(80n-1n)-1n,Gir=2n**(88n-1n)-1n,Yir=2n**(96n-1n)-1n,Jir=2n**(104n-1n)-1n,Qir=2n**(112n-1n)-1n,Xir=2n**(120n-1n)-1n,ear=2n**(128n-1n)-1n,tar=2n**(136n-1n)-1n,rar=2n**(144n-1n)-1n,nar=2n**(152n-1n)-1n,oar=2n**(160n-1n)-1n,sar=2n**(168n-1n)-1n,iar=2n**(176n-1n)-1n,aar=2n**(184n-1n)-1n,car=2n**(192n-1n)-1n,lar=2n**(200n-1n)-1n,uar=2n**(208n-1n)-1n,dar=2n**(216n-1n)-1n,far=2n**(224n-1n)-1n,par=2n**(232n-1n)-1n,har=2n**(240n-1n)-1n,mar=2n**(248n-1n)-1n,gar=2n**(256n-1n)-1n,yar=-(2n**(8n-1n)),war=-(2n**(16n-1n)),bar=-(2n**(24n-1n)),xar=-(2n**(32n-1n)),Ear=-(2n**(40n-1n)),Aar=-(2n**(48n-1n)),Car=-(2n**(56n-1n)),Sar=-(2n**(64n-1n)),Iar=-(2n**(72n-1n)),Tar=-(2n**(80n-1n)),_ar=-(2n**(88n-1n)),Par=-(2n**(96n-1n)),Nar=-(2n**(104n-1n)),Rar=-(2n**(112n-1n)),Oar=-(2n**(120n-1n)),Bar=-(2n**(128n-1n)),kar=-(2n**(136n-1n)),Uar=-(2n**(144n-1n)),Dar=-(2n**(152n-1n)),Lar=-(2n**(160n-1n)),Mar=-(2n**(168n-1n)),Har=-(2n**(176n-1n)),$ar=-(2n**(184n-1n)),Far=-(2n**(192n-1n)),zar=-(2n**(200n-1n)),Var=-(2n**(208n-1n)),jar=-(2n**(216n-1n)),qar=-(2n**(224n-1n)),War=-(2n**(232n-1n)),Kar=-(2n**(240n-1n)),Zar=-(2n**(248n-1n)),Gar=-(2n**(256n-1n)),Yar=2n**8n-1n,Jar=2n**16n-1n,Qar=2n**24n-1n,Xar=2n**32n-1n,ecr=2n**40n-1n,tcr=2n**48n-1n,rcr=2n**56n-1n,ncr=2n**64n-1n,ocr=2n**72n-1n,scr=2n**80n-1n,icr=2n**88n-1n,acr=2n**96n-1n,ccr=2n**104n-1n,lcr=2n**112n-1n,ucr=2n**120n-1n,dcr=2n**128n-1n,fcr=2n**136n-1n,pcr=2n**144n-1n,hcr=2n**152n-1n,mcr=2n**160n-1n,gcr=2n**168n-1n,ycr=2n**176n-1n,wcr=2n**184n-1n,bcr=2n**192n-1n,xcr=2n**200n-1n,vcr=2n**208n-1n,Ecr=2n**216n-1n,Acr=2n**224n-1n,Ccr=2n**232n-1n,Scr=2n**240n-1n,Icr=2n**248n-1n,p$=2n**256n-1n});function m$(e,t){if(e.length!==t.length)throw new y$({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n{l();i7();xm();bp();a7();(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return j6(c),f5(c.toLowerCase(),o?32:0)}if(r==="string")return Che(n);if(r==="bytes")return n;if(r==="bool")return f5(Ahe(n),o?32:1);let s=r.match(Hhe);if(s){let[c,u,d="256"]=s,f=Number.parseInt(d,10)/8;return ui(n,{size:o?32:f,signed:u==="int"})}let i=r.match(Mhe);if(i){let[c,u]=i;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new g$({expectedSize:Number.parseInt(u,10),value:n});return p5(n,o?32:0)}let a=r.match(Lhe);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let f=0;f{l()});var zhe=b(()=>{l()});var Vhe=b(()=>{l()});var jhe=b(()=>{l()});var qhe=b(()=>{l()});var Whe=b(()=>{l()});var Khe=b(()=>{l()});var Zhe=b(()=>{l()});var c7,b$,Ghe=b(()=>{l();fy();c7=class extends vm{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,$pe(t);let n=dy(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew c7(e,t).update(r).digest();b$.create=(e,t)=>new c7(e,t)});function xs(e,t){let r=e%t;return r>=di?r:t+r}function Ra(e,t,r){let n=e;for(;t-- >di;)n*=n,n%=r;return n}function l7(e,t){if(e===di)throw new Error("invert: expected non-zero number");if(t<=di)throw new Error("invert: expected positive modulus, got "+t);let r=xs(e,t),n=t,o=di,s=vs,i=vs,a=di;for(;r!==di;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==vs)throw new Error("invert: does not exist");return xs(o,t)}function e0e(e,t){let r=(e.ORDER+vs)/Jhe,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function q$e(e,t){let r=(e.ORDER-Qhe)/Xhe,n=e.mul(t,by),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,by),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function W$e(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return e0e;let s=o.pow(n,t),i=(t+vs)/by;return function(c,u){if(c.is0(u))return u;if(Yhe(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=vs<(n[o]="function",n),t);return gy(e,r)}function G$e(e,t,r){if(rdi;)r&vs&&(n=e.mul(n,o)),o=e.sqr(o),r>>=vs;return n}function v$(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function Yhe(e,t){let r=(e.ORDER-vs)/by,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function E$(e,t){t!==void 0&&uy(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function g5(e,t,r=!1,n={}){if(e<=di)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=E$(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:my(o),ZERO:di,ONE:vs,create:c=>xs(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return di<=c&&cc===di,isOdd:c=>(c&vs)===vs,neg:c=>xs(-c,e),eql:(c,u)=>c===u,sqr:c=>xs(c*c,e),add:(c,u)=>xs(c+u,e),sub:(c,u)=>xs(c-u,e),mul:(c,u)=>xs(c*u,e),pow:(c,u)=>G$e(a,c,u),div:(c,u)=>xs(c*l7(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>l7(c,e),sqrt:n.sqrt||(c=>(i||(i=K$e(e)),i(a,c))),toBytes:c=>r?WH(c,s):py(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?qH(c):yp(c)},invertBatch:c=>v$(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function t0e(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function A$(e){let t=t0e(e);return t+Math.ceil(t/2)}function r0e(e,t,r=!1){let n=e.length,o=t0e(t),s=A$(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?qH(e):yp(e),a=xs(i,t-vs)+vs;return r?WH(a,o):py(a,o)}var di,vs,by,j$e,Jhe,Qhe,Xhe,Z$e,u7=b(()=>{l();fy();Z_();di=BigInt(0),vs=BigInt(1),by=BigInt(2),j$e=BigInt(3),Jhe=BigInt(4),Qhe=BigInt(5),Xhe=BigInt(8);Z$e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function C$(e,t){let r=t.negate();return e?r:t}function s0e(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function S$(e,t){s0e(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=my(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function o0e(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=_$);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function Y$e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function J$e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function T$(e){return i0e.get(e)||1}function a0e(e,t){return{constTimeNegate:C$,hasPrecomputes(r){return T$(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>n0e;)n&_$&&(o=o.add(s)),s=s.double(),n>>=_$;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=S$(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=my(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{l();u7();Z_();n0e=BigInt(0),_$=BigInt(1);I$=new WeakMap,i0e=new WeakMap});function u0e(e){e.lowS!==void 0&&H6("lowS",e.lowS),e.prehash!==void 0&&H6("prehash",e.prehash)}function Q$e(e){let t=P$(e);gy(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function N$(e,t){return $6(py(e,t))}function eFe(e){let t=Q$e(e),{Fp:r}=t,n=g5(t.n,t.nBitLength),o=t.toBytes||((E,S,_)=>{let O=S.toAffine();return c5(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,R$),X$e),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return K_(E,Po,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(M6(E)&&(E=$6(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:yp(Hi("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=xs(M,D)),hy("private key",M,Po,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=KH((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=KH(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=v$(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(Hi("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return c0e(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,R$),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,R$),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;hy("scalar",S,vp,O);let D=w.ZERO;if(S===vp)return D;if(this.is0()||S===Po)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>vp||P>vp;)N&Po&&(R=R.add(B)),P&Po&&(I=I.add(B)),B=B.double(),N>>=Po,P>>=Po;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;hy("scalar",S,Po,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===vp||P===Po||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===Po)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===Po?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return H6("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return H6("isCompressed",S),$6(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=a0e(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function tFe(e){let t=P$(e);return gy(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function d0e(e){let t=tFe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return xs(C,n)}function u(C){return l7(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=eFe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=c5;return H6("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=yp(H);if(!K_(k,Po,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&Po)===Po;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>Po;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>yp(C.slice(A,U));class v{constructor(A,U,H){hy("r",A,Po,n),hy("s",U,Po,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=Hi("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=xp.toSig(Hi("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(Hi("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+N$(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return a5(this.toDERHex())}toDERHex(){return xp.hexFromSig(this)}toCompactRawBytes(){return a5(this.toCompactHex())}toCompactHex(){let A=o;return N$(this.r,A)+N$(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=A$(t.n);return r0e(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=Hi("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=yp(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=my(s);function N(C){return hy("num < 2^"+s,C,vp,M),py(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=Hi("msgHash",C),u0e(U),j&&(C=Hi("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(Hi("extraEntropy",ye))}let pe=c5(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===vp)return;let ur=c(Et*c(me+At*te));if(ur===vp)return;let _r=(kt.x===At?0:2)|Number(kt.y&Po),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return mhe(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=Hi("msgHash",A),U=Hi("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(u0e(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||M6(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof xp.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}var O$,xp,vp,Po,Jcr,R$,X$e,f0e=b(()=>{l();l0e();u7();Z_();O$=class extends Error{constructor(t=""){super(t)}},xp={Err:O$,_tlv:{encode:(e,t)=>{let{Err:r}=xp;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=i5(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?i5(o.length/2|128):"";return i5(e)+s+o+t},decode(e,t){let{Err:r}=xp,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=xp;if(eb$(e,t,zpe(...r)),randomBytes:Vpe}}function p0e(e,t){let r=n=>d0e({...e,...rFe(n)});return{...r(t),create:r}}var h0e=b(()=>{l();Ghe();fy();f0e();});function sFe(e){let t=y0e,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=Ra(d,r,t)*d%t,p=Ra(f,r,t)*d%t,h=Ra(p,B$,t)*u%t,y=Ra(h,o,t)*h%t,w=Ra(y,s,t)*y%t,x=Ra(w,a,t)*w%t,v=Ra(x,c,t)*x%t,T=Ra(v,a,t)*w%t,E=Ra(T,r,t)*d%t,S=Ra(E,i,t)*y%t,_=Ra(S,n,t)*u%t,O=Ra(_,B$,t);if(!k$.eql(k$.sqr(O),e))throw new Error("Cannot find square root");return O}var y0e,m0e,nFe,oFe,B$,g0e,k$,Oa,U$=b(()=>{l();lhe();h0e();u7();y0e=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),m0e=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),nFe=BigInt(0),oFe=BigInt(1),B$=BigInt(2),g0e=(e,t)=>(e+t/B$)/t;k$=g5(y0e,void 0,void 0,{sqrt:sFe}),Oa=p0e({a:nFe,b:BigInt(7),Fp:k$,n:m0e,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=m0e,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-oFe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=g0e(s*e,t),c=g0e(-n*e,t),u=xs(e-a*r-c*o,t),d=xs(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},che)});var y7={};Te(y7,{InvalidRError:()=>f7,InvalidSError:()=>p7,InvalidSerializedSizeError:()=>d7,InvalidVError:()=>h7,InvalidYParityError:()=>xy,MissingPropertiesError:()=>q6,assert:()=>m7,extract:()=>iFe,from:()=>L$,fromBytes:()=>w0e,fromDerBytes:()=>aFe,fromDerHex:()=>b0e,fromHex:()=>D$,fromLegacy:()=>x0e,fromRpc:()=>v0e,fromTuple:()=>cFe,toBytes:()=>lFe,toDerBytes:()=>uFe,toDerHex:()=>dFe,toHex:()=>E0e,toLegacy:()=>fFe,toRpc:()=>pFe,toTuple:()=>hFe,vToYParity:()=>g7,validate:()=>mFe,yParityToV:()=>M$});function m7(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new q6({signature:e});if(typeof e.s>"u")throw new q6({signature:e});if(r&&typeof e.yParity>"u")throw new q6({signature:e});if(e.r<0n||e.r>p$)throw new f7({value:e.r});if(e.s<0n||e.s>p$)throw new p7({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new xy({value:e.yParity})}function w0e(e){return D$(li(e))}function D$(e){if(e.length!==130&&e.length!==132)throw new d7({signature:e});let t=BigInt(fl(e,0,32)),r=BigInt(fl(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return g7(o)}catch{throw new xy({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function iFe(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return L$(e)}function L$(e){let t=typeof e=="string"?D$(e):e instanceof Uint8Array?w0e(e):typeof e.r=="string"?v0e(e):e.v?x0e(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return m7(t),t}function aFe(e){return b0e(li(e))}function b0e(e){let{r:t,s:r}=Oa.Signature.fromDER(Tu(e).slice(2));return{r:t,s:r}}function x0e(e){return{r:e.r,s:e.s,yParity:g7(e.v)}}function v0e(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=g7(r)),typeof n!="number")throw new xy({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function cFe(e){let[t,r,n]=e;return L$({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function lFe(e){return h5(E0e(e))}function E0e(e){m7(e);let t=e.r,r=e.s;return wy(ui(t,{size:32}),ui(r,{size:32}),typeof e.yParity=="number"?ui(M$(e.yParity),{size:1}):"0x")}function uFe(e){return new Oa.Signature(e.r,e.s).toDERRawBytes()}function dFe(e){return`0x${new Oa.Signature(e.r,e.s).toDERHex()}`}function fFe(e){return{r:e.r,s:e.s,v:M$(e.yParity)}}function pFe(e){let{r:t,s:r,yParity:n}=e;return{r:ui(t,{size:32}),s:ui(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function hFe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":XH(ui(t)),r===0n?"0x":XH(ui(r))]}function mFe(e,t={}){try{return m7(e,t),!0}catch{return!1}}function g7(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new h7({value:e})}function M$(e){if(e===0)return 27;if(e===1)return 28;throw new xy({value:e})}var d7,q6,f7,p7,xy,h7,A0e=b(()=>{l();U$();Am();xm();bp();F6();a7();d7=class extends zt{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${$i(Tu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},q6=class extends zt{constructor({signature:t}){super(`Signature \`${Sm(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},f7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},p7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},xy=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},h7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}});var C0e=b(()=>{l()});var S0e=b(()=>{l()});var hlr,mlr,I0e=b(()=>{l();hlr=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),mlr={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var T0e=b(()=>{l()});var _0e=b(()=>{l()});var P0e,vFe,N0e,EFe,blr,R0e=b(()=>{l();P0e=6,vFe=32,N0e=4096,EFe=vFe*N0e,blr=EFe*P0e-1-1*N0e*P0e});var O0e=b(()=>{l()});var B0e=b(()=>{l()});var k0e=b(()=>{l()});var U0e=b(()=>{l()});var D0e=b(()=>{l()});var L0e=b(()=>{l()});var M0e=b(()=>{l()});var H0e=b(()=>{l()});var $0e=b(()=>{l()});var F0e=b(()=>{l();pZ()});var z0e=b(()=>{l()});var V0e=b(()=>{l()});var j0e,q0e=b(()=>{l();j0e=!1});var w7={};Te(w7,{createKeyPair:()=>LFe,getPublicKey:()=>W0e,getSharedSecret:()=>MFe,noble:()=>DFe,randomPrivateKey:()=>K0e,recoverAddress:()=>Z0e,recoverPublicKey:()=>G0e,sign:()=>HFe,verify:()=>$Fe});function LFe(e={}){let{as:t="Hex"}=e,r=K0e({as:t}),n=W0e({privateKey:r});return{privateKey:r,publicKey:n}}function W0e(e){let{privateKey:t}=e,r=Oa.ProjectivePoint.fromPrivateKey(Tu(t).slice(2));return c$(r)}function MFe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,i=Oa.ProjectivePoint.fromHex(m5(n).slice(2)).multiply(Oa.utils.normPrivateKeyToScalar(Tu(r).slice(2))).toRawBytes(!0);return t==="Hex"?li(i):i}function K0e(e={}){let{as:t="Hex"}=e,r=Oa.utils.randomPrivateKey();return t==="Hex"?li(r):r}function Z0e(e){return khe(G0e(e))}function G0e(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new Oa.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Tu(t).substring(2));return c$(a)}function HFe(e){let{extraEntropy:t=j0e,hash:r,payload:n,privateKey:o}=e,{r:s,s:i,recovery:a}=Oa.sign(V6(n),V6(o),{extraEntropy:typeof t=="boolean"?t:Tu(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function $Fe(e){let{address:t,hash:r,payload:n,publicKey:o,signature:s}=e;return t?Uhe(t,Z0e({payload:n,signature:s})):Oa.verify(s,V6(n),Ohe(o),...r?[{prehash:!0,lowS:!0}]:[])}var DFe,Y0e=b(()=>{l();U$();i7();Am();bp();q0e();o7();DFe=Oa});var J0e=b(()=>{l()});var Q0e=b(()=>{l()});var X0e=b(()=>{l()});var eme=b(()=>{l();kZ()});var tme=b(()=>{l()});var rme=b(()=>{l()});var Fi,H$,$$,F$,z$,V$,j$,q$,W$,K$,Z$,G$,Y$,nme=b(()=>{l();Fi=class extends Error{constructor(t){let{cause:r,code:n,message:o,data:s,stack:i}=t;super(o,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.BaseError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=r,this.code=n,this.data=s,this.stack=i??""}},H$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Missing or invalid parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidInputError"})}};Object.defineProperty(H$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});$$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not found."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceNotFoundError"})}};Object.defineProperty($$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});F$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not available."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceUnavailableError"})}};Object.defineProperty(F$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});z$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Transaction creation failed."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.TransactionRejectedError"})}};Object.defineProperty(z$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});V$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method is not implemented."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotSupportedError"})}};Object.defineProperty(V$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});j$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Rate limit exceeded."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.LimitExceededError"})}};Object.defineProperty(j$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});q$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"JSON-RPC version not supported."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.VersionNotSupportedError"})}};Object.defineProperty(q$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});W$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Input is not a valid JSON-RPC request."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidRequestError"})}};Object.defineProperty(W$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});K$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method does not exist."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotFoundError"})}};Object.defineProperty(K$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Z$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Invalid method parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidParamsError"})}};Object.defineProperty(Z$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});G$=class e extends Fi{constructor(t={}){super({cause:t.cause,code:e.code,data:t.data,message:t.message??"Internal JSON-RPC error.",stack:t.stack}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InternalError"})}};Object.defineProperty(G$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Y$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Failed to parse JSON-RPC response."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ParseError"})}};Object.defineProperty(Y$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700})});var fi,J$,Q$,X$,eF,tF,rF,nF,oF,sF,iF,aF,cF,lF,ome=b(()=>{l();MZ();fi=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderRpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}},J$=class extends fi{constructor({message:t="The user rejected the request."}={}){super(4001,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UserRejectedRequestError"})}};Object.defineProperty(J$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});Q$=class extends fi{constructor({message:t="The requested method and/or account has not been authorized by the user."}={}){super(4100,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnauthorizedError"})}};Object.defineProperty(Q$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});X$=class extends fi{constructor({message:t="The provider does not support the requested method."}={}){super(4200,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedMethodError"})}};Object.defineProperty(X$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});eF=class extends fi{constructor({message:t="The provider is disconnected from all chains."}={}){super(4900,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DisconnectedError"})}};Object.defineProperty(eF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});tF=class extends fi{constructor({message:t="The provider is not connected to the requested chain."}={}){super(4901,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.ChainDisconnectedError"})}};Object.defineProperty(tF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});rF=class extends fi{constructor({message:t="An error occurred when attempting to switch chain."}={}){super(4902,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.SwitchChainError"})}};Object.defineProperty(rF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});nF=class extends fi{constructor({message:t="This Wallet does not support a capability that was not marked as optional."}={}){super(5700,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedNonOptionalCapabilityError"})}};Object.defineProperty(nF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});oF=class extends fi{constructor({message:t="This Wallet does not support the requested chain ID."}={}){super(5710,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedChainIdError"})}};Object.defineProperty(oF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});sF=class extends fi{constructor({message:t="There is already a bundle submitted with this ID."}={}){super(5720,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DuplicateIdError"})}};Object.defineProperty(sF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});iF=class extends fi{constructor({message:t="This bundle id is unknown / has not been submitted."}={}){super(5730,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnknownBundleIdError"})}};Object.defineProperty(iF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});aF=class extends fi{constructor({message:t="The call bundle is too large for the Wallet to process."}={}){super(5740,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.BundleTooLargeError"})}};Object.defineProperty(aF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});cF=class extends fi{constructor({message:t="The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."}={}){super(5750,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicReadyWalletRejectedUpgradeError"})}};Object.defineProperty(cF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});lF=class extends fi{constructor({message:t="The wallet does not support atomic execution but the request requires it."}={}){super(5760,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicityNotSupportedError"})}};Object.defineProperty(lF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760})});var sme=b(()=>{l()});var ime=b(()=>{l()});var ame=b(()=>{l()});var cme=b(()=>{l()});var lme=b(()=>{l()});var ume=b(()=>{l()});var dme=b(()=>{l()});var fme=b(()=>{l()});var pme=b(()=>{l()});var hme=b(()=>{l()});var mme=b(()=>{l()});var gme=b(()=>{l()});var yme=b(()=>{l()});var wme=b(()=>{l()});var bme=b(()=>{l()});var xme=b(()=>{l()});var pur,vme=b(()=>{l();pur=Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233])});var Eme=b(()=>{l()});var Ame=b(()=>{l()});var Cme=b(()=>{l();Bpe();Fhe();zhe();Vhe();jhe();Dhe();$he();qhe();Whe();i7();Khe();C0e();S0e();I0e();T0e();R0e();k0e();U0e();D0e();L0e();M0e();Am();n$();H0e();$0e();F0e();xm();z0e();V0e();r$();J0e();bp();F6();Q0e();_0e();X0e();eme();tme();rme();ome();o7();Zhe();sme();nme();ime();ame();Y0e();A0e();cme();a7();lme();O0e();dme();fme();pme();hme();mme();gme();yme();wme();bme();xme();ume();vme();Eme();B0e();Ame()});function Sme(e){let t=e.length,r=0,n=0;for(;n=55296&&o<=56319&&n>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}function yze(e,t,r){mze.encodeInto(e,t.subarray(r))}function Ime(e,t,r){e.length>gze?yze(e,t,r):hze(e,t,r)}function uF(e,t,r){let n=t,o=n+r,s=[],i="";for(;n65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=wze&&(i+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(i+=String.fromCharCode(...s)),i}function vze(e,t,r){let n=e.subarray(t,t+r);return bze.decode(n)}function Tme(e,t,r){return r>xze?vze(e,t,r):uF(e,t,r)}var mze,gze,wze,bze,xze,b7=b(()=>{l();mze=new TextEncoder,gze=50;wze=4096;bze=new TextDecoder,xze=200});var vy,_me=b(()=>{l();vy=class{constructor(t,r){this.type=t,this.data=r}}});var zi,dF=b(()=>{l();zi=class e extends Error{constructor(t){super(t);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}});function Pme(e,t,r){let n=r/4294967296,o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function x7(e,t,r){let n=Math.floor(r/4294967296),o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function v7(e,t){let r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function Nme(e,t){let r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}var E7=b(()=>{l()});function Sze({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=Cze)if(t===0&&e<=Aze){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|r&3),s.setUint32(4,n),o}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),x7(n,4,e),r}}function Ize(e){let t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,o=Math.floor(n/1e9);return{sec:r+o,nsec:n-o*1e9}}function Tze(e){if(e instanceof Date){let t=Ize(e);return Sze(t)}else return null}function _ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let r=t.getUint32(0),n=t.getUint32(4),o=(r&3)*4294967296+n,s=r>>>2;return{sec:o,nsec:s}}case 12:{let r=v7(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new zi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Pze(e){let t=_ze(e);return new Date(t.sec*1e3+t.nsec/1e6)}var Eze,Aze,Cze,Rme,Ome=b(()=>{l();dF();E7();Eze=-1,Aze=4294967296-1,Cze=17179869184-1;Rme={type:Eze,encode:Tze,decode:Pze}});var Im,fF=b(()=>{l();_me();Ome();Im=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Rme)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{let o=-1-t;this.builtInEncoders[o]=r,this.builtInDecoders[o]=n}}tryToEncode(t,r){for(let n=0;n{l()});var Rze,Oze,A7,Bme=b(()=>{l();b7();fF();E7();pF();Rze=100,Oze=2048,A7=class e{constructor(t){this.entered=!1,this.extensionCodec=t?.extensionCodec??Im.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??Rze,this.initialBufferSize=t?.initialBufferSize??Oze,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){let r=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let n=Sme(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Ime(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){let n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let n=y5(t);this.writeU8a(n)}encodeArray(t,r){let n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let o of t)this.doEncode(o,r+1)}countWithoutUndefined(t,r){let n=0;for(let o of r)t[o]!==void 0&&n++;return n}encodeMap(t,r){let n=Object.keys(t);this.sortKeys&&n.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of n){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){let n=t.data(this.pos+6),o=n.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(n);return}let r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),Pme(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),x7(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}});function hF(e,t){return new A7(t).encodeSharedRef(e)}var kme=b(()=>{l();Bme()});function C7(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}var Ume=b(()=>{l()});var Bze,kze,S7,Dme=b(()=>{l();b7();Bze=16,kze=16,S7=class{constructor(t=Bze,r=kze){this.hit=0,this.miss=0,this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n0&&t<=this.maxKeyLength}find(t,r,n){let o=this.caches[n-1];e:for(let s of o){let i=s.bytes;for(let a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)}decode(t,r,n){let o=this.find(t,r,n);if(o!=null)return this.hit++,o;this.miss++;let s=uF(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,s),s}}});var mF,x5,Mme,Uze,gF,b5,yF,Dze,Lme,Lze,I7,Hme=b(()=>{l();Ume();fF();E7();b7();pF();Dme();dF();mF="array",x5="map_key",Mme="map_value",Uze=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new zi("The type of key must be string or number but "+typeof e)},gF=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let r=this.getUninitializedStateFromPool();r.type=mF,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){let r=this.getUninitializedStateFromPool();r.type=x5,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===mF){let n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===x5||t.type===Mme){let n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},b5=-1,yF=new DataView(new ArrayBuffer(0)),Dze=new Uint8Array(yF.buffer);try{yF.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}Lme=new RangeError("Insufficient data"),Lze=new S7,I7=class e{constructor(t){this.totalPos=0,this.pos=0,this.view=yF,this.bytes=Dze,this.headByte=b5,this.stack=new gF,this.entered=!1,this.extensionCodec=t?.extensionCodec??Im.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??4294967295,this.maxBinLength=t?.maxBinLength??4294967295,this.maxArrayLength=t?.maxArrayLength??4294967295,this.maxMapLength=t?.maxMapLength??4294967295,this.maxExtLength=t?.maxExtLength??4294967295,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:Lze,this.mapKeyConverter=t?.mapKeyConverter??Uze}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=b5,this.stack.reset()}setBuffer(t){let r=y5(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===b5&&!this.hasRemaining(1))this.setBuffer(t);else{let r=this.bytes.subarray(this.pos),n=y5(t),o=new Uint8Array(r.length+n.length);o.set(r),o.set(n,r.length),this.setBuffer(o)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(let a of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:o,pos:s,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${C7(o)} at ${i} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,o=-1;for await(let s of t){if(r&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){let o=t-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t<160){let o=t-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else{let o=t-160;r=this.decodeString(o,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){let o=this.lookU8();r=this.decodeString(o,1)}else if(t===218){let o=this.lookU16();r=this.decodeString(o,2)}else if(t===219){let o=this.lookU32();r=this.decodeString(o,4)}else if(t===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===196){let o=this.lookU8();r=this.decodeBinary(o,1)}else if(t===197){let o=this.lookU16();r=this.decodeBinary(o,2)}else if(t===198){let o=this.lookU32();r=this.decodeBinary(o,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){let o=this.lookU8();r=this.decodeExtension(o,1)}else if(t===200){let o=this.lookU16();r=this.decodeExtension(o,2)}else if(t===201){let o=this.lookU32();r=this.decodeExtension(o,4)}else throw new zi(`Unrecognized type byte: ${C7(t)}`);this.complete();let n=this.stack;for(;n.length>0;){let o=n.top();if(o.type===mF)if(o.array[o.position]=r,o.position++,o.position===o.size)r=o.array,n.release(o);else continue e;else if(o.type===x5){if(r==="__proto__")throw new zi("The key __proto__ is not allowed");o.key=this.mapKeyConverter(r),o.type=Mme;continue e}else if(o.map[o.key]=r,o.readCount++,o.readCount===o.size)r=o.map,n.release(o);else{o.key=null,o.type=x5;continue e}}return r}}readHeadByte(){return this.headByte===b5&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=b5}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new zi(`Unrecognized array type byte: ${C7(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new zi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new zi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new zi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===x5:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new zi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw Lme;let n=this.pos+r,o=this.bytes.subarray(n,n+t);return this.pos+=r+t,o}decodeExtension(t,r){if(t>this.maxExtLength)throw new zi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+r),o=this.decodeBinary(t,r+1);return this.extensionCodec.decode(o,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){let t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){let t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){let t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){let t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){let t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){let t=Nme(this.view,this.pos);return this.pos+=8,t}readI64(){let t=v7(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){let t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){let t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){let t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){let t=this.view.getFloat64(this.pos);return this.pos+=8,t}}});function wF(e,t){return new I7(t).decode(e)}var $me=b(()=>{l();Hme()});var Fme=b(()=>{l();kme();$me()});function bl(e){let[t,r]=e.split(Mze);return{namespace:t,reference:r}}function C1e(e,t){return e.includes(":")?[e]:t.chains||[]}function P5(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function _p(){return!(0,yl.getDocument)()&&!!(0,yl.getNavigator)()&&navigator.product===qze}function S1e(){return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function I1e(){return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Ty(){return!P5()&&!!(0,yl.getNavigator)()&&!!(0,yl.getDocument)()}function N5(){return _p()?ji.reactNative:P5()?ji.node:Ty()?ji.browser:ji.unknown}function JF(){var e;try{return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(e=global.Application)==null?void 0:e.applicationId:void 0}catch{return}}function Kze(e,t){let r=new URLSearchParams(e);return Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!=null&&r.set(n,String(o))}),r.toString()}function T1e(e){var t,r;let n=QF();try{return e!=null&&e.url&&n.url&&new URL(e.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),e.url=n.url),(t=e?.icons)!=null&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(o=>o!=="")),jze(Vme(Vme({},n),e),{url:e?.url||n.url,name:e?.name||n.name,description:e?.description||n.description,icons:(r=e?.icons)!=null&&r.length&&e.icons.length>0?e.icons:n.icons})}catch(o){return console.warn("Error populating app metadata",o),e||n}}function QF(){return(0,E1e.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function Zze(){if(N5()===ji.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let e=iA();if(e===null)return"unknown";let t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function Gze(){var e;let t=N5();return t===ji.browser?[t,((e=(0,yl.getLocation)())==null?void 0:e.host)||"unknown"].join(":"):t}function XF(e,t,r){let n=Zze(),o=Gze();return[[e,t].join("-"),[Wze,r].join("-"),n,o].join("/")}function _1e({protocol:e,version:t,relayUrl:r,sdkVersion:n,auth:o,projectId:s,useOnCloseEvent:i,bundleId:a,packageName:c}){let u=r.split("?"),d=XF(e,t,n),f={auth:o,ua:d,projectId:s,useOnCloseEvent:i||void 0,packageName:c||void 0,bundleId:a||void 0},p=Kze(u[1]||"",f);return u[0]+"?"+p}function Ey(e,t){return e.filter(r=>t.includes(r)).length===e.length}function $7(e){return Object.fromEntries(e.entries())}function F7(e){return new Map(Object.entries(e))}function Pp(e=Ip.FIVE_MINUTES,t){let r=(0,Ip.toMiliseconds)(e||Ip.FIVE_MINUTES),n,o,s,i;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),i=Promise.resolve(a))},reject:a=>{s&&o&&(clearTimeout(s),o(a))},done:()=>new Promise((a,c)=>{if(i)return a(i);s=setTimeout(()=>{let u=new Error(t);i=Promise.reject(u),c(u)},r),n=a,o=c})}}function xl(e,t,r){return new Promise(async(n,o)=>{let s=setTimeout(()=>o(new Error(r)),t);try{let i=await e;n(i)}catch(i){o(i)}clearTimeout(s)})}function P1e(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function N1e(e){return P1e("topic",e)}function R1e(e){return P1e("id",e)}function z7(e){let[t,r]=e.split(":"),n={id:void 0,topic:void 0};if(t==="topic"&&typeof r=="string")n.topic=r;else if(t==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);return n}function pn(e,t){return(0,Ip.fromMiliseconds)((t||Date.now())+(0,Ip.toMiliseconds)(e))}function ka(e){return Date.now()>=(0,Ip.toMiliseconds)(e)}function cr(e,t){return`${e}${t?`:${t}`:""}`}function ml(e=[],t=[]){return[...new Set([...e,...t])]}async function O1e({id:e,topic:t,wcDeepLink:r}){var n;try{if(!r)return;let o=typeof r=="string"?JSON.parse(r):r,s=o?.href;if(typeof s!="string")return;let i=Yze(s,e,t),a=N5();if(a===ji.browser){if(!((n=(0,yl.getDocument)())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Jze(i)}else a===ji.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(i)}catch(o){console.error(o)}}function Yze(e,t,r){let n=`requestId=${t}&sessionTopic=${r}`;e.endsWith("/")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith("https://t.me")){let s=e.includes("?")?"&startapp=":"?startapp=";o=`${o}${s}${eVe(n,!0)}`}else o=`${o}/wc?${n}`;return o}function Jze(e){let t="_self";Xze()?t="_top":(Qze()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function B1e(e,t){let r="";try{if(Ty()&&(r=localStorage.getItem(t),r))return r;r=await e.getItem(t)}catch(n){console.error(n)}return r}function ez(e,t){if(!e.includes(t))return null;let r=e.split(/([&,?,=])/),n=r.indexOf(t);return r[n+2]}function tz(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function R5(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function Qze(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Xze(){try{return window.self!==window.top}catch{return!1}}function eVe(e,t=!1){let r=Buffer.from(e).toString("base64");return t?r.replace(/[=]/g,""):r}function k1e(e){return Buffer.from(e,"base64").toString("utf-8")}function U1e(e){return new Promise(t=>setTimeout(t,e))}function D1e(e,t=!1){return t?{h:Number(e&T7),l:Number(e>>qme&T7)}:{h:Number(e>>qme&T7)|0,l:Number(e&T7)|0}}function L1e(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}function V7(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Tp(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wl(e,...t){if(!V7(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function j7(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Tp(e.outputLen),Tp(e.blockLen)}function Mm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oz(e,t){wl(e);let r=t.outputLen;if(e.length>>t}function H1e(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function dVe(e){for(let t=0;t=Ep._0&&e<=Ep._9)return e-Ep._0;if(e>=Ep.A&&e<=Ep.F)return e-(Ep.A-10);if(e>=Ep.a&&e<=Ep.f)return e-(Ep.a-10)}function B7(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if($1e)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oe().update(gl(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function pVe(e){let t=(n,o)=>e(o).update(gl(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function _y(e=32){if(W6&&typeof W6.getRandomValues=="function")return W6.getRandomValues(new Uint8Array(e));if(W6&&typeof W6.randomBytes=="function")return Uint8Array.from(W6.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function vVe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=Gme(u,d,1)^r[a],p=Yme(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=V1e[i],c=Gme(o,s,a),u=Yme(o,s,a),d=z1e[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=bVe[n],e[1]^=xVe[n]}bc(r)}function CVe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function SVe(e,t,r){return e&t^~e&r}function IVe(e,t,r){return e&t^e&r^t&r}function Rm(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=ke[2*e],u=ke[2*e+1],d=ke[2*t],f=ke[2*t+1],p=ke[2*r],h=ke[2*r+1],y=ke[2*n],w=ke[2*n+1],x=rz(c,d,i);u=nz(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:tVe(w,y),Dl:rVe(w)},{h,l:p}=hl(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:Bm(f,d,24),Bl:km(f,d,24)},ke[2*e]=c,ke[2*e+1]=u,ke[2*t]=d,ke[2*t+1]=f,ke[2*r]=p,ke[2*r+1]=h,ke[2*n]=y,ke[2*n+1]=w}function Om(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=ke[2*e],u=ke[2*e+1],d=ke[2*t],f=ke[2*t+1],p=ke[2*r],h=ke[2*r+1],y=ke[2*n],w=ke[2*n+1],x=rz(c,d,i);u=nz(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:Bm(w,y,16),Dl:km(w,y,16)},{h,l:p}=hl(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:A5(f,d,63),Bl:C5(f,d,63)},ke[2*e]=c,ke[2*e+1]=u,ke[2*t]=d,ke[2*t+1]=f,ke[2*r]=p,ke[2*r+1]=h,ke[2*n]=y,ke[2*n+1]=w}function kVe(e,t={},r,n,o){if(Tp(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");let{key:s,salt:i,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(i!==void 0&&i.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==o)throw new Error("personalization must be undefined or "+o)}function K1e(e){let t=`Ethereum Signed Message: +${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toString("hex")}async function LVe(e,t,r,n,o,s){switch(r.t){case"eip191":return await MVe(e,t,r.s);case"eip1271":return await HVe(e,t,r.s,n,o,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function MVe(e,t,r){let n=y7.fromHex(r);return w7.recoverAddress({payload:K1e(t),signature:n}).toLowerCase()===e.toLowerCase()}async function HVe(e,t,r,n,o,s){let i=bl(n);if(!i.namespace||!i.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{let a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),d=(u.length/2).toString(16).padStart(64,"0"),f=(t.startsWith("0x")?t:K1e(t)).substring(2),p=a+f+c+d+u,h=await fetch(`${s||DVe}/?chainId=${n}&projectId=${o}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:$Ve(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:p},"latest"]})}),{result:y}=await h.json();return y?y.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function $Ve(){return Date.now()+Math.floor(Math.random()*1e3)}function Z1e(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;is.charCodeAt(0)),n=new Uint8Array(r.length+t.length);n.set(r),n.set(t,r.length);let o=UVe(n,{dkLen:32});return wm.encode(o)}function sz(e){let t=new Uint8Array(q7(FVe(e)));return wm.encode(t)}function FVe(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(typeof e=="object"&&e!=null&&e.data)return new Uint8Array(Object.values(e.data));if(typeof e=="object"&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function iz(e){let t=Buffer.from(e,"base64"),r=wF(t).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");let n=hF(r),o=Buffer.from("TX"),s=Buffer.concat([o,Buffer.from(n)]),i=OVe(s);return KA.encode(i).replace(/=+$/,"")}function xF(e){let t=[],r=BigInt(e);for(;r>=BigInt(128);)t.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return t.push(Number(r)),Buffer.from(t)}function Y1e(e){let t=Buffer.from(e.signed.bodyBytes,"base64"),r=Buffer.from(e.signed.authInfoBytes,"base64"),n=Buffer.from(e.signature.signature,"base64"),o=[];o.push(Buffer.from([10])),o.push(xF(t.length)),o.push(t),o.push(Buffer.from([18])),o.push(xF(r.length)),o.push(r),o.push(Buffer.from([26])),o.push(xF(n.length)),o.push(n);let s=Buffer.concat(o),i=q7(s);return Buffer.from(i).toString("hex").toUpperCase()}function J1e(e){var t,r;let n=[];try{if(typeof e=="string")return n.push(e),n;if(typeof e!="object")return n;e!=null&&e.id&&n.push(e.id);let o=(r=(t=e?.capabilities)==null?void 0:t.caip345)==null?void 0:r.transactionHashes;o&&n.push(...o)}catch(o){console.warn("getWalletSendCallsHashes failed: ",o)}return n}async function az(e){let{cacao:t,projectId:r}=e,{s:n,p:o}=t,s=cz(o,o.iss),i=B5(o.iss);return await LVe(i,s,n,K7(o.iss),r)}function XVe(e){return Buffer.from(JSON.stringify(e)).toString("base64")}function eje(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}function Iy(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");let t=Object.keys(e.att);if(!(t!=null&&t.length))throw new Error("No resources found in `att` property");t.forEach(r=>{let n=e.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(o=>{let s=n[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!="object")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function tje(e,t,r,n={}){return r?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:rje(t,r,n)}}}function rje(e,t,r={}){t=t?.sort((o,s)=>o.localeCompare(s));let n=t.map(o=>({[`${e}/${o}`]:[r]}));return Object.assign({},...n)}function X1e(e){return Iy(e),`urn:recap:${XVe(e).replace(/=/g,"")}`}function _5(e){let t=eje(e.replace("urn:recap:",""));return Iy(t),t}function ege(e,t,r){let n=tje(e,t,r);return X1e(n)}function nje(e){return e&&e.includes("urn:recap:")}function tge(e,t){let r=_5(e),n=_5(t),o=oje(r,n);return X1e(o)}function oje(e,t){Iy(e),Iy(t);let r=Object.keys(e.att).concat(Object.keys(t.att)).sort((o,s)=>o.localeCompare(s)),n={att:{}};return r.forEach(o=>{var s,i;Object.keys(((s=e.att)==null?void 0:s[o])||{}).concat(Object.keys(((i=t.att)==null?void 0:i[o])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;n.att[o]=ZVe(KVe({},n.att[o]),{[a]:((c=e.att[o])==null?void 0:c[a])||((u=t.att[o])==null?void 0:u[a])})})}),n}function sje(e="",t){Iy(t);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(r))return e;let n=[],o=0;Object.keys(t.att).forEach(a=>{let c=Object.keys(t.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,p)=>f.action.localeCompare(p.action));let u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});let d=Object.keys(u).map(f=>(o++,`(${o}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});let s=n.join(" "),i=`${r}${s}`;return`${e?e+" ":""}${i}`}function lz(e){var t;let r=_5(e);Iy(r);let n=(t=r.att)==null?void 0:t.eip155;return n?Object.keys(n).map(o=>o.split("/")[1]):[]}function uz(e){let t=_5(e);Iy(t);let r=[];return Object.values(t.att).forEach(n=>{Object.values(n).forEach(o=>{var s;(s=o?.[0])!=null&&s.chains&&r.push(o[0].chains)})}),[...new Set(r.flat())]}function k5(e){if(!e)return;let t=e?.[e.length-1];return nje(t)?t:void 0}function rge(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function MF(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function vF(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Vi(e,...t){if(!rge(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Xme(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ije(e,t){Vi(e);let r=t.outputLen;if(e.length>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function pje(e,t,r){MF(r);let n=new Uint8Array(16),o=aje(n);return t1e(o,0,BigInt(t),r),t1e(o,8,BigInt(e),r),n}function hje(e){return e.byteOffset%4===0}function $F(e){return Uint8Array.from(e)}function tr(e,t){return e<>>32-t}function FF(e){return e.byteOffset%4===0}function xje(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(_7),d=Lm(u),f=FF(o)&&FF(s),p=f?Lm(o):r1e,h=f?Lm(s):r1e;for(let y=0;y=oge)throw new Error("arx: counter overflow");let w=Math.min(_7,c-y);if(f&&w===_7){let x=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,T;v{Vi(a),Vi(c),Vi(u);let p=u.length;if(d===void 0&&(d=new Uint8Array(p)),Vi(d),vF(f),f<0||f>=oge)throw new Error("arx: counter overflow");if(d.lengthe(o).update(HF(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Cje(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],p=t[2],h=t[3],y=t[4],w=t[5],x=t[6],v=t[7],T=o,E=r[0],S=r[1],_=r[2],O=i,D=a,M=c,N=u,L=d,P=f,R=p,I=h,B=y,C=w,A=x,U=v,H=T,k=E,F=S,j=_;for(let ae=0;ae255*o)throw new Error("Length should be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0&&(r=s1e);let i=new Uint8Array(s*o),a=Z7.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;ddz;e>>=VF,t+=1);return t}function Bje(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),o=p=>Uint8Array.of(p),s=n(e),i=n(e),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...p)=>r(i,s,...p),d=(p=n(0))=>{i=u(o(0),p),s=u(),p.length!==0&&(i=u(o(1),p),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,h=[];for(;p{c(),d(p);let y;for(;!(y=h(f()));)d();return c(),y}}function J7(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function i1e(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}function Ba(e,t){let r=e%t;return r>=qi?r:t+r}function pl(e,t,r){let n=e;for(;t-- >qi;)n*=n,n%=r;return n}function a1e(e,t){if(e===qi)throw new Error("invert: expected non-zero number");if(t<=qi)throw new Error("invert: expected positive modulus, got "+t);let r=Ba(e,t),n=t,o=qi,s=pi;for(;r!==qi;){let i=n/r,a=n%r,c=o-s*i;n=r,r=a,o=s,s=c}if(n!==pi)throw new Error("invert: does not exist");return Ba(o,t)}function hz(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function pge(e,t){let r=(e.ORDER+pi)/lge,n=e.pow(t,r);return hz(e,n,t),n}function Dje(e,t){let r=(e.ORDER-uge)/dge,n=e.mul(t,Cy),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Cy),o),a=e.mul(s,e.sub(i,e.ONE));return hz(e,a,t),a}function Lje(e){let t=Fm(e),r=hge(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+kje)/fge;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),h=a.eql(a.sqr(d),c),y=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(p,f,y);let w=a.eql(a.sqr(d),c),x=a.cmov(u,d,w);return hz(a,x,c),x}}function hge(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return pge;let s=o.pow(n,t),i=(t+pi)/Cy;return function(a,c){if(a.is0(c))return c;if(c1e(a,c)!==1)throw new Error("Cannot find square root");let u=r,d=a.mul(a.ONE,s),f=a.pow(c,t),p=a.pow(c,i);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let h=1,y=a.sqr(f);for(;!a.eql(y,a.ONE);)if(h++,y=a.sqr(y),h===u)throw new Error("Cannot find square root");let w=pi<(n[o]="function",n),t);return J7(e,r),e}function Fje(e,t,r){if(rqi;)r&pi&&(n=e.mul(n,o)),o=e.sqr(o),r>>=pi;return n}function mge(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function c1e(e,t){let r=(e.ORDER-pi)/Cy,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function gge(e,t){t!==void 0&&Tp(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Fm(e,t,r=!1,n={}){if(e<=qi)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(r=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=gge(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:U5(c),ZERO:qi,ONE:pi,allowedLengths:a,create:p=>Ba(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return qi<=p&&pp===qi,isValidNot0:p=>!f.is0(p)&&f.isValid(p),isOdd:p=>(p&pi)===pi,neg:p=>Ba(-p,e),eql:(p,h)=>p===h,sqr:p=>Ba(p*p,e),add:(p,h)=>Ba(p+h,e),sub:(p,h)=>Ba(p-h,e),mul:(p,h)=>Ba(p*h,e),pow:(p,h)=>Fje(f,p,h),div:(p,h)=>Ba(p*a1e(h,e),e),sqrN:p=>p*p,addN:(p,h)=>p+h,subN:(p,h)=>p-h,mulN:(p,h)=>p*h,inv:p=>a1e(p,e),sqrt:s||(p=>(d||(d=Mje(e)),d(f,p))),toBytes:p=>r?pz(p,u):fz(p,u),fromBytes:(p,h=!0)=>{if(a){if(!a.includes(p.length)||p.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let w=new Uint8Array(u);w.set(p,r?0:w.length-p.length),p=w}if(p.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+p.length);let y=r?L7(p):Y7(p);if(i&&(y=Ba(y,e)),!h&&!f.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:p=>mge(f,p),cmov:(p,h,y)=>y?h:p});return Object.freeze(f)}function yge(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function wge(e){let t=yge(e);return t+Math.ceil(t/2)}function zje(e,t,r=!1){let n=e.length,o=yge(t),s=wge(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?L7(e):Y7(e),a=Ba(i,t-pi)+pi;return r?pz(a,o):fz(a,o)}function M7(e,t){let r=t.negate();return e?r:t}function CF(e,t){let r=mge(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function bge(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function SF(e,t){bge(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=U5(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function l1e(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=Sy);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function Vje(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function jje(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function TF(e){return xge.get(e)||1}function u1e(e){if(e!==X6)throw new Error("invalid wNAF")}function qje(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>X6||n>X6;)r&Sy&&(s=s.add(o)),n&Sy&&(i=i.add(o)),o=o.double(),r>>=Sy,n>>=Sy;return{p1:s,p2:i}}function Wje(e,t,r,n){Vje(r,e),jje(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=age(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=U5(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;wX6))throw new Error(`CURVE.${a} must be positive bigint`)}let o=d1e(t.p,r.Fp,n),s=d1e(t.n,r.Fn,n),i=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let a of i)if(!o.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Zje(e){return J7(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Gje(e){let t=Zje(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||_y,u=a?255:448,d=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),h=a?N7**BigInt(254):N7**BigInt(447),y=a?BigInt(8)*N7**BigInt(251)-K6:BigInt(4)*N7**BigInt(445)-K6,w=h+y+K6,x=R=>Ba(R,r),v=T(f);function T(R){return pz(x(R),d)}function E(R){let I=Ss("u coordinate",R,d);return a&&(I[31]&=127),x(L7(I))}function S(R){return L7(o(Ss("scalar",R,d)))}function _(R,I){let B=M(E(I),S(R));if(B===E5)throw new Error("invalid private or public key received");return T(B)}function O(R){return _(R,v)}function D(R,I,B){let C=x(R*(I-B));return I=x(I-C),B=x(B+C),{x_2:I,x_3:B}}function M(R,I){jF("u",R,E5,r),jF("scalar",I,h,w);let B=I,C=R,A=K6,U=E5,H=R,k=K6,F=E5;for(let W=BigInt(u-1);W>=E5;W--){let ae=B>>W&K6;F^=ae,{x_2:A,x_3:H}=D(F,A,H),{x_2:U,x_3:k}=D(F,U,k),F=ae;let te=A+U,X=x(te*te),pe=A-U,me=x(pe*pe),Ne=X-me,ye=H+k,Re=H-k,Et=x(Re*te),kt=x(ye*pe),At=Et+kt,ur=Et-kt;H=x(At*At),k=x(C*x(ur*ur)),A=x(X*me),U=x(Ne*(X+x(p*Ne)))}({x_2:A,x_3:H}=D(F,A,H)),{x_2:U,x_3:k}=D(F,U,k);let j=s(U);return x(A*j)}let N={secretKey:d,publicKey:d,seed:d},L=(R=c(d))=>(wl(R,N.seed),R);function P(R){let I=L(R);return{secretKey:I,publicKey:O(I)}}return{keygen:P,getSharedSecret:(R,I)=>_(R,I),getPublicKey:R=>O(R),scalarMult:_,scalarMultBase:O,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:v.slice(),lengths:N}}function tqe(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=vge,i=e*e%s*e%s,a=pl(i,f1e,s)*i%s,c=pl(a,Yje,s)*e%s,u=pl(c,Qje,s)*c%s,d=pl(u,t,s)*u%s,f=pl(d,r,s)*d%s,p=pl(f,n,s)*f%s,h=pl(p,o,s)*p%s,y=pl(h,o,s)*p%s,w=pl(y,t,s)*u%s;return{pow_p_5_8:pl(w,f1e,s)*e%s,b2:i}}function rqe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function oqe(e,t,r){let[[n,o],[s,i]]=t,a=p1e(i*e,r),c=p1e(-o*e,r),u=e-a*n-c*s,d=-a*o-c*i,f=u=h||d=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function KF(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function _F(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return D7(r.lowS,"lowS"),D7(r.prehash,"prehash"),r.format!==void 0&&KF(r.format),r}function Z6(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=Ss("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function iqe(e,t={}){let r=Kje("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;J7(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Cge(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(R,I,B){let{x:C,y:A}=I.toAffine(),U=n.toBytes(C);if(D7(B,"isCompressed"),B){d();let H=!n.isOdd(A);return Dm(Age(H),U)}else return Dm(Uint8Array.of(4),U,n.toBytes(A))}function p(R){Ay(R,void 0,"Point");let{publicKey:I,publicKeyUncompressed:B}=u,C=R.length,A=R[0],U=R.subarray(1);if(C===I&&(A===2||A===3)){let H=n.fromBytes(U);if(!n.isValid(H))throw new Error("bad point: is not on curve, wrong x");let k=w(H),F;try{F=n.sqrt(k)}catch(W){let ae=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}d();let j=n.isOdd(F);return(A&1)===1!==j&&(F=n.neg(F)),{x:H,y:F}}else if(C===B&&A===4){let H=n.BYTES,k=n.fromBytes(U.subarray(0,H)),F=n.fromBytes(U.subarray(H,H*2));if(!x(k,F))throw new Error("bad point: is not on curve");return{x:k,y:F}}else throw new Error(`bad point: got length ${C}, expected compressed=${I} or uncompressed=${B}`)}let h=t.toBytes||f,y=t.fromBytes||p;function w(R){let I=n.sqr(R),B=n.mul(I,R);return n.add(n.add(B,n.mul(R,s.a)),s.b)}function x(R,I){let B=n.sqr(I),C=w(R);return n.eql(B,C)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,R7),sqe),T=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,T)))throw new Error("bad curve params: a or b");function E(R,I,B=!1){if(!n.isValid(I)||B&&n.is0(I))throw new Error(`bad point coordinate ${R}`);return I}function S(R){if(!(R instanceof N))throw new Error("ProjectivePoint expected")}function _(R){if(!c||!c.basises)throw new Error("no endo");return oqe(R,c.basises,o.ORDER)}let O=i1e((R,I)=>{let{X:B,Y:C,Z:A}=R;if(n.eql(A,n.ONE))return{x:B,y:C};let U=R.is0();I==null&&(I=U?n.ONE:n.inv(A));let H=n.mul(B,I),k=n.mul(C,I),F=n.mul(A,I);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:k}}),D=i1e(R=>{if(R.is0()){if(t.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:B}=R.toAffine();if(!n.isValid(I)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!x(I,B))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,I,B,C,A){return B=new N(n.mul(B.X,R),B.Y,B.Z),I=M7(C,I),B=M7(A,B),I.add(B)}class N{constructor(I,B,C){this.X=E("x",I),this.Y=E("y",B,!0),this.Z=E("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){let{x:B,y:C}=I||{};if(!I||!n.isValid(B)||!n.isValid(C))throw new Error("invalid affine point");if(I instanceof N)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(C)?N.ZERO:new N(B,C,n.ONE)}static fromBytes(I){let B=N.fromAffine(y(Ay(I,void 0,"point")));return B.assertValidity(),B}static fromHex(I){return N.fromBytes(Ss("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,B=!0){return P.createCache(this,I),B||this.multiply(R7),this}assertValidity(){D(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.eql(n.mul(B,k),n.mul(U,A)),j=n.eql(n.mul(C,k),n.mul(H,A));return F&&j}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:B}=s,C=n.mul(B,R7),{X:A,Y:U,Z:H}=this,k=n.ZERO,F=n.ZERO,j=n.ZERO,W=n.mul(A,A),ae=n.mul(U,U),te=n.mul(H,H),X=n.mul(A,U);return X=n.add(X,X),j=n.mul(A,H),j=n.add(j,j),k=n.mul(I,j),F=n.mul(C,te),F=n.add(k,F),k=n.sub(ae,F),F=n.add(ae,F),F=n.mul(k,F),k=n.mul(X,k),j=n.mul(C,j),te=n.mul(I,te),X=n.sub(W,te),X=n.mul(I,X),X=n.add(X,j),j=n.add(W,W),W=n.add(j,W),W=n.add(W,te),W=n.mul(W,X),F=n.add(F,W),te=n.mul(U,H),te=n.add(te,te),W=n.mul(te,X),k=n.sub(k,W),j=n.mul(te,ae),j=n.add(j,j),j=n.add(j,j),new N(k,F,j)}add(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.ZERO,j=n.ZERO,W=n.ZERO,ae=s.a,te=n.mul(s.b,R7),X=n.mul(B,U),pe=n.mul(C,H),me=n.mul(A,k),Ne=n.add(B,C),ye=n.add(U,H);Ne=n.mul(Ne,ye),ye=n.add(X,pe),Ne=n.sub(Ne,ye),ye=n.add(B,A);let Re=n.add(U,k);return ye=n.mul(ye,Re),Re=n.add(X,me),ye=n.sub(ye,Re),Re=n.add(C,A),F=n.add(H,k),Re=n.mul(Re,F),F=n.add(pe,me),Re=n.sub(Re,F),W=n.mul(ae,ye),F=n.mul(te,me),W=n.add(F,W),F=n.sub(pe,W),W=n.add(pe,W),j=n.mul(F,W),pe=n.add(X,X),pe=n.add(pe,X),me=n.mul(ae,me),ye=n.mul(te,ye),pe=n.add(pe,me),me=n.sub(X,me),me=n.mul(ae,me),ye=n.add(ye,me),X=n.mul(pe,ye),j=n.add(j,X),X=n.mul(Re,ye),F=n.mul(Ne,F),F=n.sub(F,X),X=n.mul(Ne,pe),W=n.mul(Re,W),W=n.add(W,X),new N(F,j,W)}subtract(I){return this.add(I.negate())}is0(){return this.equals(N.ZERO)}multiply(I){let{endo:B}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let C,A,U=H=>P.cached(this,H,k=>CF(N,k));if(B){let{k1neg:H,k1:k,k2neg:F,k2:j}=_(I),{p:W,f:ae}=U(k),{p:te,f:X}=U(j);A=ae.add(X),C=M(B.beta,W,te,H,F)}else{let{p:H,f:k}=U(I);C=H,A=k}return CF(N,[C,A])[0]}multiplyUnsafe(I){let{endo:B}=t,C=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===Sp||C.is0())return N.ZERO;if(I===Y6)return C;if(P.hasCache(this))return this.multiply(I);if(B){let{k1neg:A,k1:U,k2neg:H,k2:k}=_(I),{p1:F,p2:j}=qje(N,C,U,k);return M(B.beta,F,j,A,H)}else return P.unsafe(C,I)}multiplyAndAddUnsafe(I,B,C){let A=this.multiplyUnsafe(B).add(I.multiplyUnsafe(C));return A.is0()?void 0:A}toAffine(I){return O(this,I)}isTorsionFree(){let{isTorsionFree:I}=t;return i===Y6?!0:I?I(N,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=t;return i===Y6?this:I?I(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return D7(I,"isCompressed"),this.assertValidity(),h(N,this,I)}toHex(I=!0){return G6(this.toBytes(I))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return CF(N,I)}static msm(I,B){return Wje(N,o,I,B)}static fromPrivateKey(I){return N.BASE.multiply(Z6(o,I))}}N.BASE=new N(s.Gx,s.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=o;let L=o.BITS,P=new qF(N,t.endo?Math.ceil(L/2):L);return N.BASE.precompute(8),N}function Age(e){return Uint8Array.of(e?2:3)}function Cge(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function aqe(e,t={}){let{Fn:r}=e,n=t.randomBytes||_y,o=Object.assign(Cge(e.Fp,r),{seed:wge(r.ORDER)});function s(p){try{return!!Z6(r,p)}catch{return!1}}function i(p,h){let{publicKey:y,publicKeyUncompressed:w}=o;try{let x=p.length;return h===!0&&x!==y||h===!1&&x!==w?!1:!!e.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return zje(Ay(p,o.seed,"seed"),r.ORDER)}function c(p,h=!0){return e.BASE.multiply(Z6(r,p)).toBytes(h)}function u(p){let h=a(p);return{secretKey:h,publicKey:c(h)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof e)return!0;let{secretKey:h,publicKey:y,publicKeyUncompressed:w}=o;if(r.allowedLengths||h===y)return;let x=Ss("key",p).length;return x===y||x===w}function f(p,h,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(h)===!1)throw new Error("second arg must be public key");let w=Z6(r,p);return e.fromHex(h).multiply(w).toBytes(y)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:p=>Z6(r,p),precompute(p=8,h=e.BASE){return h.precompute(p,!1)}},lengths:o})}function cqe(e,t,r={}){j7(t),J7(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||_y,o=r.hmac||((B,...C)=>Z7(t,B,Dm(...C))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h}=aqe(e,r),y={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function x(B){let C=a>>Y6;return B>C}function v(B,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${B}: out of range 1..Point.Fn.ORDER`);return C}function T(B,C){KF(C);let A=h.signature,U=C==="compact"?A:C==="recovered"?A+1:void 0;return Ay(B,U,`${C} signature`)}class E{constructor(C,A,U){this.r=v("r",C),this.s=v("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(C,A=w){T(C,A);let U;if(A==="der"){let{r:j,s:W}=Cp.toSig(Ay(C));return new E(j,W)}A==="recovered"&&(U=C[0],A="compact",C=C.subarray(1));let H=i.BYTES,k=C.subarray(0,H),F=C.subarray(H,H*2);return new E(i.fromBytes(k),i.fromBytes(F),U)}static fromHex(C,A){return this.fromBytes(B7(C),A)}addRecoveryBit(C){return new E(this.r,this.s,C)}recoverPublicKey(C){let A=s.ORDER,{r:U,s:H,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*Ege1)throw new Error("recovery id is ambiguous for h>1 curve");let F=k===2||k===3?U+a:U;if(!s.isValid(F))throw new Error("recovery id 2 or 3 invalid");let j=s.toBytes(F),W=e.fromBytes(Dm(Age((k&1)===0),j)),ae=i.inv(F),te=_(Ss("msgHash",C)),X=i.create(-te*ae),pe=i.create(H*ae),me=e.BASE.multiplyUnsafe(X).add(W.multiplyUnsafe(pe));if(me.is0())throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return x(this.s)}toBytes(C=w){if(KF(C),C==="der")return B7(Cp.hexFromSig(this));let A=i.toBytes(this.r),U=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Dm(Uint8Array.of(this.recovery),A,U)}return Dm(A,U)}toHex(C){return G6(this.toBytes(C))}assertValidity(){}static fromCompact(C){return E.fromBytes(Ss("sig",C),"compact")}static fromDER(C){return E.fromBytes(Ss("sig",C),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return G6(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return G6(this.toBytes("compact"))}}let S=r.bits2int||function(B){if(B.length>8192)throw new Error("input is too large");let C=Y7(B),A=B.length*8-c;return A>0?C>>BigInt(A):C},_=r.bits2int_modN||function(B){return i.create(S(B))},O=U5(c);function D(B){return jF("num < 2^"+c,B,Sp,O),i.toBytes(B)}function M(B,C){return Ay(B,void 0,"message"),C?Ay(t(B),void 0,"prehashed message"):B}function N(B,C,A){if(["recovered","canonical"].some(pe=>pe in A))throw new Error("sign() legacy options not supported");let{lowS:U,prehash:H,extraEntropy:k}=_F(A,y);B=M(B,H);let F=_(B),j=Z6(i,C),W=[D(j),D(F)];if(k!=null&&k!==!1){let pe=k===!0?n(h.secretKey):k;W.push(Ss("extraEntropy",pe))}let ae=Dm(...W),te=F;function X(pe){let me=S(pe);if(!i.isValidNot0(me))return;let Ne=i.inv(me),ye=e.BASE.multiply(me).toAffine(),Re=i.create(ye.x);if(Re===Sp)return;let Et=i.create(Ne*i.create(te+Re*j));if(Et===Sp)return;let kt=(ye.x===Re?0:2)|Number(ye.y&Y6),At=Et;return U&&x(Et)&&(At=i.neg(Et),kt^=1),new E(Re,At,kt)}return{seed:ae,k2sig:X}}function L(B,C,A={}){B=Ss("message",B);let{seed:U,k2sig:H}=N(B,C,A);return Bje(t.outputLen,i.BYTES,o)(U,H)}function P(B){let C,A=typeof B=="string"||V7(B),U=!A&&B!==null&&typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)C=new E(B.r,B.s);else if(A){try{C=E.fromBytes(Ss("sig",B),"der")}catch(H){if(!(H instanceof Cp.Err))throw H}if(!C)try{C=E.fromBytes(Ss("sig",B),"compact")}catch{return!1}}return C||!1}function R(B,C,A,U={}){let{lowS:H,prehash:k,format:F}=_F(U,y);if(A=Ss("publicKey",A),C=M(Ss("message",C),k),"strict"in U)throw new Error("options.strict was renamed to lowS");let j=F===void 0?P(B):E.fromBytes(Ss("sig",B),F);if(j===!1)return!1;try{let W=e.fromBytes(A);if(H&&j.hasHighS())return!1;let{r:ae,s:te}=j,X=_(C),pe=i.inv(te),me=i.create(X*pe),Ne=i.create(ae*pe),ye=e.BASE.multiplyUnsafe(me).add(W.multiplyUnsafe(Ne));return ye.is0()?!1:i.create(ye.x)===ae}catch{return!1}}function I(B,C,A={}){let{prehash:U}=_F(A,y);return C=M(C,U),E.fromBytes(B,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h,Point:e,sign:L,verify:R,recoverPublicKey:I,Signature:E,hash:t})}function lqe(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Fm(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function uqe(e){let{CURVE:t,curveOpts:r}=lqe(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function dqe(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,gge(r.Fn.ORDER,r.Fn.BITS))})}function fqe(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:o}=uqe(e),s=iqe(t,r),i=cqe(s,n,o);return dqe(e,i)}function GF(e,t){let r=n=>fqe({...e,hash:n});return{...r(t),create:r}}function Nge(){let e=WF.utils.randomPrivateKey(),t=WF.getPublicKey(e);return{privateKey:Ut(e,Is),publicKey:Ut(t,Is)}}function Q7(){let e=_y(mz);return Ut(e,Is)}function Rge(e,t){let r=WF.getSharedSecret(Qt(e,Is),Qt(t,Is)),n=Rje(G7,r,void 0,void 0,mz);return Ut(n,Is)}function tx(e){let t=G7(Qt(e,Is));return Ut(t,Is)}function Wi(e){let t=G7(Qt(e,D5));return Ut(t,Is)}function Oge(e){return Qt(`${e}`,_ge)}function Hm(e){return Number(Ut(e,_ge))}function Bge(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kge(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}function Uge(e){let t=Oge(typeof e.type<"u"?e.type:Pge);if(Hm(t)===vl&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof e.senderPublicKey<"u"?Qt(e.senderPublicKey,Is):void 0,n=typeof e.iv<"u"?Qt(e.iv,Is):_y(S5),o=Qt(e.symKey,Is),s=sge(o,n).encrypt(Qt(e.message,D5)),i=Hge({type:t,sealed:s,iv:n,senderPublicKey:r});return e.encoding===Np?Bge(i):i}function Dge(e){let t=Qt(e.symKey,Is),{sealed:r,iv:n}=rx({encoded:e.encoded,encoding:e.encoding}),o=sge(t,n).decrypt(r);if(o===null)throw new Error("Failed to decrypt");return Ut(o,D5)}function Lge(e,t){let r=Oge(ex),n=_y(S5),o=Qt(e,D5),s=Hge({type:r,sealed:o,iv:n});return t===Np?Bge(s):s}function Mge(e,t){let{sealed:r}=rx({encoded:e,encoding:t});return Ut(r,D5)}function Hge(e){if(Hm(e.type)===ex)return Ut(Ms([e.type,e.sealed]),Ts);if(Hm(e.type)===vl){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ut(Ms([e.type,e.senderPublicKey,e.iv,e.sealed]),Ts)}return Ut(Ms([e.type,e.iv,e.sealed]),Ts)}function rx(e){let t=(e.encoding||Ts)===Np?kge(e.encoded):e.encoded,r=Qt(t,Ts),n=r.slice(wqe,h1e),o=h1e;if(Hm(n)===vl){let c=o+mz,u=c+S5,d=r.slice(o,c),f=r.slice(c,u),p=r.slice(u);return{type:n,sealed:p,iv:f,senderPublicKey:d}}if(Hm(n)===ex){let c=r.slice(o),u=_y(S5);return{type:n,sealed:c,iv:u}}let s=o+S5,i=r.slice(o,s),a=r.slice(s);return{type:n,sealed:a,iv:i}}function $ge(e,t){let r=rx({encoded:e,encoding:t?.encoding});return gz({type:Hm(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ut(r.senderPublicKey,Is):void 0,receiverPublicKey:t?.receiverPublicKey})}function gz(e){let t=e?.type||Pge;if(t===vl){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function yz(e){return e.type===vl&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function wz(e){return e.type===ex}function bqe(e){let t=Buffer.from(e.x,"base64"),r=Buffer.from(e.y,"base64");return Ms([new Uint8Array([4]),t,r])}function Fge(e,t){let[r,n,o]=e.split("."),s=Buffer.from(kge(o),"base64");if(s.length!==64)throw new Error("Invalid signature length");let i=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=G7(c),d=bqe(t);if(!yqe.verify(Ms([i,a]),u,d))throw new Error("Invalid signature");return Hl(e).payload}function L5(e){return e?.relay||{protocol:xqe}}function Py(e){let t=kC[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Tqe(e,t="-"){let r={},n="relay"+t;return Object.keys(e).forEach(o=>{if(o.startsWith(n)){let s=o.replace(n,""),i=e[o];r[s]=i}}),r}function bz(e){if(!e.includes("wc:")){let u=k1e(e);u!=null&&u.includes("wc:")&&(e=u)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;let t=e.indexOf(":"),r=e.indexOf("?")!==-1?e.indexOf("?"):void 0,n=e.substring(0,t),o=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",i=new URLSearchParams(s),a=Object.fromEntries(i.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:_qe(o[0]),version:parseInt(o[1],10),symKey:a.symKey,relay:Tqe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function _qe(e){return e.startsWith("//")?e.substring(2):e}function Pqe(e,t="-"){let r="relay",n={};return Object.keys(e).forEach(o=>{let s=o,i=r+t+s;e[s]&&(n[i]=e[s])}),n}function xz(e){let t=new URLSearchParams,r=PF(PF(Iqe(PF({},Pqe(e.relay)),{symKey:e.symKey}),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")});return Object.entries(r).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!==void 0&&t.append(n,String(o))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function M5(e,t,r){return`${e}?wc_ev=${r}&topic=${t}`}function nx(e){let t=[];return e.forEach(r=>{let[n,o]=r.split(":");t.push(`${n}:${o}`)}),t}function vz(e){let t=[];return Object.values(e).forEach(r=>{t.push(...nx(r.accounts))}),[...new Set(t)]}function zge(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.methods)}),[...new Set(t)]}function Vge(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.events)}),[...new Set(t)]}function Lqe(e,t){let r=[];return Object.values(e).forEach(n=>{nx(n.accounts).includes(t)&&r.push(...n.methods)}),r}function Mqe(e,t){let r=[];return Object.values(e).forEach(n=>{nx(n.accounts).includes(t)&&r.push(...n.events)}),r}function H5(e){return e.includes(":")}function Ny(e){return H5(e)?e.split(":")[0]:e}function b1e(e){var t,r,n;let o={};if(!xc(e))return o;for(let[s,i]of Object.entries(e)){let a=H5(s)?[s]:i.chains,c=i.methods||[],u=i.events||[],d=Ny(s);o[d]=Dqe(Uqe({},o[d]),{chains:ml(a,(t=o[d])==null?void 0:t.chains),methods:ml(c,(r=o[d])==null?void 0:r.methods),events:ml(u,(n=o[d])==null?void 0:n.events)})}return o}function Hqe(e){let t={};return e?.forEach(r=>{var n;let[o,s]=r.split(":");t[o]||(t[o]={accounts:[],chains:[],events:[],methods:[]}),t[o].accounts.push(r),(n=t[o].chains)==null||n.push(`${o}:${s}`)}),t}function Ez(e,t){t=t.map(n=>n.replace("did:pkh:",""));let r=Hqe(t);for(let[n,o]of Object.entries(r))o.methods?o.methods=ml(o.methods,e):o.methods=e,o.events=["chainChanged","accountsChanged"];return r}function jge(e,t){var r,n,o,s,i,a;let c=b1e(e),u=b1e(t),d={},f=Object.keys(c).concat(Object.keys(u));for(let p of f)d[p]={chains:ml((r=c[p])==null?void 0:r.chains,(n=u[p])==null?void 0:n.chains),methods:ml((o=c[p])==null?void 0:o.methods,(s=u[p])==null?void 0:s.methods),events:ml((i=c[p])==null?void 0:i.events,(a=u[p])==null?void 0:a.events)};return d}function Ie(e,t){let{message:r,code:n}=Fqe[e];return{message:t?`${r} ${t}`:r,code:n}}function Rr(e,t){let{message:r,code:n}=$qe[e];return{message:t?`${r} ${t}`:r,code:n}}function El(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function xc(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Ln(e){return typeof e>"u"}function An(e,t){return t&&Ln(e)?!0:typeof e=="string"&&!!e.trim().length}function Az(e,t){return t&&Ln(e)?!0:typeof e=="number"&&!isNaN(e)}function qge(e,t){let{requiredNamespaces:r}=t,n=Object.keys(e.namespaces),o=Object.keys(r),s=!0;return Ey(o,n)?(n.forEach(i=>{let{accounts:a,methods:c,events:u}=e.namespaces[i],d=nx(a),f=r[i];(!Ey(C1e(i,f),d)||!Ey(f.methods,c)||!Ey(f.events,u))&&(s=!1)}),s):!1}function H7(e){return An(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function zqe(e){if(An(e,!1)&&e.includes(":")){let t=e.split(":");if(t.length===3){let r=t[0]+":"+t[1];return!!t[2]&&H7(r)}}return!1}function Wge(e){function t(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(An(e,!1)){if(t(e))return!0;let r=k1e(e);return t(r)}}catch{}return!1}function Kge(e){var t;return(t=e?.proposer)==null?void 0:t.publicKey}function Zge(e){return e?.topic}function Gge(e,t){let r=null;return An(e?.publicKey,!1)||(r=Ie("MISSING_OR_INVALID",`${t} controller public key should be a string`)),r}function x1e(e){let t=!0;return El(e)?e.length&&(t=e.every(r=>An(r,!1))):t=!1,t}function Vqe(e,t,r){let n=null;return El(t)&&t.length?t.forEach(o=>{n||H7(o)||(n=Rr("UNSUPPORTED_CHAINS",`${r}, chain ${o} should be a string and conform to "namespace:chainId" format`))}):H7(e)||(n=Rr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function jqe(e,t,r){let n=null;return Object.entries(e).forEach(([o,s])=>{if(n)return;let i=Vqe(o,C1e(o,s),`${t} ${r}`);i&&(n=i)}),n}function qqe(e,t){let r=null;return El(e)?e.forEach(n=>{r||zqe(n)||(r=Rr("UNSUPPORTED_ACCOUNTS",`${t}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=Rr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function Wqe(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=qqe(n?.accounts,`${t} namespace`);o&&(r=o)}),r}function Kqe(e,t){let r=null;return x1e(e?.methods)?x1e(e?.events)||(r=Rr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Rr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}function Yge(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=Kqe(n,`${t}, namespace`);o&&(r=o)}),r}function Jge(e,t,r){let n=null;if(e&&xc(e)){let o=Yge(e,t);o&&(n=o);let s=jqe(e,t,r);s&&(n=s)}else n=Ie("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return n}function X7(e,t){let r=null;if(e&&xc(e)){let n=Yge(e,t);n&&(r=n);let o=Wqe(e,t);o&&(r=o)}else r=Ie("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function Cz(e){return An(e.protocol,!0)}function Qge(e,t){let r=!1;return t&&!e?r=!0:e&&El(e)&&e.length&&e.forEach(n=>{r=Cz(n)}),r}function Xge(e){return typeof e=="number"}function _s(e){return typeof e<"u"&&typeof e!==null}function eye(e){return!(!e||typeof e!="object"||!e.code||!Az(e.code,!1)||!e.message||!An(e.message,!1))}function tye(e){return!(Ln(e)||!An(e.method,!1))}function rye(e){return!(Ln(e)||Ln(e.result)&&Ln(e.error)||!Az(e.id,!1)||!An(e.jsonrpc,!1))}function nye(e){return!(Ln(e)||!An(e.name,!1))}function Sz(e,t){return!(!H7(t)||!vz(e).includes(t))}function oye(e,t,r){return An(r,!1)?Lqe(e,t).includes(r):!1}function sye(e,t,r){return An(r,!1)?Mqe(e,t).includes(r):!1}function Iz(e,t,r){let n=null,o=Zqe(e),s=Gqe(t),i=Object.keys(o),a=Object.keys(s),c=v1e(Object.keys(e)),u=v1e(Object.keys(t)),d=c.filter(f=>!u.includes(f));return d.length&&(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. + Required: ${d.toString()} + Received: ${Object.keys(t).toString()}`)),Ey(i,a)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. + Required: ${i.toString()} + Approved: ${a.toString()}`)),Object.keys(t).forEach(f=>{if(!f.includes(":")||n)return;let p=nx(t[f].accounts);p.includes(f)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${f} + Required: ${f} + Approved: ${p.toString()}`))}),i.forEach(f=>{n||(Ey(o[f].methods,s[f].methods)?Ey(o[f].events,s[f].events)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function Zqe(e){let t={};return Object.keys(e).forEach(r=>{var n;r.includes(":")?t[r]=e[r]:(n=e[r].chains)==null||n.forEach(o=>{t[o]={methods:e[r].methods,events:e[r].events}})}),t}function v1e(e){return[...new Set(e.map(t=>t.includes(":")?t.split(":")[0]:t))]}function Gqe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:nx(e[r].accounts)?.forEach(o=>{t[o]={accounts:e[r].accounts.filter(s=>s.includes(`${o}:`)),methods:e[r].methods,events:e[r].events}})}),t}function iye(e,t){return Az(e,!1)&&e<=t.max&&e>=t.min}function Tz(){let e=N5();return new Promise(t=>{switch(e){case ji.browser:t(Yqe());break;case ji.reactNative:t(Jqe());break;case ji.node:t(Qqe());break;default:t(!0)}})}function Yqe(){return Ty()&&navigator?.onLine}async function Jqe(){return _p()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function Qqe(){return!0}function aye(e){switch(N5()){case ji.browser:Xqe(e);break;case ji.reactNative:eWe(e);break;case ji.node:break}}function Xqe(e){!_p()&&Ty()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}function eWe(e){_p()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(t=>e(t?.isConnected))}function cye(){var e;return Ty()&&(0,yl.getDocument)()?((e=(0,yl.getDocument)())==null?void 0:e.visibilityState)==="visible":!0}function tWe(e){let t=wm.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}function rWe({publicKey:e,signature:t,payload:r}){var n;let o=YF(r.method),s=128|parseInt(((n=r.version)==null?void 0:n.toString())||"4"),i=sWe(r.address),a=r.era==="00"?new Uint8Array([0]):YF(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");let c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${oWe(r.tip)}`),f=aWe(d),p=new Uint8Array([0,...e,i,...t,...a,...u,...f,...o]),h=iWe(p.length+1);return new Uint8Array([...h,s,...p])}function nWe(e){let t=YF(e),r=(0,A1e.blake2b)(t,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function YF(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(t=>parseInt(t,16)))}function oWe(e){return e.startsWith("0x")?e.slice(2):e}function sWe(e){let t=wm.decode(e)[0];return t===42?0:t===60?2:1}function iWe(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([t&255,t>>8&255])}else if(e<1<<30){let t=e<<2|2;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function aWe(e){if(e>BigInt(8)&BigInt(255))])}else if(e>BigInt(8)&BigInt(255)),Number(t>>BigInt(16)&BigInt(255)),Number(t>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function lye(e){let t=Uint8Array.from(Buffer.from(e.signature,"hex")),r=tWe(e.transaction.address),n=rWe({publicKey:r,signature:t,payload:e.transaction}),o=Buffer.from(n).toString("hex");return nWe(o)}function ox({logger:e,name:t}){let r=typeof e=="string"?Fl({opts:{level:e,name:t}}).logger:e;return r.level=typeof e=="string"?e:e.level,r}var Ip,yl,E1e,A1e,Mze,Hze,$ze,Fze,zme,zze,Vze,RF,Vme,jze,jme,qze,ji,Wze,O7,T7,qme,Wme,Kme,Bm,km,A5,C5,tVe,rVe,nVe,oVe,sVe,iVe,rz,nz,aVe,cVe,lVe,uVe,W6,M1e,Ap,Um,$1e,fVe,Ep,J6,hVe,v5,mVe,gVe,yVe,wVe,z1e,V1e,j1e,q1e,bVe,xVe,Gme,Yme,OF,EVe,AVe,k7,Tm,Es,As,TVe,_m,BF,W1e,_Ve,PVe,Pm,Nm,T5,kF,Cs,UF,q7,NVe,RVe,OVe,BVe,co,ke,DF,LF,UVe,DVe,zVe,VVe,jVe,Jme,qVe,WVe,Qme,KVe,ZVe,Q1e,GVe,YVe,W7,JVe,QVe,K7,B5,cz,cje,fje,nge,mje,gje,yje,wje,_7,bje,oge,r1e,qo,zF,Aje,Sje,Ije,n1e,Tje,_je,sge,U7,Z7,EF,s1e,Rje,G7,dz,VF,AF,U5,qi,pi,Cy,cge,lge,uge,kje,dge,Uje,fge,Hje,X6,Sy,IF,xge,qF,E5,K6,N7,Yje,f1e,Jje,Qje,Xje,vge,eqe,nqe,WF,p1e,ZF,Cp,Sp,Y6,Ege,R7,sqe,Sge,Ige,Tge,pqe,hqe,mqe,gqe,yqe,_ge,Is,Ts,Np,D5,Pge,vl,ex,wqe,h1e,S5,mz,xqe,vqe,Eqe,Aqe,m1e,Cqe,Sqe,g1e,PF,Iqe,Nqe,Rqe,Oqe,y1e,Bqe,kqe,w1e,Uqe,Dqe,$qe,Fqe,NF,$m,eP=b(()=>{l();jN();Ip=Ht(jd(),1),yl=Ht(C2(),1),E1e=Ht(JN(),1);Cme();RH();Fme();JR();B1();I8();BB();A1e=Ht(LB(),1);gh();Mze=":";Hze=Object.defineProperty,$ze=Object.defineProperties,Fze=Object.getOwnPropertyDescriptors,zme=Object.getOwnPropertySymbols,zze=Object.prototype.hasOwnProperty,Vze=Object.prototype.propertyIsEnumerable,RF=(e,t,r)=>t in e?Hze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vme=(e,t)=>{for(var r in t||(t={}))zze.call(t,r)&&RF(e,r,t[r]);if(zme)for(var r of zme(t))Vze.call(t,r)&&RF(e,r,t[r]);return e},jze=(e,t)=>$ze(e,Fze(t)),jme=(e,t,r)=>RF(e,typeof t!="symbol"?t+"":t,r),qze="ReactNative",ji={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wze="js";O7=class{constructor({limit:t}){jme(this,"limit"),jme(this,"set"),this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){let r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(t)}}has(t){return this.set.has(t)}},T7=BigInt(2**32-1),qme=BigInt(32);Wme=(e,t,r)=>e>>>r,Kme=(e,t,r)=>e<<32-r|t>>>r,Bm=(e,t,r)=>e>>>r|t<<32-r,km=(e,t,r)=>e<<32-r|t>>>r,A5=(e,t,r)=>e<<64-r|t>>>r-32,C5=(e,t,r)=>e>>>r-32|t<<64-r,tVe=(e,t)=>t,rVe=(e,t)=>e,nVe=(e,t,r)=>e<>>32-r,oVe=(e,t,r)=>t<>>32-r,sVe=(e,t,r)=>t<>>64-r,iVe=(e,t,r)=>e<>>64-r;rz=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),nz=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,aVe=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),cVe=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,lVe=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),uVe=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,W6=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;M1e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Ap=M1e?e=>e:e=>H1e(e);Um=M1e?e=>e:dVe,$1e=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fVe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Ep={_0:48,_9:57,A:65,F:70,a:97,f:102};J6=class{};hVe=BigInt(0),v5=BigInt(1),mVe=BigInt(2),gVe=BigInt(7),yVe=BigInt(256),wVe=BigInt(113),z1e=[],V1e=[],j1e=[];for(let e=0,t=v5,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],z1e.push(2*(5*n+r)),V1e.push((e+1)*(e+2)/2%64);let o=hVe;for(let s=0;s<7;s++)t=(t<>gVe)*wVe)%yVe,t&mVe&&(o^=v5<<(v5<r>32?sVe(e,t,r):nVe(e,t,r),Yme=(e,t,r)=>r>32?iVe(e,t,r):oVe(e,t,r);OF=class e extends J6{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Tp(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Tp(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(oz(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,bc(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},EVe=(e,t,r)=>O5(()=>new OF(t,e,r)),AVe=EVe(1,136,256/8);k7=class extends J6{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=bF(this.buffer)}update(t){Mm(this),t=gl(t),wl(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>>3,w=_u(h,17)^_u(h,19)^h>>>10;_m[f]=w+_m[f-7]+y+_m[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=_u(a,6)^_u(a,11)^_u(a,25),h=d+p+SVe(a,c,u)+TVe[f]+_m[f]|0,y=(_u(n,2)^_u(n,13)^_u(n,22))+IVe(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){bc(_m)}destroy(){this.set(0,0,0,0,0,0,0,0),bc(this.buffer)}},W1e=L1e(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),_Ve=W1e[0],PVe=W1e[1],Pm=new Uint32Array(80),Nm=new Uint32Array(80),T5=class extends k7{constructor(t=64){super(128,t,16,!1),this.Ah=As[0]|0,this.Al=As[1]|0,this.Bh=As[2]|0,this.Bl=As[3]|0,this.Ch=As[4]|0,this.Cl=As[5]|0,this.Dh=As[6]|0,this.Dl=As[7]|0,this.Eh=As[8]|0,this.El=As[9]|0,this.Fh=As[10]|0,this.Fl=As[11]|0,this.Gh=As[12]|0,this.Gl=As[13]|0,this.Hh=As[14]|0,this.Hl=As[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)Pm[E]=t.getUint32(r),Nm[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Pm[E-15]|0,_=Nm[E-15]|0,O=Bm(S,_,1)^Bm(S,_,8)^Wme(S,_,7),D=km(S,_,1)^km(S,_,8)^Kme(S,_,7),M=Pm[E-2]|0,N=Nm[E-2]|0,L=Bm(M,N,19)^A5(M,N,61)^Wme(M,N,6),P=km(M,N,19)^C5(M,N,61)^Kme(M,N,6),R=aVe(D,P,Nm[E-7],Nm[E-16]),I=cVe(R,O,L,Pm[E-7],Pm[E-16]);Pm[E]=I|0,Nm[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Bm(f,p,14)^Bm(f,p,18)^A5(f,p,41),_=km(f,p,14)^km(f,p,18)^C5(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=lVe(T,_,D,PVe[E],Nm[E]),N=uVe(M,v,S,O,_Ve[E],Pm[E]),L=M|0,P=Bm(n,o,28)^A5(n,o,34)^A5(n,o,39),R=km(n,o,28)^C5(n,o,34)^C5(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=hl(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=rz(L,R,B);n=nz(C,N,P,I),o=C|0}({h:n,l:o}=hl(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=hl(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=hl(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=hl(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=hl(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=hl(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=hl(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=hl(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){bc(Pm,Nm)}destroy(){bc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},kF=class extends T5{constructor(){super(48),this.Ah=Es[0]|0,this.Al=Es[1]|0,this.Bh=Es[2]|0,this.Bl=Es[3]|0,this.Ch=Es[4]|0,this.Cl=Es[5]|0,this.Dh=Es[6]|0,this.Dl=Es[7]|0,this.Eh=Es[8]|0,this.El=Es[9]|0,this.Fh=Es[10]|0,this.Fl=Es[11]|0,this.Gh=Es[12]|0,this.Gl=Es[13]|0,this.Hh=Es[14]|0,this.Hl=Es[15]|0}},Cs=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),UF=class extends T5{constructor(){super(32),this.Ah=Cs[0]|0,this.Al=Cs[1]|0,this.Bh=Cs[2]|0,this.Bl=Cs[3]|0,this.Ch=Cs[4]|0,this.Cl=Cs[5]|0,this.Dh=Cs[6]|0,this.Dl=Cs[7]|0,this.Eh=Cs[8]|0,this.El=Cs[9]|0,this.Fh=Cs[10]|0,this.Fl=Cs[11]|0,this.Gh=Cs[12]|0,this.Gl=Cs[13]|0,this.Hh=Cs[14]|0,this.Hl=Cs[15]|0}},q7=O5(()=>new BF),NVe=O5(()=>new T5),RVe=O5(()=>new kF),OVe=O5(()=>new UF),BVe=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),co=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ke=new Uint32Array(32);DF=class extends J6{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Tp(t),Tp(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=I5(this.buffer)}update(t){Mm(this),t=gl(t),wl(t);let{blockLen:r,buffer:n,buffer32:o}=this,s=t.length,i=t.byteOffset,a=t.buffer;for(let c=0;co[i]=Ap(s))}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){let{buffer:r,length:n,finished:o,destroyed:s,outputLen:i,pos:a}=this;return t||(t=new this.constructor({dkLen:i})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=o,t.length=n,t.pos=a,t.outputLen=i,t}clone(){return this._cloneInto()}},LF=class extends DF{constructor(t={}){let r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=co[0]|0,this.v0h=co[1]|0,this.v1l=co[2]|0,this.v1h=co[3]|0,this.v2l=co[4]|0,this.v2h=co[5]|0,this.v3l=co[6]|0,this.v3h=co[7]|0,this.v4l=co[8]|0,this.v4h=co[9]|0,this.v5l=co[10]|0,this.v5h=co[11]|0,this.v6l=co[12]|0,this.v6h=co[13]|0,this.v7l=co[14]|0,this.v7h=co[15]|0,kVe(r,t,64,16,16);let{key:n,personalization:o,salt:s}=t,i=0;if(n!==void 0&&(n=gl(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){s=gl(s);let a=I5(s);this.v4l^=Ap(a[0]),this.v4h^=Ap(a[1]),this.v5l^=Ap(a[2]),this.v5h^=Ap(a[3])}if(o!==void 0){o=gl(o);let a=I5(o);this.v6l^=Ap(a[0]),this.v6h^=Ap(a[1]),this.v7l^=Ap(a[2]),this.v7h^=Ap(a[3])}if(n!==void 0){let a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:u,v4h:d,v5l:f,v5h:p,v6l:h,v6h:y,v7l:w,v7h:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=d|0,this.v5l=f|0,this.v5h=p|0,this.v6l=h|0,this.v6h=y|0,this.v7l=w|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>ke[u]=c),ke.set(co,16);let{h:o,l:s}=D1e(BigInt(this.length));ke[24]=co[8]^s,ke[25]=co[9]^o,n&&(ke[28]=~ke[28],ke[29]=~ke[29]);let i=0,a=BVe;for(let c=0;c<12;c++)Rm(0,4,8,12,t,r+2*a[i++]),Om(0,4,8,12,t,r+2*a[i++]),Rm(1,5,9,13,t,r+2*a[i++]),Om(1,5,9,13,t,r+2*a[i++]),Rm(2,6,10,14,t,r+2*a[i++]),Om(2,6,10,14,t,r+2*a[i++]),Rm(3,7,11,15,t,r+2*a[i++]),Om(3,7,11,15,t,r+2*a[i++]),Rm(0,5,10,15,t,r+2*a[i++]),Om(0,5,10,15,t,r+2*a[i++]),Rm(1,6,11,12,t,r+2*a[i++]),Om(1,6,11,12,t,r+2*a[i++]),Rm(2,7,8,13,t,r+2*a[i++]),Om(2,7,8,13,t,r+2*a[i++]),Rm(3,4,9,14,t,r+2*a[i++]),Om(3,4,9,14,t,r+2*a[i++]);this.v0l^=ke[0]^ke[16],this.v0h^=ke[1]^ke[17],this.v1l^=ke[2]^ke[18],this.v1h^=ke[3]^ke[19],this.v2l^=ke[4]^ke[20],this.v2h^=ke[5]^ke[21],this.v3l^=ke[6]^ke[22],this.v3h^=ke[7]^ke[23],this.v4l^=ke[8]^ke[24],this.v4h^=ke[9]^ke[25],this.v5l^=ke[10]^ke[26],this.v5h^=ke[11]^ke[27],this.v6l^=ke[12]^ke[28],this.v6h^=ke[13]^ke[29],this.v7l^=ke[14]^ke[30],this.v7h^=ke[15]^ke[31],bc(ke)}destroy(){this.destroyed=!0,bc(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},UVe=pVe(e=>new LF(e)),DVe="https://rpc.walletconnect.org/v1";zVe=Object.defineProperty,VVe=Object.defineProperties,jVe=Object.getOwnPropertyDescriptors,Jme=Object.getOwnPropertySymbols,qVe=Object.prototype.hasOwnProperty,WVe=Object.prototype.propertyIsEnumerable,Qme=(e,t,r)=>t in e?zVe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,KVe=(e,t)=>{for(var r in t||(t={}))qVe.call(t,r)&&Qme(e,r,t[r]);if(Jme)for(var r of Jme(t))WVe.call(t,r)&&Qme(e,r,t[r]);return e},ZVe=(e,t)=>VVe(e,jVe(t)),Q1e="did:pkh:",GVe={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},YVe=e=>e?GVe[e]||e:"",W7=e=>e?.split(":"),JVe=e=>{let t=e&&W7(e);if(t)return e.includes(Q1e)?t[3]:t[1]},QVe=e=>{let t=e&&W7(e);if(t)return e.includes(Q1e)?t[2]:t[0]},K7=e=>{let t=e&&W7(e);if(t)return t[2]+":"+t[3]},B5=e=>{let t=e&&W7(e);if(t)return t.pop()};cz=(e,t)=>{let r=QVe(t);if(!r)throw new Error("Invalid issuer: "+t);let n=`${e.domain} wants you to sign in with your ${YVe(r)} account:`,o=B5(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0,i=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${JVe(t)}`,u=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,f=e.exp?`Expiration Time: ${e.exp}`:void 0,p=e.nbf?`Not Before: ${e.nbf}`:void 0,h=e.requestId?`Request ID: ${e.requestId}`:void 0,y=e.resources?`Resources:${e.resources.map(x=>` +- ${x}`).join("")}`:void 0,w=k5(e.resources);if(w){let x=_5(w);s=sje(s,x)}return[n,o,"",s,"",i,a,c,u,d,f,p,h,y].filter(x=>x!=null).join(` +`)};cje=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;fje=(e,t)=>{function r(n,...o){if(Vi(n),!cje)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");e.varSizeNonce?Vi(u):Vi(u,e.nonceLength)}let s=e.tagLength;s&&o[1]!==void 0&&Vi(o[1]);let i=t(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Vi(d)}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Vi(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(Vi(u),s&&u.lengtht.charCodeAt(0))),mje=nge("expand 16-byte k"),gje=nge("expand 32-byte k"),yje=Lm(mje),wje=Lm(gje);_7=64,bje=16,oge=2**32-1,r1e=new Uint32Array;qo=(e,t)=>e[t++]&255|(e[t++]&255)<<8,zF=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=HF(t),Vi(t,32);let r=qo(t,0),n=qo(t,2),o=qo(t,4),s=qo(t,6),i=qo(t,8),a=qo(t,10),c=qo(t,12),u=qo(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=qo(t,16+2*d)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],d=i[3],f=i[4],p=i[5],h=i[6],y=i[7],w=i[8],x=i[9],v=qo(t,r+0),T=qo(t,r+2),E=qo(t,r+4),S=qo(t,r+6),_=qo(t,r+8),O=qo(t,r+10),D=qo(t,r+12),M=qo(t,r+14),N=s[0]+(v&8191),L=s[1]+((v>>>13|T<<3)&8191),P=s[2]+((T>>>10|E<<6)&8191),R=s[3]+((E>>>7|S<<9)&8191),I=s[4]+((S>>>4|_<<12)&8191),B=s[5]+(_>>>1&8191),C=s[6]+((_>>>14|O<<2)&8191),A=s[7]+((O>>>11|D<<5)&8191),U=s[8]+((D>>>8|M<<8)&8191),H=s[9]+(M>>>5|o),k=0,F=k+N*a+L*(5*x)+P*(5*w)+R*(5*y)+I*(5*h);k=F>>>13,F&=8191,F+=B*(5*p)+C*(5*f)+A*(5*d)+U*(5*u)+H*(5*c),k+=F>>>13,F&=8191;let j=k+N*c+L*a+P*(5*x)+R*(5*w)+I*(5*y);k=j>>>13,j&=8191,j+=B*(5*h)+C*(5*p)+A*(5*f)+U*(5*d)+H*(5*u),k+=j>>>13,j&=8191;let W=k+N*u+L*c+P*a+R*(5*x)+I*(5*w);k=W>>>13,W&=8191,W+=B*(5*y)+C*(5*h)+A*(5*p)+U*(5*f)+H*(5*d),k+=W>>>13,W&=8191;let ae=k+N*d+L*u+P*c+R*a+I*(5*x);k=ae>>>13,ae&=8191,ae+=B*(5*w)+C*(5*y)+A*(5*h)+U*(5*p)+H*(5*f),k+=ae>>>13,ae&=8191;let te=k+N*f+L*d+P*u+R*c+I*a;k=te>>>13,te&=8191,te+=B*(5*x)+C*(5*w)+A*(5*y)+U*(5*h)+H*(5*p),k+=te>>>13,te&=8191;let X=k+N*p+L*f+P*d+R*u+I*c;k=X>>>13,X&=8191,X+=B*a+C*(5*x)+A*(5*w)+U*(5*y)+H*(5*h),k+=X>>>13,X&=8191;let pe=k+N*h+L*p+P*f+R*d+I*u;k=pe>>>13,pe&=8191,pe+=B*c+C*a+A*(5*x)+U*(5*w)+H*(5*y),k+=pe>>>13,pe&=8191;let me=k+N*y+L*h+P*p+R*f+I*d;k=me>>>13,me&=8191,me+=B*u+C*c+A*a+U*(5*x)+H*(5*w),k+=me>>>13,me&=8191;let Ne=k+N*w+L*y+P*h+R*p+I*f;k=Ne>>>13,Ne&=8191,Ne+=B*d+C*u+A*c+U*a+H*(5*x),k+=Ne>>>13,Ne&=8191;let ye=k+N*x+L*w+P*y+R*h+I*p;k=ye>>>13,ye&=8191,ye+=B*f+C*d+A*u+U*c+H*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+F|0,F=k&8191,k=k>>>13,j+=k,s[0]=F,s[1]=j,s[2]=W,s[3]=ae,s[4]=te,s[5]=X,s[6]=pe,s[7]=me,s[8]=Ne,s[9]=ye}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;Q6(n)}update(t){Xme(this),t=HF(t),Vi(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};Aje=Eje(e=>new zF(e));Sje=vje(Cje,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ije=new Uint8Array(16),n1e=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ije.subarray(r))},Tje=new Uint8Array(32);_je=e=>(t,r,n)=>({encrypt(o,s){let i=o.length;s=e1e(i+16,s,!1),s.set(o);let a=s.subarray(0,-16);e(t,r,a,a,1);let c=o1e(e,t,r,a,n);return s.set(c,i),Q6(c),s},decrypt(o,s){s=e1e(o.length-16,s,!1);let i=o.subarray(0,-16),a=o.subarray(-16),c=o1e(e,t,r,i,n);if(!dje(a,c))throw new Error("invalid tag");return s.set(o.subarray(0,-16)),e(t,r,s,s,1),Q6(c),s}}),sge=fje({blockSize:64,nonceLength:12,tagLength:16},_je(Sje)),U7=class extends J6{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,j7(t);let n=gl(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew U7(e,t).update(r).digest();Z7.create=(e,t)=>new U7(e,t);EF=Uint8Array.from([0]),s1e=Uint8Array.of();Rje=(e,t,r,n,o)=>Nje(e,Pje(e,t,r),n,o),G7=q7,dz=BigInt(0),VF=BigInt(1);AF=e=>typeof e=="bigint"&&dz<=e;U5=e=>(VF<X6;)r&Sy&&(n=n.add(o)),o=o.double(),r>>=Sy;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=SF(r,this.bits),s=[],i=t,a=i;for(let c=0;c{let e=nqe.ORDER;return Gje({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=tqe(t);return Ba(pl(r,Jje,e)*n,e)},adjustScalarBytes:rqe})})(),p1e=(e,t)=>(e+(e>=0?t:-t)/Ege)/t;ZF=class extends Error{constructor(t=""){super(t)}},Cp={Err:ZF,_tlv:{encode:(e,t)=>{let{Err:r}=Cp;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=P7(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?P7(o.length/2|128):"";return P7(e)+s+o+t},decode(e,t){let{Err:r}=Cp,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Cp;if(et in e?vqe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,PF=(e,t)=>{for(var r in t||(t={}))Cqe.call(t,r)&&g1e(e,r,t[r]);if(m1e)for(var r of m1e(t))Sqe.call(t,r)&&g1e(e,r,t[r]);return e},Iqe=(e,t)=>Eqe(e,Aqe(t));Nqe=Object.defineProperty,Rqe=Object.defineProperties,Oqe=Object.getOwnPropertyDescriptors,y1e=Object.getOwnPropertySymbols,Bqe=Object.prototype.hasOwnProperty,kqe=Object.prototype.propertyIsEnumerable,w1e=(e,t,r)=>t in e?Nqe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Uqe=(e,t)=>{for(var r in t||(t={}))Bqe.call(t,r)&&w1e(e,r,t[r]);if(y1e)for(var r of y1e(t))kqe.call(t,r)&&w1e(e,r,t[r]);return e},Dqe=(e,t)=>Rqe(e,Oqe(t));$qe={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Fqe={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};NF={},$m=class{static get(t){return NF[t]}static set(t,r){NF[t]=r}static delete(t){delete NF[t]}}});function zWe(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}function PKe(e){return e.reduce((t,r)=>(t+=TKe[r],t),"")}function NKe(e){let t=[];for(let r of e){let n=_Ke[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}function zye(e,t,r){t=t||[],r=r||0;for(var n=r;e>=DKe;)t[r++]=e&255|fye,e/=128;for(;e&UKe;)t[r++]=e&255|fye,e>>>=7;return t[r]=e|0,zye.bytes=r-n+1,t}function Dz(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Dz.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&pye)<=MKe);return Dz.bytes=s-n,r}function Zye(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function nZe(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zye(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Gye(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}function sZe(e,t="utf8"){let r=oZe[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zye(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function OZe(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Cye(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function Sye(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}function nGe(){}function Tye(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function oGe(e,t,r){return V5(e,t,void 0,void 0,void 0,void 0,r)}function V5(e,t,r,n,o,s,i){let a=i(e,t,r,n,o,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return j5(e,t,s,i)}return j5(e,t,s,i)}function j5(e,t,r,n){if(Object.is(e,t))return!0;let o=Sye(e),s=Sye(t);if(o===Iye&&(o=Nz),s===Iye&&(s=Nz),o!==s)return!1;switch(o){case kZe:return e.toString()===t.toString();case UZe:{let c=e.valueOf(),u=t.valueOf();return OZe(c,u)}case DZe:case MZe:case LZe:return Object.is(e.valueOf(),t.valueOf());case BZe:return e.source===t.source&&e.flags===t.flags;case zZe:return e===t}r=r??new Map;let i=r.get(e),a=r.get(t);if(i!=null&&a!=null)return i===t;r.set(e,t),r.set(t,e);try{switch(o){case HZe:{if(e.size!==t.size)return!1;for(let[c,u]of e.entries())if(!t.has(c)||!V5(u,t.get(c),c,e,t,r,n))return!1;return!0}case $Ze:{if(e.size!==t.size)return!1;let c=Array.from(e.values()),u=Array.from(t.values());for(let d=0;dV5(f,h,void 0,e,t,r,n));if(p===-1)return!1;u.splice(p,1)}return!0}case FZe:case WZe:case KZe:case ZZe:case GZe:case YZe:case JZe:case QZe:case XZe:case eGe:case tGe:case rGe:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c{l();Rp=Ht(ks(),1);vk();Rk();gh();DH();Xe=Ht(jd(),1);R1();B1();B1();eP();I8();cw();$c();Hk();kye=Ht(C2(),1),Uye="wc",Dye=2,rP="core",Ru=`${Uye}@2:${rP}:`,cWe={name:rP,logger:"error"},lWe={database:":memory:"},uWe="crypto",uye="client_ed25519_seed",dWe=Xe.ONE_DAY,fWe="keychain",pWe="0.3",hWe="messages",mWe="0.3",gWe=Xe.SIX_HOURS,yWe="publisher",aV="irn",wWe="error",Lye="wss://relay.walletconnect.org",bWe="relayer",Mn={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},xWe="_subscription",vc={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},vWe=.1,Rz="2.23.2",Vr={link_mode:"link_mode",relay:"relay"},tP={inbound:"inbound",outbound:"outbound"},EWe="0.3",AWe="WALLETCONNECT_CLIENT_ID",dye="WALLETCONNECT_LINK_MODE_APPS",Da={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},CWe="subscription",SWe="0.3",Mdr=Xe.FIVE_SECONDS*1e3,IWe="pairing",TWe="0.3",$5={wc_pairingDelete:{req:{ttl:Xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:Xe.ONE_DAY,prompt:!1,tag:0}}},zm={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Al={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},_We="history",PWe="0.3",NWe="expirer",La={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},RWe="0.3",OWe="verify-api",BWe="https://verify.walletconnect.com",Mye="https://verify.walletconnect.org",ax=Mye,kWe=`${ax}/v3`,UWe=[BWe,Mye],DWe="echo",LWe="https://echo.walletconnect.com",Cl={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Nu={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Ac={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Vm={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},jm={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},cx={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},MWe=.1,HWe="event-client",$We=86400,FWe="https://pulse.walletconnect.org/batch";VWe=zWe,jWe=VWe,Hye=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},qWe=e=>new TextEncoder().encode(e),WWe=e=>new TextDecoder().decode(e),Oz=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Bz=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $ye(this,t)}},kz=class{constructor(t){this.decoders=t}or(t){return $ye(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},$ye=(e,t)=>new kz({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),Uz=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Oz(t,r,n),this.decoder=new Bz(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},nP=({name:e,prefix:t,encode:r,decode:n})=>new Uz(e,t,r,n),q5=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=jWe(r,t);return nP({prefix:e,name:t,encode:n,decode:s=>Hye(o(s))})},KWe=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},ZWe=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<nP({prefix:t,name:e,encode(o){return ZWe(o,n,r)},decode(o){return KWe(o,n,r,e)}}),GWe=nP({prefix:"\0",name:"identity",encode:e=>WWe(e),decode:e=>qWe(e)}),YWe=Object.freeze({__proto__:null,identity:GWe}),JWe=Ko({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),QWe=Object.freeze({__proto__:null,base2:JWe}),XWe=Ko({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),eKe=Object.freeze({__proto__:null,base8:XWe}),tKe=q5({prefix:"9",name:"base10",alphabet:"0123456789"}),rKe=Object.freeze({__proto__:null,base10:tKe}),nKe=Ko({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oKe=Ko({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),sKe=Object.freeze({__proto__:null,base16:nKe,base16upper:oKe}),iKe=Ko({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aKe=Ko({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cKe=Ko({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lKe=Ko({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uKe=Ko({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dKe=Ko({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fKe=Ko({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pKe=Ko({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hKe=Ko({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),mKe=Object.freeze({__proto__:null,base32:iKe,base32upper:aKe,base32pad:cKe,base32padupper:lKe,base32hex:uKe,base32hexupper:dKe,base32hexpad:fKe,base32hexpadupper:pKe,base32z:hKe}),gKe=q5({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yKe=q5({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),wKe=Object.freeze({__proto__:null,base36:gKe,base36upper:yKe}),bKe=q5({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xKe=q5({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),vKe=Object.freeze({__proto__:null,base58btc:bKe,base58flickr:xKe}),EKe=Ko({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),AKe=Ko({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CKe=Ko({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),SKe=Ko({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),IKe=Object.freeze({__proto__:null,base64:EKe,base64pad:AKe,base64url:CKe,base64urlpad:SKe}),Fye=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),TKe=Fye.reduce((e,t,r)=>(e[r]=t,e),[]),_Ke=Fye.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);RKe=nP({prefix:"\u{1F680}",name:"base256emoji",encode:PKe,decode:NKe}),OKe=Object.freeze({__proto__:null,base256emoji:RKe}),BKe=zye,fye=128,kKe=127,UKe=~kKe,DKe=Math.pow(2,31);LKe=Dz,MKe=128,pye=127;HKe=Math.pow(2,7),$Ke=Math.pow(2,14),FKe=Math.pow(2,21),zKe=Math.pow(2,28),VKe=Math.pow(2,35),jKe=Math.pow(2,42),qKe=Math.pow(2,49),WKe=Math.pow(2,56),KKe=Math.pow(2,63),ZKe=function(e){return e(Vye.encode(e,t,r),t),mye=e=>Vye.encodingLength(e),Lz=(e,t)=>{let r=t.byteLength,n=mye(e),o=n+mye(r),s=new Uint8Array(o+r);return hye(e,s,0),hye(r,s,n),s.set(t,o),new Mz(e,r,t,s)},Mz=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}},jye=({name:e,code:t,encode:r})=>new Hz(e,t,r),Hz=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?Lz(this.code,r):r.then(n=>Lz(this.code,n))}else throw Error("Unknown type, must be binary type")}},qye=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),YKe=jye({name:"sha2-256",code:18,encode:qye("SHA-256")}),JKe=jye({name:"sha2-512",code:19,encode:qye("SHA-512")}),QKe=Object.freeze({__proto__:null,sha256:YKe,sha512:JKe}),Wye=0,XKe="identity",Kye=Hye,eZe=e=>Lz(Wye,Kye(e)),tZe={code:Wye,name:XKe,encode:Kye,digest:eZe},rZe=Object.freeze({__proto__:null,identity:tZe});new TextEncoder,new TextDecoder;gye={...YWe,...QWe,...eKe,...rKe,...sKe,...mKe,...wKe,...vKe,...IKe,...OKe};({...QKe,...rZe});yye=Gye("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),_z=Gye("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=nZe(e.length);for(let r=0;rt in e?iZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pu=(e,t,r)=>aZe(e,typeof t!="symbol"?t+"":t,r),$z=class{constructor(t,r){this.core=t,this.logger=r,Pu(this,"keychain",new Map),Pu(this,"name",fWe),Pu(this,"version",pWe),Pu(this,"initialized",!1),Pu(this,"storagePrefix",Ru),Pu(this,"init",async()=>{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Pu(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Pu(this,"set",async(n,o)=>{this.isInitialized(),this.keychain.set(n,o),await this.persist()}),Pu(this,"get",n=>{this.isInitialized();let o=this.keychain.get(n);if(typeof o>"u"){let{message:s}=Ie("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return o}),Pu(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=t,this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,$7(t))}async getKeyChain(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?F7(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},cZe=Object.defineProperty,lZe=(e,t,r)=>t in e?cZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,No=(e,t,r)=>lZe(e,typeof t!="symbol"?t+"":t,r),Fz=class{constructor(t,r,n){this.core=t,this.logger=r,No(this,"name",uWe),No(this,"keychain"),No(this,"randomSessionIdentifier",Q7()),No(this,"initialized",!1),No(this,"clientId"),No(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),No(this,"hasKeys",o=>(this.isInitialized(),this.keychain.has(o))),No(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;let o=await this.getClientSeed(),s=J2(o),i=U8(s.publicKey);return this.clientId=i,i}),No(this,"generateKeyPair",()=>{this.isInitialized();let o=Nge();return this.setPrivateKey(o.publicKey,o.privateKey)}),No(this,"signJWT",async o=>{this.isInitialized();let s=await this.getClientSeed(),i=J2(s),a=this.randomSessionIdentifier;return await BC(a,o,dWe,i)}),No(this,"generateSharedKey",(o,s,i)=>{this.isInitialized();let a=this.getPrivateKey(o),c=Rge(a,s);return this.setSymKey(c,i)}),No(this,"setSymKey",async(o,s)=>{this.isInitialized();let i=s||tx(o);return await this.keychain.set(i,o),i}),No(this,"deleteKeyPair",async o=>{this.isInitialized(),await this.keychain.del(o)}),No(this,"deleteSymKey",async o=>{this.isInitialized(),await this.keychain.del(o)}),No(this,"encode",async(o,s,i)=>{this.isInitialized();let a=gz(i),c=yi(s);if(wz(a))return Lge(c,i?.encoding);if(yz(a)){let p=a.senderPublicKey,h=a.receiverPublicKey;o=await this.generateSharedKey(p,h)}let u=this.getSymKey(o),{type:d,senderPublicKey:f}=a;return Uge({type:d,symKey:u,message:c,senderPublicKey:f,encoding:i?.encoding})}),No(this,"decode",async(o,s,i)=>{this.isInitialized();let a=$ge(s,i);if(wz(a)){let c=Mge(s,i?.encoding);return Fs(c)}if(yz(a)){let c=a.receiverPublicKey,u=a.senderPublicKey;o=await this.generateSharedKey(c,u)}try{let c=this.getSymKey(o),u=Dge({symKey:c,encoded:s,encoding:i?.encoding});return Fs(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),No(this,"getPayloadType",(o,s=Ts)=>{let i=rx({encoded:o,encoding:s});return Hm(i.type)}),No(this,"getPayloadSenderPublicKey",(o,s=Ts)=>{let i=rx({encoded:o,encoding:s});return i.senderPublicKey?Ut(i.senderPublicKey,Is):void 0}),this.core=t,this.logger=Cr(r,this.name),this.keychain=n||new $z(this.core,this.logger)}get context(){return sr(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(uye)}catch{t=Q7(),await this.keychain.set(uye,t)}return sZe(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},uZe=Object.defineProperty,dZe=Object.defineProperties,fZe=Object.getOwnPropertyDescriptors,wye=Object.getOwnPropertySymbols,pZe=Object.prototype.hasOwnProperty,hZe=Object.prototype.propertyIsEnumerable,zz=(e,t,r)=>t in e?uZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,mZe=(e,t)=>{for(var r in t||(t={}))pZe.call(t,r)&&zz(e,r,t[r]);if(wye)for(var r of wye(t))hZe.call(t,r)&&zz(e,r,t[r]);return e},gZe=(e,t)=>dZe(e,fZe(t)),Ua=(e,t,r)=>zz(e,typeof t!="symbol"?t+"":t,r),Vz=class extends R_{constructor(t,r){super(t,r),this.logger=t,this.core=r,Ua(this,"messages",new Map),Ua(this,"messagesWithoutClientAck",new Map),Ua(this,"name",hWe),Ua(this,"version",mWe),Ua(this,"initialized",!1),Ua(this,"storagePrefix",Ru),Ua(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);let o=await this.getRelayerMessagesWithoutClientAck();typeof o<"u"&&(this.messagesWithoutClientAck=o),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Ua(this,"set",async(n,o,s)=>{this.isInitialized();let i=Wi(o),a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[i]<"u")return i;if(a[i]=o,this.messages.set(n,a),s===tP.inbound){let c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,gZe(mZe({},c),{[i]:o}))}return await this.persist(),i}),Ua(this,"get",n=>{this.isInitialized();let o=this.messages.get(n);return typeof o>"u"&&(o={}),o}),Ua(this,"getWithoutAck",n=>{this.isInitialized();let o={};for(let s of n){let i=this.messagesWithoutClientAck.get(s)||{};o[s]=Object.values(i)}return o}),Ua(this,"has",(n,o)=>{this.isInitialized();let s=this.get(n),i=Wi(o);return typeof s[i]<"u"}),Ua(this,"ack",async(n,o)=>{this.isInitialized();let s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;let i=Wi(o);delete s[i],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),Ua(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Cr(t,this.name),this.core=r}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,$7(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,$7(t))}async getRelayerMessages(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?F7(t):void 0}async getRelayerMessagesWithoutClientAck(){let t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?F7(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},yZe=Object.defineProperty,wZe=Object.defineProperties,bZe=Object.getOwnPropertyDescriptors,bye=Object.getOwnPropertySymbols,xZe=Object.prototype.hasOwnProperty,vZe=Object.prototype.propertyIsEnumerable,jz=(e,t,r)=>t in e?yZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,sx=(e,t)=>{for(var r in t||(t={}))xZe.call(t,r)&&jz(e,r,t[r]);if(bye)for(var r of bye(t))vZe.call(t,r)&&jz(e,r,t[r]);return e},xye=(e,t)=>wZe(e,bZe(t)),Ec=(e,t,r)=>jz(e,typeof t!="symbol"?t+"":t,r),qz=class extends O_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,Ec(this,"events",new Rp.EventEmitter),Ec(this,"name",yWe),Ec(this,"queue",new Map),Ec(this,"publishTimeout",(0,Xe.toMiliseconds)(Xe.ONE_MINUTE)),Ec(this,"initialPublishTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),Ec(this,"needsTransportRestart",!1),Ec(this,"publish",async(n,o,s)=>{var i,a,c,u,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:o,opts:s}});let f=s?.ttl||gWe,p=s?.prompt||!1,h=s?.tag||0,y=s?.id||_n().toString(),w=Py(L5().protocol),x={id:y,method:s?.publishMethod||w.publish,params:sx({topic:n,message:o,ttl:f,prompt:p,tag:h,attestation:s?.attestation},s?.tvf)},v=`Failed to publish payload, please try again. id:${y} tag:${h}`;try{Ln((i=x.params)==null?void 0:i.prompt)&&((a=x.params)==null||delete a.prompt),Ln((c=x.params)==null?void 0:c.tag)&&((u=x.params)==null||delete u.tag);let T=new Promise(async E=>{let S=({id:O})=>{var D;((D=x.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(Mn.publish,S),E())};this.relayer.events.on(Mn.publish,S);let _=xl(new Promise((O,D)=>{this.rpcPublish(x,s).then(O).catch(M=>{this.logger.warn(M,M?.message),D(M)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${y} tag:${h}`);try{await _,this.events.removeListener(Mn.publish,S)}catch(O){this.queue.set(y,{request:x,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:y,topic:n,message:o,opts:s}}),await xl(T,this.publishTimeout,v)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(d=s?.internal)!=null&&d.throwOnFailedPublish)throw T}finally{this.queue.delete(y)}}),Ec(this,"publishCustom",async n=>{var o,s,i,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});let{payload:u,opts:d={}}=n,{attestation:f,tvf:p,publishMethod:h,prompt:y,tag:w,ttl:x=Xe.FIVE_MINUTES}=d,v=d.id||_n().toString(),T=Py(L5().protocol),E=h||T.publish,S={id:v,method:E,params:sx(xye(sx({},u),{ttl:x,prompt:y,tag:w,attestation:f}),p)},_=`Failed to publish custom payload, please try again. id:${v} tag:${w}`;try{Ln((o=S.params)==null?void 0:o.prompt)&&((s=S.params)==null||delete s.prompt),Ln((i=S.params)==null?void 0:i.tag)&&((a=S.params)==null||delete a.tag);let O=new Promise(async D=>{let M=({id:L})=>{var P;((P=S.id)==null?void 0:P.toString())===L.toString()&&(this.removeRequestFromQueue(L),this.relayer.events.removeListener(Mn.publish,M),D())};this.relayer.events.on(Mn.publish,M);let N=xl(new Promise((L,P)=>{this.rpcPublish(S,d).then(L).catch(R=>{this.logger.warn(R,R?.message),P(R)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${E} id:${v} tag:${w}`);try{await N,this.events.removeListener(Mn.publish,M)}catch(L){this.queue.set(v,{request:S,opts:d,attempt:1}),this.logger.warn(L,L?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:v,payload:u,opts:d}}),await xl(O,this.publishTimeout,_)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=d?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(v)}}),Ec(this,"on",(n,o)=>{this.events.on(n,o)}),Ec(this,"once",(n,o)=>{this.events.once(n,o)}),Ec(this,"off",(n,o)=>{this.events.off(n,o)}),Ec(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.relayer=t,this.logger=Cr(r,this.name),this.registerEventListeners()}get context(){return sr(this.logger)}async rpcPublish(t,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});let n=await this.relayer.request(t);return this.relayer.events.emit(Mn.publish,sx(sx({},t),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,r)=>{var n;let o=t.attempt+1;this.queue.set(r,xye(sx({},t),{attempt:o})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(n=t.request.params)==null?void 0:n.tag}, attempt: ${o}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Mn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Mn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}},EZe=Object.defineProperty,AZe=(e,t,r)=>t in e?EZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ix=(e,t,r)=>AZe(e,typeof t!="symbol"?t+"":t,r),Wz=class{constructor(){ix(this,"map",new Map),ix(this,"set",(t,r)=>{let n=this.get(t);this.exists(t,r)||this.map.set(t,[...n,r])}),ix(this,"get",t=>this.map.get(t)||[]),ix(this,"exists",(t,r)=>this.get(t).includes(r)),ix(this,"delete",(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;let n=this.get(t);if(!this.exists(t,r))return;let o=n.filter(s=>s!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)}),ix(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}},CZe=Object.defineProperty,SZe=Object.defineProperties,IZe=Object.getOwnPropertyDescriptors,vye=Object.getOwnPropertySymbols,TZe=Object.prototype.hasOwnProperty,_Ze=Object.prototype.propertyIsEnumerable,Kz=(e,t,r)=>t in e?CZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,F5=(e,t)=>{for(var r in t||(t={}))TZe.call(t,r)&&Kz(e,r,t[r]);if(vye)for(var r of vye(t))_Ze.call(t,r)&&Kz(e,r,t[r]);return e},Pz=(e,t)=>SZe(e,IZe(t)),Or=(e,t,r)=>Kz(e,typeof t!="symbol"?t+"":t,r),Zz=class extends U_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,Or(this,"subscriptions",new Map),Or(this,"topicMap",new Wz),Or(this,"events",new Rp.EventEmitter),Or(this,"name",CWe),Or(this,"version",SWe),Or(this,"pending",new Map),Or(this,"cached",[]),Or(this,"initialized",!1),Or(this,"storagePrefix",Ru),Or(this,"subscribeTimeout",(0,Xe.toMiliseconds)(Xe.ONE_MINUTE)),Or(this,"initialSubscribeTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),Or(this,"clientId"),Or(this,"batchSubscribeTopicsLimit",500),Or(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Or(this,"subscribe",async(n,o)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}});try{let i=L5(o),a={topic:n,relay:i,transportType:o?.transportType};(s=o?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);let c=await this.rpcSubscribe(n,i,o);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}})),c}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}}),Or(this,"unsubscribe",async(n,o)=>{this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(n,o.id,o):await this.unsubscribeByTopic(n,o)}),Or(this,"isSubscribed",n=>new Promise(o=>{o(this.topicMap.topics.includes(n))})),Or(this,"isKnownTopic",n=>new Promise(o=>{o(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),Or(this,"on",(n,o)=>{this.events.on(n,o)}),Or(this,"once",(n,o)=>{this.events.once(n,o)}),Or(this,"off",(n,o)=>{this.events.off(n,o)}),Or(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),Or(this,"start",async()=>{await this.onConnect()}),Or(this,"stop",async()=>{await this.onDisconnect()}),Or(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Or(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;let n=[];this.pending.forEach(o=>{n.push(o)}),await this.batchSubscribe(n)}),Or(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Vs.pulse,async()=>{await this.checkPending()}),this.events.on(Da.created,async n=>{let o=Da.created;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()}),this.events.on(Da.deleted,async n=>{let o=Da.deleted;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()})}),this.relayer=t,this.logger=Cr(r,this.name),this.clientId=""}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,r){let n=!1;try{n=this.getSubscription(t).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){let n=this.topicMap.get(t);await Promise.all(n.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}});try{let o=L5(n);await this.restartToComplete({topic:t,id:r,relay:o}),await this.rpcUnsubscribe(t,r,o);let s=Rr("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r,n){var o,s;let i=await this.getSubscriptionId(t);if((o=n?.internal)!=null&&o.skipSubscribe)return i;(!n||n?.transportType===Vr.relay)&&await this.restartToComplete({topic:t,id:t,relay:r});let a={method:Py(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});let c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===Vr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},(0,Xe.toMiliseconds)(Xe.ONE_SECOND)),i;let u=new Promise(async f=>{let p=h=>{h.topic===t&&(this.events.removeListener(Da.created,p),f(h.id))};this.events.on(Da.created,p);try{let h=await xl(new Promise((y,w)=>{this.relayer.request(a).catch(x=>{this.logger.warn(x,x?.message),w(x)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(Da.created,p),f(h)}catch{}}),d=await xl(u,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return d?i:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Mn.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(t){if(!t.length)return;let r=t[0].relay,n={method:Py(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await xl(new Promise(o=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(o)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Mn.connection_stalled)}}async rpcBatchFetchMessages(t){if(!t.length)return;let r=t[0].relay,n={method:Py(r.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let o;try{o=await await xl(new Promise((s,i)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),i(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Mn.connection_stalled)}return o}rpcUnsubscribe(t,r,n){let o={method:Py(n.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,Pz(F5({},r),{id:t})),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,F5({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,n),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r)}addSubscription(t,r){this.subscriptions.set(t,F5({},r)),this.topicMap.set(r.topic,t),this.events.emit(Da.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});let r=this.subscriptions.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});let n=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(n.topic,t),this.events.emit(Da.deleted,Pz(F5({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Da.sync)}async onRestart(){if(this.cached.length){let t=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n"u"||!t.length)return;if(this.subscriptions.size&&!t.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){t.length&&(await this.rpcBatchSubscribe(t),this.onBatchSubscribe(await Promise.all(t.map(async r=>Pz(F5({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);let r=await this.rpcBatchFetchMessages(t);r&&r.messages&&(await U1e((0,Xe.toMiliseconds)(Xe.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Wi(t+await this.getClientId())}},PZe=Object.defineProperty,Eye=Object.getOwnPropertySymbols,NZe=Object.prototype.hasOwnProperty,RZe=Object.prototype.propertyIsEnumerable,Gz=(e,t,r)=>t in e?PZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Aye=(e,t)=>{for(var r in t||(t={}))NZe.call(t,r)&&Gz(e,r,t[r]);if(Eye)for(var r of Eye(t))RZe.call(t,r)&&Gz(e,r,t[r]);return e},rr=(e,t,r)=>Gz(e,typeof t!="symbol"?t+"":t,r),Yz=class extends B_{constructor(t){var r;super(t),rr(this,"protocol","wc"),rr(this,"version",2),rr(this,"core"),rr(this,"logger"),rr(this,"events",new Rp.EventEmitter),rr(this,"provider"),rr(this,"messages"),rr(this,"subscriber"),rr(this,"publisher"),rr(this,"name",bWe),rr(this,"transportExplicitlyClosed",!1),rr(this,"initialized",!1),rr(this,"connectionAttemptInProgress",!1),rr(this,"relayUrl"),rr(this,"projectId"),rr(this,"packageName"),rr(this,"bundleId"),rr(this,"hasExperiencedNetworkDisruption",!1),rr(this,"pingTimeout"),rr(this,"heartBeatTimeout",(0,Xe.toMiliseconds)(Xe.THIRTY_SECONDS+Xe.FIVE_SECONDS)),rr(this,"reconnectTimeout"),rr(this,"connectPromise"),rr(this,"reconnectInProgress",!1),rr(this,"requestsInFlight",[]),rr(this,"connectTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),rr(this,"request",async n=>{var o,s;this.logger.debug("Publishing Request Payload");let i=n.id||_n().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:n.method,topic:(o=n.params)==null?void 0:o.topic},"relayer.request - publishing...");let a=`${i}:${((s=n.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);let c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${i}`),a}}),rr(this,"resetPingTimeout",()=>{P5()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,o,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(i=(s=(o=(n=this.provider)==null?void 0:n.connection)==null?void 0:o.socket)==null?void 0:s.terminate)==null||i.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),rr(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),rr(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Mn.connect)}),rr(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),rr(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Mn.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),rr(this,"registerProviderListeners",()=>{this.provider.on(vc.payload,this.onPayloadHandler),this.provider.on(vc.connect,this.onConnectHandler),this.provider.on(vc.disconnect,this.onDisconnectHandler),this.provider.on(vc.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=ox({logger:(r=t.logger)!=null?r:wWe,name:this.name}),this.messages=new Vz(this.logger,t.core),this.subscriber=new Zz(this,this.logger),this.publisher=new qz(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Lye,S1e()?this.packageName=JF():I1e()&&(this.bundleId=JF()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return sr(this.logger)}get connected(){var t,r,n;return((n=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var t,r,n;return((n=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,r,n){this.isInitialized(),await this.publisher.publish(t,r,n),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now(),transportType:Vr.relay},tP.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,r){var n,o,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();let i=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(o=r?.internal)==null?void 0:o.throwOnFailedPublish,a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c,u=d=>{d.topic===t&&(this.subscriber.off(Da.created,u),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Da.created,u)}),new Promise(async(d,f)=>{a=await this.subscriber.subscribe(t,Aye({internal:{throwOnFailedPublish:i}},r)).catch(p=>{i&&f(p)})||a,d()})]),a}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await xl(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(t).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tz())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}let r=t.sort((n,o)=>n.publishedAt-o.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(let n of r)try{await this.onMessageEvent(n)}catch(o){this.logger.warn(o,"Error while processing batch message event: "+o?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(t,r){let{topic:n}=t;if(!r.sessionExists){let o=pn(Xe.FIVE_MINUTES),s={topic:n,expiry:o,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Mn.message,t),await this.recordMessageEvent(t,tP.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to connect"))};this.provider.once(vc.disconnect,s),await xl(new Promise((i,a)=>{this.provider.connect().then(i).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(i=>{o(i)}).finally(()=>{this.provider.off(vc.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(i,a)=>{let c=()=>{o(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(vc.disconnect,c),await this.subscriber.start().then(i).catch(a).finally(()=>{this.provider.off(vc.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();let o=n;this.logger.warn({},o.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,(0,Xe.toMiliseconds)(r*1))),r++}}startPingTimeout(){var t,r,n,o,s;if(P5())try{(r=(t=this.provider)==null?void 0:t.connection)!=null&&r.socket&&((s=(o=(n=this.provider)==null?void 0:n.connection)==null?void 0:o.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(i){this.logger.warn(i,i?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new da(new lw(_1e({sdkVersion:Rz,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,r){let{topic:n,message:o}=t;await this.messages.set(n,o,r)}async shouldIgnoreMessageEvent(t){let{topic:r,message:n}=t;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;let o=this.messages.has(r,n);return o&&this.logger.warn(`Ignoring duplicate message: ${n}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Hc(t)){if(!t.method.endsWith(xWe))return;let r=t.params,{topic:n,message:o,publishedAt:s,attestation:i}=r.data,a={topic:n,message:o,publishedAt:s,transportType:Vr.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Aye({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else ua(t)&&this.events.emit(Mn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,tP.inbound),this.events.emit(Mn.message,t))}async acknowledgePayload(t){let r=bo(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(vc.payload,this.onPayloadHandler),this.provider.off(vc.connect,this.onConnectHandler),this.provider.off(vc.disconnect,this.onDisconnectHandler),this.provider.off(vc.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await Tz();aye(async r=>{t!==r&&(t=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vs.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&cye())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Mn.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,Xe.toMiliseconds)(vWe)))))}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}};BZe="[object RegExp]",kZe="[object String]",UZe="[object Number]",DZe="[object Boolean]",Iye="[object Arguments]",LZe="[object Symbol]",MZe="[object Date]",HZe="[object Map]",$Ze="[object Set]",FZe="[object Array]",zZe="[object Function]",VZe="[object ArrayBuffer]",Nz="[object Object]",jZe="[object Error]",qZe="[object DataView]",WZe="[object Uint8Array]",KZe="[object Uint8ClampedArray]",ZZe="[object Uint16Array]",GZe="[object Uint32Array]",YZe="[object BigUint64Array]",JZe="[object Int8Array]",QZe="[object Int16Array]",XZe="[object Int32Array]",eGe="[object BigInt64Array]",tGe="[object Float32Array]",rGe="[object Float64Array]";iGe=Object.defineProperty,_ye=Object.getOwnPropertySymbols,aGe=Object.prototype.hasOwnProperty,cGe=Object.prototype.propertyIsEnumerable,Jz=(e,t,r)=>t in e?iGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pye=(e,t)=>{for(var r in t||(t={}))aGe.call(t,r)&&Jz(e,r,t[r]);if(_ye)for(var r of _ye(t))cGe.call(t,r)&&Jz(e,r,t[r]);return e},Ki=(e,t,r)=>Jz(e,typeof t!="symbol"?t+"":t,r),Ou=class extends k_{constructor(t,r,n,o=Ru,s=void 0){super(t,r,n,o),this.core=t,this.logger=r,this.name=n,Ki(this,"map",new Map),Ki(this,"version",EWe),Ki(this,"cached",[]),Ki(this,"initialized",!1),Ki(this,"getKey"),Ki(this,"storagePrefix",Ru),Ki(this,"recentlyDeleted",[]),Ki(this,"recentlyDeletedLimit",200),Ki(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>{this.getKey&&i!==null&&!Ln(i)?this.map.set(this.getKey(i),i):Kge(i)?this.map.set(i.id,i):Zge(i)&&this.map.set(i.topic,i)}),this.cached=[],this.initialized=!0)}),Ki(this,"set",async(i,a)=>{this.isInitialized(),this.map.has(i)?await this.update(i,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:i,value:a}),this.map.set(i,a),await this.persist())}),Ki(this,"get",i=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:i}),this.getData(i))),Ki(this,"getAll",i=>(this.isInitialized(),i?this.values.filter(a=>Object.keys(i).every(c=>sGe(a[c],i[c]))):this.values)),Ki(this,"update",async(i,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:i,update:a});let c=Pye(Pye({},this.getData(i)),a);this.map.set(i,c),await this.persist()}),Ki(this,"delete",async(i,a)=>{this.isInitialized(),this.map.has(i)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:i,reason:a}),this.map.delete(i),this.addToRecentlyDeleted(i),await this.persist())}),this.logger=Cr(r,this.name),this.storagePrefix=o,this.getKey=s}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){let r=this.map.get(t);if(!r){if(this.recentlyDeleted.includes(t)){let{message:o}=Ie("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(o),new Error(o)}let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},lGe=Object.defineProperty,uGe=(e,t,r)=>t in e?lGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vt=(e,t,r)=>uGe(e,typeof t!="symbol"?t+"":t,r),Qz=class{constructor(t,r){this.core=t,this.logger=r,Vt(this,"name",IWe),Vt(this,"version",TWe),Vt(this,"events",new Rp.default),Vt(this,"pairings"),Vt(this,"initialized",!1),Vt(this,"storagePrefix",Ru),Vt(this,"ignoredPayloadTypes",[vl]),Vt(this,"registeredMethods",[]),Vt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Vt(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Vt(this,"create",async n=>{this.isInitialized();let o=Q7(),s=await this.core.crypto.setSymKey(o),i=pn(Xe.FIVE_MINUTES),a={protocol:aV},c={topic:s,expiry:i,relay:a,active:!1,methods:n?.methods},u=xz({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:o,relay:a,expiryTimestamp:i,methods:n?.methods});return this.events.emit(zm.create,c),this.core.expirer.set(s,i),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}}),Vt(this,"pair",async n=>{this.isInitialized();let o=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Cl.pairing_started]}});this.isValidPair(n,o);let{topic:s,symKey:i,relay:a,expiryTimestamp:c,methods:u}=bz(n.uri);o.props.properties.topic=s,o.addTrace(Cl.pairing_uri_validation_success),o.addTrace(Cl.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(s)){if(d=this.pairings.get(s),o.addTrace(Cl.existing_pairing),d.active)throw o.setError(Nu.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);o.addTrace(Cl.pairing_not_expired)}let f=c||pn(Xe.FIVE_MINUTES),p={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,p),o.addTrace(Cl.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(zm.create,p),o.addTrace(Cl.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),o.addTrace(Cl.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{o.setError(Nu.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw o.setError(Nu.subscribe_pairing_topic_failure),h}return o.addTrace(Cl.subscribe_pairing_topic_success),p}),Vt(this,"activate",async({topic:n})=>{this.isInitialized();let o=pn(Xe.FIVE_MINUTES);this.core.expirer.set(n,o),await this.pairings.update(n,{active:!0,expiry:o})}),Vt(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:o}=n;if(this.pairings.keys.includes(o)){let s=await this.sendRequest(o,"wc_pairingPing",{}),{done:i,resolve:a,reject:c}=Pp();this.events.once(cr("pairing_ping",s),({error:u})=>{u?c(u):a()}),await i()}}),Vt(this,"updateExpiry",async({topic:n,expiry:o})=>{this.isInitialized(),await this.pairings.update(n,{expiry:o})}),Vt(this,"updateMetadata",async({topic:n,metadata:o})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:o})}),Vt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Vt(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:o}=n;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",Rr("USER_DISCONNECTED")),await this.deletePairing(o))}),Vt(this,"formatUriFromPairing",n=>{this.isInitialized();let{topic:o,relay:s,expiry:i,methods:a}=n,c=this.core.crypto.keychain.get(o);return xz({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:c,relay:s,expiryTimestamp:i,methods:a})}),Vt(this,"sendRequest",async(n,o,s)=>{let i=dr(o,s),a=await this.core.crypto.encode(n,i),c=$5[o].req;return this.core.history.set(n,i),this.core.relayer.publish(n,a,c),i.id}),Vt(this,"sendResult",async(n,o,s)=>{let i=bo(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=$5[c].res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)}),Vt(this,"sendError",async(n,o,s)=>{let i=la(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=$5[c]?$5[c].res:$5.unregistered_method.res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)}),Vt(this,"deletePairing",async(n,o)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Rr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),o?Promise.resolve():this.core.expirer.del(n)])}),Vt(this,"cleanup",async()=>{let n=this.pairings.getAll().filter(o=>ka(o.expiry));await Promise.all(n.map(o=>this.deletePairing(o.topic)))}),Vt(this,"onRelayEventRequest",async n=>{let{topic:o,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(o,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(o,s);default:return await this.onUnknownRpcMethodRequest(o,s)}}),Vt(this,"onRelayEventResponse",async n=>{let{topic:o,payload:s}=n,i=(await this.core.history.get(o,s.id)).request.method;return i==="wc_pairingPing"?this.onPairingPingResponse(o,s):this.onUnknownRpcMethodResponse(i)}),Vt(this,"onPairingPingRequest",async(n,o)=>{let{id:s}=o;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(zm.ping,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}}),Vt(this,"onPairingPingResponse",(n,o)=>{let{id:s}=o;setTimeout(()=>{Jr(o)?this.events.emit(cr("pairing_ping",s),{}):Ir(o)&&this.events.emit(cr("pairing_ping",s),{error:o.error})},500)}),Vt(this,"onPairingDeleteRequest",async(n,o)=>{let{id:s}=o;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(zm.delete,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}}),Vt(this,"onUnknownRpcMethodRequest",async(n,o)=>{let{id:s,method:i}=o;try{if(this.registeredMethods.includes(i))return;let a=Rr("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Vt(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Rr("WC_METHOD_UNSUPPORTED",n))}),Vt(this,"isValidPair",(n,o)=>{var s;if(!_s(n)){let{message:a}=Ie("MISSING_OR_INVALID",`pair() params: ${n}`);throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(!Wge(n.uri)){let{message:a}=Ie("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw o.setError(Nu.malformed_pairing_uri),new Error(a)}let i=bz(n?.uri);if(!((s=i?.relay)!=null&&s.protocol)){let{message:a}=Ie("MISSING_OR_INVALID","pair() uri#relay-protocol");throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(!(i!=null&&i.symKey)){let{message:a}=Ie("MISSING_OR_INVALID","pair() uri#symKey");throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(i!=null&&i.expiryTimestamp&&(0,Xe.toMiliseconds)(i?.expiryTimestamp){if(!_s(n)){let{message:s}=Ie("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)}),Vt(this,"isValidDisconnect",async n=>{if(!_s(n)){let{message:s}=Ie("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)}),Vt(this,"isValidPairingTopic",async n=>{if(!An(n,!1)){let{message:o}=Ie("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(o)}if(!this.pairings.keys.includes(n)){let{message:o}=Ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(o)}if(ka(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:o}=Ie("EXPIRED",`pairing topic: ${n}`);throw new Error(o)}}),this.core=t,this.logger=Cr(r,this.name),this.pairings=new Ou(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sr(this.logger)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(Mn.message,async t=>{let{topic:r,message:n,transportType:o}=t;if(this.pairings.keys.includes(r)&&o!==Vr.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{let s=await this.core.crypto.decode(r,n);Hc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ua(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(La.expired,async t=>{let{topic:r}=z7(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(zm.expire,{topic:r}))})}},dGe=Object.defineProperty,fGe=(e,t,r)=>t in e?dGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Wo=(e,t,r)=>fGe(e,typeof t!="symbol"?t+"":t,r),Xz=class extends N_{constructor(t,r){super(t,r),this.core=t,this.logger=r,Wo(this,"records",new Map),Wo(this,"events",new Rp.EventEmitter),Wo(this,"name",_We),Wo(this,"version",PWe),Wo(this,"cached",[]),Wo(this,"initialized",!1),Wo(this,"storagePrefix",Ru),Wo(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Wo(this,"set",(n,o,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:o,chainId:s}),this.records.has(o.id))return;let i={id:o.id,topic:n,request:{method:o.method,params:o.params||null},chainId:s,expiry:pn(Xe.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Al.created,i)}),Wo(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let o=await this.getRecord(n.id);typeof o.response>"u"&&(o.response=Ir(n)?{error:n.error}:{result:n.result},this.records.set(o.id,o),this.persist(),this.events.emit(Al.updated,o))}),Wo(this,"get",async(n,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:o}),await this.getRecord(o))),Wo(this,"delete",(n,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(s=>{if(s.topic===n){if(typeof o<"u"&&s.id!==o)return;this.records.delete(s.id),this.events.emit(Al.deleted,s)}}),this.persist()}),Wo(this,"exists",async(n,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===n:!1)),Wo(this,"on",(n,o)=>{this.events.on(n,o)}),Wo(this,"once",(n,o)=>{this.events.once(n,o)}),Wo(this,"off",(n,o)=>{this.events.off(n,o)}),Wo(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(n)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();let r=this.records.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Al.sync)}async restore(){try{let t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(Al.created,t=>{let r=Al.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Al.updated,t=>{let r=Al.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Al.deleted,t=>{let r=Al.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.core.heartbeat.on(Vs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(r=>{(0,Xe.toMiliseconds)(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Al.deleted,r,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},pGe=Object.defineProperty,hGe=(e,t,r)=>t in e?pGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ps=(e,t,r)=>hGe(e,typeof t!="symbol"?t+"":t,r),eV=class extends D_{constructor(t,r){super(t,r),this.core=t,this.logger=r,Ps(this,"expirations",new Map),Ps(this,"events",new Rp.EventEmitter),Ps(this,"name",NWe),Ps(this,"version",RWe),Ps(this,"cached",[]),Ps(this,"initialized",!1),Ps(this,"storagePrefix",Ru),Ps(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ps(this,"has",n=>{try{let o=this.formatTarget(n);return typeof this.getExpiration(o)<"u"}catch{return!1}}),Ps(this,"set",(n,o)=>{this.isInitialized();let s=this.formatTarget(n),i={target:s,expiry:o};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(La.created,{target:s,expiration:i})}),Ps(this,"get",n=>{this.isInitialized();let o=this.formatTarget(n);return this.getExpiration(o)}),Ps(this,"del",n=>{if(this.isInitialized(),this.has(n)){let o=this.formatTarget(n),s=this.getExpiration(o);this.expirations.delete(o),this.events.emit(La.deleted,{target:o,expiration:s})}}),Ps(this,"on",(n,o)=>{this.events.on(n,o)}),Ps(this,"once",(n,o)=>{this.events.once(n,o)}),Ps(this,"off",(n,o)=>{this.events.off(n,o)}),Ps(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(t){if(typeof t=="string")return N1e(t);if(typeof t=="number")return R1e(t);let{message:r}=Ie("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(La.sync)}async restore(){try{let t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){let r=this.expirations.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(t,r){let{expiry:n}=r;(0,Xe.toMiliseconds)(n)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(La.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Vs.pulse,()=>this.checkExpirations()),this.events.on(La.created,t=>{let r=La.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(La.expired,t=>{let r=La.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(La.deleted,t=>{let r=La.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},mGe=Object.defineProperty,gGe=(e,t,r)=>t in e?mGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Kn=(e,t,r)=>gGe(e,typeof t!="symbol"?t+"":t,r),tV=class extends L_{constructor(t,r,n){super(t,r,n),this.core=t,this.logger=r,this.store=n,Kn(this,"name",OWe),Kn(this,"abortController"),Kn(this,"isDevEnv"),Kn(this,"verifyUrlV3",kWe),Kn(this,"storagePrefix",Ru),Kn(this,"version",Dye),Kn(this,"publicKey"),Kn(this,"fetchPromise"),Kn(this,"init",async()=>{var o;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,Xe.toMiliseconds)((o=this.publicKey)==null?void 0:o.expiresAt){if(!Ty()||this.isDevEnv)return;let s=window.location.origin,{id:i,decryptedId:a}=o,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${i}&decryptedId=${a}`;try{let u=(0,kye.getDocument)(),d=this.startAbortTimer(Xe.ONE_SECOND*5),f=await new Promise((p,h)=>{let y=()=>{window.removeEventListener("message",x),u.body.removeChild(w),h("attestation aborted")};this.abortController.signal.addEventListener("abort",y);let w=u.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});let x=v=>{if(v.data&&typeof v.data=="string")try{let T=JSON.parse(v.data);if(T.type==="verify_attestation"){if(Hl(T.attestation).payload.id!==i)return;clearInterval(d),u.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",x),p(T.attestation===null?"":T.attestation)}}catch(T){this.logger.warn(T)}};u.body.appendChild(w),window.addEventListener("message",x,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Kn(this,"resolve",async o=>{if(this.isDevEnv)return"";let{attestationId:s,hash:i,encryptedId:a}=o;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Hl(s).payload.id!==a)return;let u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!i)return;let c=this.getVerifyUrl(o?.verifyUrl);return this.fetchAttestation(i,c)}),Kn(this,"fetchAttestation",async(o,s)=>{this.logger.debug(`resolving attestation: ${o} from url: ${s}`);let i=this.startAbortTimer(Xe.ONE_SECOND*5),a=await fetch(`${s}/attestation/${o}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),a.status===200?await a.json():void 0}),Kn(this,"getVerifyUrl",o=>{let s=o||ax;return UWe.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${ax}`),s=ax),s}),Kn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let o=this.startAbortTimer(Xe.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(o),await s.json()}catch(o){this.logger.warn(o)}}),Kn(this,"persistPublicKey",async o=>{this.logger.debug(o,"persisting public key to local storage"),await this.store.setItem(this.storeKey,o),this.publicKey=o}),Kn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Kn(this,"isValidJwtAttestation",async o=>{let s=await this.getPublicKey();try{if(s)return this.validateAttestation(o,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(o,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Kn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Kn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{let i=await this.fetchPublicKey();i&&(await this.persistPublicKey(i),s(i))});let o=await this.fetchPromise;return this.fetchPromise=void 0,o}),Kn(this,"validateAttestation",(o,s)=>{let i=Fge(o,s.publicKey),a={hasExpired:(0,Xe.toMiliseconds)(i.exp)this.abortController.abort(),(0,Xe.toMiliseconds)(t))}},yGe=Object.defineProperty,wGe=(e,t,r)=>t in e?yGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Nye=(e,t,r)=>wGe(e,typeof t!="symbol"?t+"":t,r),rV=class extends M_{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,Nye(this,"context",DWe),Nye(this,"registerDeviceToken",async n=>{let{clientId:o,token:s,notificationType:i,enableEncrypted:a=!1}=n,c=`${LWe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:i,token:s,always_raw:a})})}),this.logger=Cr(r,this.context)}},bGe=Object.defineProperty,Rye=Object.getOwnPropertySymbols,xGe=Object.prototype.hasOwnProperty,vGe=Object.prototype.propertyIsEnumerable,nV=(e,t,r)=>t in e?bGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,z5=(e,t)=>{for(var r in t||(t={}))xGe.call(t,r)&&nV(e,r,t[r]);if(Rye)for(var r of Rye(t))vGe.call(t,r)&&nV(e,r,t[r]);return e},Ro=(e,t,r)=>nV(e,typeof t!="symbol"?t+"":t,r),oV=class extends H_{constructor(t,r,n=!0){super(t,r,n),this.core=t,this.logger=r,Ro(this,"context",HWe),Ro(this,"storagePrefix",Ru),Ro(this,"storageVersion",MWe),Ro(this,"events",new Map),Ro(this,"shouldPersist",!1),Ro(this,"init",async()=>{if(!R5())try{let o={eventId:tz(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:XF(this.core.relayer.protocol,this.core.relayer.version,Rz)}}};await this.sendEvent([o])}catch(o){this.logger.warn(o)}}),Ro(this,"createEvent",o=>{let{event:s="ERROR",type:i="",properties:{topic:a,trace:c}}=o,u=tz(),d=this.core.projectId||"",f=Date.now(),p=z5({eventId:u,timestamp:f,props:{event:s,type:i,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,p),this.shouldPersist=!0),p}),Ro(this,"getEvent",o=>{let{eventId:s,topic:i}=o;if(s)return this.events.get(s);let a=Array.from(this.events.values()).find(c=>c.props.properties.topic===i);if(a)return z5(z5({},a),this.setMethods(a.eventId))}),Ro(this,"deleteEvent",o=>{let{eventId:s}=o;this.events.delete(s),this.shouldPersist=!0}),Ro(this,"setEventListeners",()=>{this.core.heartbeat.on(Vs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(o=>{(0,Xe.fromMiliseconds)(Date.now())-(0,Xe.fromMiliseconds)(o.timestamp)>$We&&(this.events.delete(o.eventId),this.shouldPersist=!0)})})}),Ro(this,"setMethods",o=>({addTrace:s=>this.addTrace(o,s),setError:s=>this.setError(o,s)})),Ro(this,"addTrace",(o,s)=>{let i=this.events.get(o);i&&(i.props.properties.trace.push(s),this.events.set(o,i),this.shouldPersist=!0)}),Ro(this,"setError",(o,s)=>{let i=this.events.get(o);i&&(i.props.type=s,i.timestamp=Date.now(),this.events.set(o,i),this.shouldPersist=!0)}),Ro(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ro(this,"restore",async()=>{try{let o=await this.core.storage.getItem(this.storageKey)||[];if(!o.length)return;o.forEach(s=>{this.events.set(s.eventId,z5(z5({},s),this.setMethods(s.eventId)))})}catch(o){this.logger.warn(o)}}),Ro(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;let o=[];for(let[s,i]of this.events)i.props.type&&o.push(i);if(o.length!==0)try{if((await this.sendEvent(o)).ok)for(let s of o)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Ro(this,"sendEvent",async o=>{let s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${FWe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Rz}${s}`,{method:"POST",body:JSON.stringify(o)})}),Ro(this,"getAppDomain",()=>QF().url),this.logger=Cr(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},EGe=Object.defineProperty,Oye=Object.getOwnPropertySymbols,AGe=Object.prototype.hasOwnProperty,CGe=Object.prototype.propertyIsEnumerable,sV=(e,t,r)=>t in e?EGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Bye=(e,t)=>{for(var r in t||(t={}))AGe.call(t,r)&&sV(e,r,t[r]);if(Oye)for(var r of Oye(t))CGe.call(t,r)&&sV(e,r,t[r]);return e},zr=(e,t,r)=>sV(e,typeof t!="symbol"?t+"":t,r),iV=class e extends P_{constructor(t){var r;super(t),zr(this,"protocol",Uye),zr(this,"version",Dye),zr(this,"name",rP),zr(this,"relayUrl"),zr(this,"projectId"),zr(this,"customStoragePrefix"),zr(this,"events",new Rp.EventEmitter),zr(this,"logger"),zr(this,"heartbeat"),zr(this,"relayer"),zr(this,"crypto"),zr(this,"storage"),zr(this,"history"),zr(this,"expirer"),zr(this,"pairing"),zr(this,"verify"),zr(this,"echoClient"),zr(this,"linkModeSupportedApps"),zr(this,"eventClient"),zr(this,"initialized",!1),zr(this,"logChunkController"),zr(this,"on",(a,c)=>this.events.on(a,c)),zr(this,"once",(a,c)=>this.events.once(a,c)),zr(this,"off",(a,c)=>this.events.off(a,c)),zr(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),zr(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;let d={topic:a,message:c,publishedAt:Date.now(),transportType:Vr.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:u})});let n=this.getGlobalCore(t?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Lye,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";let o=X2({level:typeof t?.logger=="string"&&t.logger?t.logger:cWe.logger,name:rP}),{logger:s,chunkLoggerController:i}=Fl({opts:o,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=i,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Cr(s,this.name),this.heartbeat=new iw,this.crypto=new Fz(this,this.logger,t?.keychain),this.history=new Xz(this,this.logger),this.expirer=new eV(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new aw(Bye(Bye({},lWe),t?.storageOptions)),this.relayer=new Yz({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Qz(this,this.logger),this.verify=new tV(this,this.logger,this.storage),this.echoClient=new rV(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new oV(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){let r=new e(t);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(AWe,n),r}get context(){return sr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(dye,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(dye)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(t){var r;try{if(this.isGlobalCoreDisabled())return;let n=`_walletConnectCore_${((r=t.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=t}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},Yye=iV});var sP,Nt,t2e,r2e,n2e,vV,cV,Qye,SGe,Xye,IGe,lx,TGe,Zo,lV,Bu,_Ge,PGe,NGe,RGe,OGe,BGe,kGe,UGe,iP,oP,DGe,LGe,MGe,e2e,HGe,$Ge,dV,lr,Go,Ee,fV,pV,hV,mV,gV,yV,wV,FGe,zGe,uV,bV,VGe,jGe,jt,xV,o2e,s2e=b(()=>{l();sP=Ht(ks(),1);Jye();DH();eP();gh();Nt=Ht(jd(),1);$c();t2e="wc",r2e=2,n2e="client",vV=`${t2e}@${r2e}:${n2e}:`,cV={name:n2e,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Qye="WALLETCONNECT_DEEPLINK_CHOICE",SGe="proposal",Xye="Proposal expired",IGe="session",lx=Nt.SEVEN_DAYS,TGe="engine",Zo={wc_sessionPropose:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Nt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Nt.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1119}}},lV={min:Nt.FIVE_MINUTES,max:Nt.SEVEN_DAYS},Bu={idle:"IDLE",active:"ACTIVE"},_Ge={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},PGe="request",NGe=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],RGe="wc",OGe="auth",BGe="authKeys",kGe="pairingTopics",UGe="requests",iP=`${RGe}@${1.5}:${OGe}:`,oP=`${iP}:PUB_KEY`,DGe=Object.defineProperty,LGe=Object.defineProperties,MGe=Object.getOwnPropertyDescriptors,e2e=Object.getOwnPropertySymbols,HGe=Object.prototype.hasOwnProperty,$Ge=Object.prototype.propertyIsEnumerable,dV=(e,t,r)=>t in e?DGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,lr=(e,t)=>{for(var r in t||(t={}))HGe.call(t,r)&&dV(e,r,t[r]);if(e2e)for(var r of e2e(t))$Ge.call(t,r)&&dV(e,r,t[r]);return e},Go=(e,t)=>LGe(e,MGe(t)),Ee=(e,t,r)=>dV(e,typeof t!="symbol"?t+"":t,r),fV=class extends F_{constructor(t){super(t),Ee(this,"name",TGe),Ee(this,"events",new sP.default),Ee(this,"initialized",!1),Ee(this,"requestQueue",{state:Bu.idle,queue:[]}),Ee(this,"sessionRequestQueue",{state:Bu.idle,queue:[]}),Ee(this,"emittedSessionRequests",new O7({limit:500})),Ee(this,"requestQueueDelay",Nt.ONE_SECOND),Ee(this,"expectedPairingMethodMap",new Map),Ee(this,"recentlyDeletedMap",new Map),Ee(this,"recentlyDeletedLimit",200),Ee(this,"relayMessageCache",[]),Ee(this,"pendingSessions",new Map),Ee(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Zo)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,Nt.toMiliseconds)(this.requestQueueDelay)))}),Ee(this,"connect",async r=>{var n;this.isInitialized(),await this.confirmOnlineStateOrThrow();let o=Go(lr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(o),o.optionalNamespaces=jge(o.requiredNamespaces,o.optionalNamespaces),o.requiredNamespaces={};let{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:d,authentication:f,walletPay:p}=o,h=((n=f?.[0])==null?void 0:n.ttl)||Zo.wc_sessionPropose.req.ttl||Nt.FIVE_MINUTES;this.validateRequestExpiry(h);let y=s,w,x=!1;try{if(y){let N=this.client.core.pairing.pairings.get(y);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),x=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${y}) failed`),N}if(!y||!x){let{topic:N,uri:L}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});y=N,w=L}if(!y){let{message:N}=Ie("NO_MATCHING_KEY",`connect() pairing topic: ${y}`);throw new Error(N)}let v=await this.client.core.crypto.generateKeyPair(),T=pn(h),E=lr(Go(lr(lr({requiredNamespaces:i,optionalNamespaces:a,relays:d??[{protocol:aV}],proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:T,pairingTopic:y},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Tn()}),(f||p)&&{requests:{authentication:f?.map(N=>{let{domain:L,chains:P,nonce:R,uri:I,exp:B,nbf:C,type:A,statement:U,requestId:H,resources:k,signatureTypes:F}=N;return{domain:L,chains:P,nonce:R,type:A??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:B,nbf:C,statement:U,requestId:H,resources:k,signatureTypes:F}}),walletPay:p}}),S=cr("session_connect",E.id),{reject:_,resolve:O,done:D}=Pp(h,Xye),M=({id:N})=>{N===E.id&&(this.client.events.off("proposal_expire",M),this.pendingSessions.delete(E.id),this.events.emit(S,{error:{message:Xye,code:0}}))};return this.client.events.on("proposal_expire",M),this.events.once(S,({error:N,session:L})=>{this.client.events.off("proposal_expire",M),N?_(N):L&&O(L)}),await this.setProposal(E.id,E),await this.sendProposeSession({proposal:E,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:E.id}}}).catch(N=>{throw this.deleteProposal(E.id),N}),{uri:w,approval:D}}),Ee(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),Ee(this,"approve",async r=>{var n,o,s;let i=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[Ac.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(L){throw i.setError(Vm.no_internet_connection),L}try{await this.isValidProposalId(r?.id)}catch(L){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),i.setError(Vm.proposal_not_found),L}try{await this.isValidApprove(r)}catch(L){throw this.client.logger.error("approve() -> isValidApprove() failed"),i.setError(Vm.session_approve_namespace_validation_failure),L}let{id:a,relayProtocol:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=r,y=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:i.eventId});let{pairingTopic:w,proposer:x,requiredNamespaces:v,optionalNamespaces:T}=y,E=(o=this.client.core.eventClient)==null?void 0:o.getEvent({topic:w});E||(E=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ac.session_approve_started,properties:{topic:w,trace:[Ac.session_approve_started,Ac.session_namespaces_validation_success]}}));let S=await this.client.core.crypto.generateKeyPair(),_=x.publicKey,O=await this.client.core.crypto.generateSharedKey(S,_),D=Go(lr(lr(lr({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:S,metadata:this.client.metadata},expiry:pn(lx)},d&&{sessionProperties:d}),f&&{scopedProperties:f}),p&&{sessionConfig:p}),{proposalRequestsResponses:h}),M=Vr.relay;E.addTrace(Ac.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:M,internal:{skipSubscribe:!0}})}catch(L){throw E.setError(Vm.subscribe_session_topic_failure),L}E.addTrace(Ac.subscribe_session_topic_success);let N=Go(lr({},D),{topic:O,requiredNamespaces:v,optionalNamespaces:T,pairingTopic:w,acknowledged:!1,self:D.controller,peer:{publicKey:x.publicKey,metadata:x.metadata},controller:S,transportType:Vr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(O,N),E.addTrace(Ac.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:y,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:S},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:lr({correlationId:a},this.getTVFApproveParams(N))}}),E.addTrace(Ac.session_approve_publish_success)}catch(L){throw this.client.logger.error(L),this.client.session.delete(O,Rr("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),L}return this.client.core.eventClient.deleteEvent({eventId:E.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:x.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(O,pn(lx)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),Ee(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(i){throw this.client.logger.error("reject() -> isValidReject() failed"),i}let{id:n,reason:o}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(i){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),i}s&&await this.sendError({id:n,topic:s,error:o,rpcOpts:Zo.wc_sessionPropose.reject}),await this.deleteProposal(n)}),Ee(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}let{topic:n,namespaces:o}=r,{done:s,resolve:i,reject:a}=Pp(Nt.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tn(),u=_n().toString(),d=this.client.session.get(n).namespaces;return this.events.once(cr("session_update",c),({error:f})=>{f?a(f):i()}),await this.client.session.update(n,{namespaces:o}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:o},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:d}),a(f)}),{acknowledged:s}}),Ee(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}let{topic:n}=r,o=Tn(),{done:s,resolve:i,reject:a}=Pp(Nt.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(cr("session_extend",o),({error:c})=>{c?a(c):i()}),await this.setExpiry(n,pn(lx)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:o,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),Ee(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}let{chainId:n,request:o,topic:s,expiry:i=Zo.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let c=Tn(),u=_n().toString(),{done:d,resolve:f,reject:p}=Pp(i,"Request expired. Please try again.");this.events.once(cr("session_request",c),({error:x,result:v})=>{x?p(x):f(v)});let h="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:Go(lr({},o),{expiryTimestamp:pn(i)}),chainId:n},expiry:i,throwOnFailedPublish:!0,appLink:y}).catch(x=>p(x)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),await d();let w={request:Go(lr({},o),{expiryTimestamp:pn(i)}),chainId:n};return await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:w,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),x()}),new Promise(async x=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){let T=await B1e(this.client.core.storage,Qye);await O1e({id:c,topic:s,wcDeepLink:T})}x()}),d()]).then(x=>x[2])}),Ee(this,"respond",async r=>{var n,o;this.isInitialized();let s=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||((o=(n=r?.response)==null?void 0:n.id)==null?void 0:o.toString()),trace:[Ac.session_request_response_started]}});try{await this.isValidRespond(r)}catch(f){throw s.addTrace(f?.message),s.setError(Vm.session_request_response_validation_failure),f}s.addTrace(Ac.session_request_response_validation_success);let{topic:i,response:a}=r,{id:c}=a,u=this.client.session.get(i);u.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let d=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(Ac.session_request_response_publish_started),Jr(a)?await this.sendResult({id:c,topic:i,result:a.result,throwOnFailedPublish:!0,appLink:d}):Ir(a)&&await this.sendError({id:c,topic:i,error:a.error,appLink:d}),this.cleanupAfterResponse(r)}catch(f){throw s.addTrace(f?.message),s.setError(Vm.session_request_response_publish_failure),f}}),Ee(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(o){throw this.client.logger.error("ping() -> isValidPing() failed"),o}let{topic:n}=r;if(this.client.session.keys.includes(n)){let o=Tn(),s=_n().toString(),{done:i,resolve:a,reject:c}=Pp(Nt.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(cr("session_ping",o),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),Ee(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);let{topic:n,event:o,chainId:s}=r,i=_n().toString(),a=Tn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:o,chainId:s},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:a})}),Ee(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Rr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:o}=Ie("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(o)}}),Ee(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>qge(n,r)))),Ee(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),Ee(this,"authenticate",async(r,n)=>{var o;this.isInitialized(),this.isValidAuthenticate(r);let s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((o=this.client.metadata.redirect)==null?void 0:o.linkMode),i=s?Vr.link_mode:Vr.relay;i===Vr.relay&&await this.confirmOnlineStateOrThrow();let{chains:a,statement:c="",uri:u,domain:d,nonce:f,type:p,exp:h,nbf:y,methods:w=[],expiry:x}=r,v=[...r.resources||[]],{topic:T,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:i});this.client.logger.info({message:"Generated new pairing",pairing:{topic:T,uri:E}});let S=await this.client.core.crypto.generateKeyPair(),_=tx(S);if(await Promise.all([this.client.auth.authKeys.set(oP,{responseTopic:_,publicKey:S}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:T})]),await this.client.core.relayer.subscribe(_,{transportType:i}),this.client.logger.info(`sending request to new pairing topic: ${T}`),w.length>0){let{namespace:k}=bl(a[0]),F=ege(k,"request",w);k5(v)&&(F=tge(F,v.pop())),v.push(F)}let O=x&&x>Zo.wc_sessionAuthenticate.req.ttl?x:Zo.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:p??"caip122",chains:a,statement:c,aud:u,domain:d,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:y,resources:v},requester:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:pn(O)},M={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},N={requiredNamespaces:{},optionalNamespaces:M,relays:[{protocol:"irn"}],pairingTopic:T,proposer:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:pn(Zo.wc_sessionPropose.req.ttl),id:Tn()},{done:L,resolve:P,reject:R}=Pp(O,"Request expired"),I=Tn(),B=cr("session_connect",N.id),C=cr("session_request",I),A=async({error:k,session:F})=>{this.events.off(C,U),k?R(k):F&&P({session:F})},U=async k=>{var F,j,W;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),k.error){let ye=Rr("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return k.error.code===ye.code?void 0:(this.events.off(B,A),R(k.error.message))}await this.deleteProposal(N.id),this.events.off(B,A);let{cacaos:ae,responder:te}=k.result,X=[],pe=[];for(let ye of ae){await az({cacao:ye,projectId:this.client.core.projectId})||(this.client.logger.error(ye,"Signature verification failed"),R(Rr("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:Re}=ye,Et=k5(Re.resources),kt=[K7(Re.iss)],At=B5(Re.iss);if(Et){let ur=lz(Et),_r=uz(Et);X.push(...ur),kt.push(..._r)}for(let ur of kt)pe.push(`${ur}:${At}`)}let me=await this.client.core.crypto.generateSharedKey(S,te.publicKey),Ne;X.length>0&&(Ne={topic:me,acknowledged:!0,self:{publicKey:S,metadata:this.client.metadata},peer:te,controller:te.publicKey,expiry:pn(lx),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:T,namespaces:Ez([...new Set(X)],[...new Set(pe)]),transportType:i},await this.client.core.relayer.subscribe(me,{transportType:i}),await this.client.session.set(me,Ne),T&&await this.client.core.pairing.updateMetadata({topic:T,metadata:te.metadata}),Ne=this.client.session.get(me)),(F=this.client.metadata.redirect)!=null&&F.linkMode&&(j=te.metadata.redirect)!=null&&j.linkMode&&(W=te.metadata.redirect)!=null&&W.universal&&n&&(this.client.core.addLinkModeSupportedApp(te.metadata.redirect.universal),this.client.session.update(me,{transportType:Vr.link_mode})),P({auths:ae,session:Ne})};this.events.once(B,A),this.events.once(C,U);let H;try{if(s){let k=dr("wc_sessionAuthenticate",D,I);this.client.core.history.set(T,k);let F=await this.client.core.crypto.encode("",k,{type:ex,encoding:Np});H=M5(n,T,F)}else await Promise.all([this.sendRequest({topic:T,method:"wc_sessionAuthenticate",params:D,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:T,method:"wc_sessionPropose",params:N,expiry:Zo.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(k){throw this.events.off(B,A),this.events.off(C,U),k}return await this.setProposal(N.id,N),await this.setAuthRequest(I,{request:Go(lr({},D),{verifyContext:{}}),pairingTopic:T,transportType:i}),{uri:H??E,response:L}}),Ee(this,"approveSessionAuthenticate",async r=>{let{id:n,auths:o}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[jm.authenticated_session_approve_started]}});try{this.isInitialized()}catch(x){throw s.setError(cx.no_internet_connection),x}let i=this.getPendingAuthRequest(n);if(!i)throw s.setError(cx.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);let a=i.transportType||Vr.relay;a===Vr.relay&&await this.confirmOnlineStateOrThrow();let c=i.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=tx(c),f={type:vl,receiverPublicKey:c,senderPublicKey:u},p=[],h=[];for(let x of o){if(!await az({cacao:x,projectId:this.client.core.projectId})){s.setError(cx.invalid_cacao);let _=Rr("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:_,encodeOpts:f}),new Error(_.message)}s.addTrace(jm.cacaos_verified);let{p:v}=x,T=k5(v.resources),E=[K7(v.iss)],S=B5(v.iss);if(T){let _=lz(T),O=uz(T);p.push(..._),E.push(...O)}for(let _ of E)h.push(`${_}:${S}`)}let y=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(jm.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:i.requester.metadata},controller:c,expiry:pn(lx),authentication:o,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:Ez([...new Set(p)],[...new Set(h)]),transportType:a},s.addTrace(jm.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(x){throw s.setError(cx.subscribe_authenticated_session_topic_failure),x}s.addTrace(jm.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),s.addTrace(jm.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}s.addTrace(jm.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:o,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,a)})}catch(x){throw s.setError(cx.authenticated_session_approve_publish_failure),x}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}}),Ee(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();let{id:n,reason:o}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let i=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tx(i),u={type:vl,receiverPublicKey:i,senderPublicKey:a};await this.sendError({id:n,topic:c,error:o,encodeOpts:u,rpcOpts:Zo.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),Ee(this,"formatAuthMessage",r=>{this.isInitialized();let{request:n,iss:o}=r;return cz(n,o)}),Ee(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{let r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),Ee(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(s=>{var i,a;return((i=s.peerMetadata)==null?void 0:i.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),Ee(this,"deleteSession",async r=>{var n;let{topic:o,expirerHasDeleted:s=!1,emitEvent:i=!0,id:a=0}=r,{self:c}=this.client.session.get(o);await this.client.core.relayer.unsubscribe(o),await this.client.session.delete(o,Rr("USER_DISCONNECTED")),this.addToRecentlyDeleted(o,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(o)&&await this.client.core.crypto.deleteSymKey(o),s||this.client.core.expirer.del(o),this.client.core.storage.removeItem(Qye).catch(u=>this.client.logger.warn(u)),o===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Bu.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===o).map(u=>this.deletePendingSessionRequest(u.id,Rr("USER_DISCONNECTED")))),i&&this.client.events.emit("session_delete",{id:a,topic:o})}),Ee(this,"deleteProposal",async(r,n)=>{if(n)try{let o=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:o.pairingTopic})?.setError(Vm.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Rr("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),Ee(this,"deletePendingSessionRequest",async(r,n,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),o&&(this.sessionRequestQueue.state=Bu.idle,this.client.events.emit("session_request_expire",{id:r}))}),Ee(this,"deletePendingAuthRequest",async(r,n,o=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)])}),Ee(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),Ee(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,pn(Zo.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),Ee(this,"setAuthRequest",async(r,n)=>{let{request:o,pairingTopic:s,transportType:i=Vr.relay}=n;this.client.core.expirer.set(r,o.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:o.authPayload,requester:o.requester,expiryTimestamp:o.expiryTimestamp,id:r,pairingTopic:s,verifyContext:o.verifyContext,transportType:i})}),Ee(this,"setPendingSessionRequest",async r=>{let{id:n,topic:o,params:s,verifyContext:i}=r,a=s.request.expiryTimestamp||pn(Zo.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:o,params:s,verifyContext:i})}),Ee(this,"sendRequest",async r=>{let{topic:n,method:o,params:s,expiry:i,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:d,tvf:f,publishOpts:p={}}=r,h=dr(o,s,c),y,w=!!d;try{let T=w?Np:Ts;y=await this.client.core.crypto.encode(n,h,{encoding:T})}catch(T){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),T}let x;if(NGe.includes(o)){let T=Wi(JSON.stringify(h)),E=Wi(y);x=await this.client.core.verify.register({id:E,decryptedId:T})}let v=lr(lr({},Zo[o].req),p);if(v.attestation=x,i&&(v.ttl=i),a&&(v.id=a),this.client.core.history.set(n,h),w){let T=M5(d,n,y);await global.Linking.openURL(T,this.client.name)}else v.tvf=Go(lr({},f),{correlationId:h.id}),u?(v.internal=Go(lr({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,y,v)):this.client.core.relayer.publish(n,y,v).catch(T=>this.client.logger.error(T));return h.id}),Ee(this,"sendProposeSession",async r=>{let{proposal:n,publishOpts:o}=r,s=dr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);let i=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:Ts}),a=Wi(JSON.stringify(s)),c=Wi(i),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:i},opts:Go(lr({},o),{publishMethod:"wc_proposeSession",attestation:u})})}),Ee(this,"sendApproveSession",async r=>{let{sessionTopic:n,pairingProposalResponse:o,proposal:s,sessionSettleRequest:i,publishOpts:a}=r,c=bo(s.id,o),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Ts}),d=dr("wc_sessionSettle",i,a?.id),f=await this.client.core.crypto.encode(n,d,{encoding:Ts});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:Go(lr({},a),{publishMethod:"wc_approveSession"})})}),Ee(this,"sendResult",async r=>{let{id:n,topic:o,result:s,throwOnFailedPublish:i,encodeOpts:a,appLink:c}=r,u=bo(n,s),d,f=c&&typeof(global==null?void 0:global.Linking)<"u";try{let y=f?Np:Ts;d=await this.client.core.crypto.encode(o,u,Go(lr({},a||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${o} failed`),y}let p,h;try{p=await this.client.core.history.get(o,n);let y=p.request;try{h=this.getTVFParams(n,y.params,s)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${o}, ${n}) failed`),y}if(f){let y=M5(c,o,d);await global.Linking.openURL(y,this.client.name)}else{let y=p.request.method,w=Zo[y].res;w.tvf=Go(lr({},h),{correlationId:n}),i?(w.internal=Go(lr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(o,d,w)):this.client.core.relayer.publish(o,d,w).catch(x=>this.client.logger.error(x))}await this.client.core.history.resolve(u)}),Ee(this,"sendError",async r=>{let{id:n,topic:o,error:s,encodeOpts:i,rpcOpts:a,appLink:c}=r,u=la(n,s),d,f=c&&typeof(global==null?void 0:global.Linking)<"u";try{let h=f?Np:Ts;d=await this.client.core.crypto.encode(o,u,Go(lr({},i||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${o} failed`),h}let p;try{p=await this.client.core.history.get(o,n)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${o}, ${n}) failed`),h}if(f){let h=M5(c,o,d);await global.Linking.openURL(h,this.client.name)}else{let h=p.request.method,y=a||Zo[h].res;this.client.core.relayer.publish(o,d,y)}await this.client.core.history.resolve(u)}),Ee(this,"cleanup",async()=>{let r=[],n=[];this.client.session.getAll().forEach(o=>{let s=!1;ka(o.expiry)&&(s=!0),this.client.core.crypto.keychain.has(o.topic)||(s=!0),s&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{ka(o.expiryTimestamp)&&n.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession({topic:o})),...n.map(o=>this.deleteProposal(o))])}),Ee(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),Ee(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),Ee(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Bu.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Bu.active;let r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Bu.idle}),Ee(this,"processRequest",async r=>{let{topic:n,payload:o,attestation:s,transportType:i,encryptedId:a}=r,c=o.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:o,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,o);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,o);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,o);case"wc_sessionPing":return await this.onSessionPingRequest(n,o);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,o);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(n,o);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),Ee(this,"onRelayEventResponse",async r=>{let{topic:n,payload:o,transportType:s}=r,i=(await this.client.core.history.get(n,o.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(n,o,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,o);case"wc_sessionExtend":return this.onSessionExtendResponse(n,o);case"wc_sessionPing":return this.onSessionPingResponse(n,o);case"wc_sessionRequest":return this.onSessionRequestResponse(n,o);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,o);default:return this.client.logger.info(`Unsupported response method ${i}`)}}),Ee(this,"onRelayEventUnknownPayload",r=>{let{topic:n}=r,{message:o}=Ie("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)}),Ee(this,"shouldIgnorePairingRequest",r=>{let{topic:n,requestMethod:o}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(o)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),Ee(this,"onSessionProposeRequest",async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i}=r,{params:a,id:c}=o;try{let u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Nu.proposal_listener_not_found)),this.isValidConnect(lr({},o.params));let d=a.expiryTimestamp||pn(Zo.wc_sessionPropose.req.ttl),f=lr({id:c,pairingTopic:n,expiryTimestamp:d,attestation:s,encryptedId:i},a);await this.setProposal(c,f);let p=await this.getVerifyContext({attestationId:s,hash:Wi(JSON.stringify(o)),encryptedId:i,metadata:f.proposer.metadata});u?.addTrace(Cl.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:p})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Zo.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),Ee(this,"onSessionProposeResponse",async(r,n,o)=>{let{id:s}=n;if(Jr(n)){let{result:i}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});let a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});let c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});let u=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let d=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:d,pairingTopic:r,proposalId:s,publicKey:c});let f=await this.client.core.relayer.subscribe(d,{transportType:o});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(Ir(n)){await this.deleteProposal(s);let i=cr("session_connect",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners, 954`);this.events.emit(i,{error:n.error})}}),Ee(this,"onSessionSettleRequest",async(r,n)=>{let{id:o,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:i,controller:a,expiry:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=n.params,y=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!y)return this.client.logger.error(`Pending session not found for topic ${r}`);let w=this.client.proposal.get(y.proposalId),x=Go(lr(lr(lr({topic:r,relay:i,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),f&&{scopedProperties:f}),p&&{sessionConfig:p}),{transportType:Vr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(x.topic,x),await this.setExpiry(x.topic,x.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:x.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(x),await this.sendResult({id:n.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:x}),this.events.emit(cr("session_connect",y.proposalId),{session:x})}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"onSessionSettleResponse",async(r,n)=>{let{id:o}=n;Jr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(cr("session_approve",o),{})):Ir(n)&&(await this.client.session.delete(r,Rr("USER_DISCONNECTED")),this.events.emit(cr("session_approve",o),{error:n.error}))}),Ee(this,"onSessionUpdateRequest",async(r,n)=>{let{params:o,id:s}=n;try{let i=`${r}_session_update`,a=$m.get(i);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Rr("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(lr({topic:r},o));try{$m.set(i,s),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw $m.delete(i),c}this.client.events.emit("session_update",{id:s,topic:r,params:o})}catch(i){await this.sendError({id:s,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3){let{id:o}=n,s=cr("session_update",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_update",o),{}):Ir(n)&&this.events.emit(cr("session_update",o),{error:n.error})}),Ee(this,"onSessionExtendRequest",async(r,n)=>{let{id:o}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,pn(lx)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}}),Ee(this,"onSessionExtendResponse",(r,n)=>{let{id:o}=n,s=cr("session_extend",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_extend",o),{}):Ir(n)&&this.events.emit(cr("session_extend",o),{error:n.error})}),Ee(this,"onSessionPingRequest",async(r,n)=>{let{id:o}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}}),Ee(this,"onSessionPingResponse",(r,n)=>{let{id:o}=n,s=cr("session_ping",o);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Jr(n)?this.events.emit(cr("session_ping",o),{}):Ir(n)&&this.events.emit(cr("session_ping",o),{error:n.error})},500)}),Ee(this,"onSessionDeleteRequest",async(r,n)=>{let{id:o}=n;try{await this.isValidDisconnect({topic:r,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Rr("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:o})}catch(s){this.client.logger.error(s)}}),Ee(this,"onSessionRequest",async r=>{var n,o,s;let{topic:i,payload:a,attestation:c,encryptedId:u,transportType:d}=r,{id:f,params:p}=a;try{await this.isValidRequest(lr({topic:i},p));let h=this.client.session.get(i),y=await this.getVerifyContext({attestationId:c,hash:Wi(JSON.stringify(dr("wc_sessionRequest",p,f))),encryptedId:u,metadata:h.peer.metadata,transportType:d}),w={id:f,topic:i,params:p,verifyContext:y};await this.setPendingSessionRequest(w),d===Vr.link_mode&&(n=h.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((o=h.peer.metadata.redirect)==null?void 0:o.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:i,error:h}),this.client.logger.error(h)}}),Ee(this,"onSessionRequestResponse",(r,n)=>{let{id:o}=n,s=cr("session_request",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(cr("session_request",o),{error:n.error})}),Ee(this,"onSessionEventRequest",async(r,n)=>{let{id:o,params:s}=n;try{let i=`${r}_session_event_${s.event.name}`,a=$m.get(i);if(a&&this.isRequestOutOfSync(a,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit(lr({topic:r},s)),this.client.events.emit("session_event",{id:o,topic:r,params:s}),$m.set(i,o)}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"onSessionAuthenticateResponse",(r,n)=>{let{id:o}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Jr(n)?this.events.emit(cr("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(cr("session_request",o),{error:n.error})}),Ee(this,"onSessionAuthenticateRequest",async r=>{var n;let{topic:o,payload:s,attestation:i,encryptedId:a,transportType:c}=r;try{let{requester:u,authPayload:d,expiryTimestamp:f}=s.params,p=await this.getVerifyContext({attestationId:i,hash:Wi(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:o,id:s.id,authPayload:d,verifyContext:p,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:o,transportType:c}),c===Vr.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:o,params:s.params,id:s.id,verifyContext:p})}catch(u){this.client.logger.error(u);let d=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:vl,receiverPublicKey:d,senderPublicKey:f};await this.sendError({id:s.id,topic:o,error:u,encodeOpts:h,rpcOpts:Zo.wc_sessionAuthenticate.autoReject,appLink:p})}}),Ee(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),Ee(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bu.idle,this.processSessionRequestQueue()},(0,Nt.toMiliseconds)(this.requestQueueDelay))}),Ee(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{let o=this.client.core.history.pending;o.length>0&&o.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(cr("session_request",s.request.id),{error:n})})}),Ee(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Bu.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),Ee(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Bu.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),Ee(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:dr("wc_sessionPropose",Go(lr({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),Ee(this,"isValidConnect",async r=>{if(!_s(r)){let{message:u}=Ie("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:s,sessionProperties:i,scopedProperties:a,relays:c}=r;if(Ln(n)||await this.isValidPairingTopic(n),!Qge(c,!0)){let{message:u}=Ie("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(o&&!Ln(o)&&xc(o)!==0){let u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(o,"requiredNamespaces")}if(s&&!Ln(s)&&xc(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),i&&!Ln(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!Ln(a)){this.validateSessionProps(a,"scopedProperties");let u=Object.keys(o||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(d=>u.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),Ee(this,"validateNamespaces",(r,n)=>{let o=Jge(r,"connect()",n);if(o)throw new Error(o.message)}),Ee(this,"isValidApprove",async r=>{if(!_s(r))throw new Error(Ie("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:o,relayProtocol:s,sessionProperties:i,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let c=this.client.proposal.get(n),u=X7(o,"approve()");if(u)throw new Error(u.message);let d=Iz(c.requiredNamespaces,o,"approve()");if(d)throw new Error(d.message);if(!An(s,!0)){let{message:f}=Ie("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(i&&!Ln(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!Ln(a)){this.validateSessionProps(a,"scopedProperties");let f=new Set(Object.keys(o));if(!Object.keys(a).every(p=>f.has(p.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),Ee(this,"isValidReject",async r=>{if(!_s(r)){let{message:s}=Ie("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:o}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!eye(o)){let{message:s}=Ie("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(s)}}),Ee(this,"isValidSessionSettleRequest",r=>{if(!_s(r)){let{message:u}=Ie("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}let{relay:n,controller:o,namespaces:s,expiry:i}=r;if(!Cz(n)){let{message:u}=Ie("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}let a=Gge(o,"onSessionSettleRequest()");if(a)throw new Error(a.message);let c=X7(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ka(i)){let{message:u}=Ie("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),Ee(this,"isValidUpdate",async r=>{if(!_s(r)){let{message:c}=Ie("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}let{topic:n,namespaces:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),i=X7(o,"update()");if(i)throw new Error(i.message);let a=Iz(s.requiredNamespaces,o,"update()");if(a)throw new Error(a.message)}),Ee(this,"isValidExtend",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),Ee(this,"isValidRequest",async r=>{if(!_s(r)){let{message:c}=Ie("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}let{topic:n,request:o,chainId:s,expiry:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!Sz(a,s)){let{message:c}=Ie("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!tye(o)){let{message:c}=Ie("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(c)}if(!oye(a,s,o.method)){let{message:c}=Ie("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(c)}this.validateRequestExpiry(i)}),Ee(this,"isValidRespond",async r=>{var n;if(!_s(r)){let{message:a}=Ie("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}let{topic:o,response:s}=r;try{await this.isValidSessionTopic(o)}catch(a){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),a}if(!rye(s)){let{message:a}=Ie("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}let i=this.client.pendingRequest.get(s.id);if(i.topic!==o){let{message:a}=Ie("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${i.topic}, received topic: ${o}`);throw new Error(a)}}),Ee(this,"isValidPing",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),Ee(this,"isValidEmit",async r=>{if(!_s(r)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:o,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:i}=this.client.session.get(n);if(!Sz(i,s)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!nye(o)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}if(!sye(i,s,o.name)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}}),Ee(this,"isValidDisconnect",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),Ee(this,"isValidAuthenticate",r=>{let{chains:n,uri:o,domain:s,nonce:i}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!An(o,!1))throw new Error("uri is required parameter");if(!An(s,!1))throw new Error("domain is required parameter");if(!An(i,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>bl(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:a}=bl(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),Ee(this,"getVerifyContext",async r=>{let{attestationId:n,hash:o,encryptedId:s,metadata:i,transportType:a}=r,c={verified:{verifyUrl:i.verifyUrl||ax,validation:"UNKNOWN",origin:i.url||""}};try{if(a===Vr.link_mode){let d=this.getAppLinkIfEnabled(i,a);return c.verified.validation=d&&new URL(d).origin===new URL(i.url).origin?"VALID":"INVALID",c}let u=await this.client.core.verify.resolve({attestationId:n,hash:o,encryptedId:s,verifyUrl:i.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),Ee(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((o,s)=>{if(o==null){let{message:i}=Ie("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${o} for key ${Object.keys(r)[s]}`);throw new Error(i)}})}),Ee(this,"getPendingAuthRequest",r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),Ee(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let o=0,s=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(o++>=s)break;this.recentlyDeletedMap.delete(i)}}}),Ee(this,"checkRecentlyDeleted",r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:o}=Ie("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(o)}}),Ee(this,"isLinkModeEnabled",(r,n)=>{var o,s,i,a,c,u,d,f,p;return!r||n!==Vr.link_mode?!1:((s=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:s.linkMode)===!0&&((a=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((d=r?.redirect)==null?void 0:d.universal)!==void 0&&((f=r?.redirect)==null?void 0:f.universal)!==""&&((p=r?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),Ee(this,"getAppLinkIfEnabled",(r,n)=>{var o;return this.isLinkModeEnabled(r,n)?(o=r?.redirect)==null?void 0:o.universal:void 0}),Ee(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;let n=ez(r,"topic")||"",o=decodeURIComponent(ez(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:Vr.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:o,sessionExists:s})}),Ee(this,"registerLinkModeListeners",async()=>{var r;if(R5()||_p()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){let n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);let o=await n.getInitialURL();o&&setTimeout(()=>{this.handleLinkModeMessage({url:o})},50)}}}),Ee(this,"getTVFApproveParams",r=>{try{let n=vz(r.namespaces),o=zge(r.namespaces),s=Vge(r.namespaces),i=r.sessionProperties,a=r.scopedProperties;return{approvedChains:n,approvedMethods:o,approvedEvents:s,sessionProperties:i,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}}),Ee(this,"getTVFParams",(r,n,o)=>{var s,i,a;if(!((s=n.request)!=null&&s.method))return{};let c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{let u=this.extractTxHashesFromResult(n.request,o);c.txHashes=u,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(i=n.request.params)==null?void 0:i[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),Ee(this,"isValidContractData",r=>{var n;if(!r)return!1;try{let o=r?.data||((n=r?.[0])==null?void 0:n.data);if(!o.startsWith("0x"))return!1;let s=o.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),Ee(this,"extractTxHashesFromResult",(r,n)=>{var o;try{if(!n)return[];let s=r.method,i=_Ge[s];if(s==="sui_signTransaction")return[G1e(n.transactionBytes)];if(s==="near_signTransaction")return[sz(n)];if(s==="near_signTransactions")return n.map(c=>sz(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(o=n.tx_json)==null?void 0:o.hash];if(s==="polkadot_signTransaction")return[lye({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return El(n)?n.map(c=>iz(c)):[iz(n)];if(s==="cosmos_signDirect")return[Y1e(n)];if(s==="wallet_sendCalls")return J1e(n);if(typeof n=="string")return[n];let a=n[i.key];if(El(a))return s==="solana_signAllTransactions"?a.map(c=>Z1e(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{let t=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(t);for(let[n,o]of Object.entries(r))for(let s of o)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){let{topic:r,message:n,attestation:o,transportType:s}=t,{publicKey:i}=this.client.auth.authKeys.keys.includes(oP)?this.client.auth.authKeys.get(oP):{responseTopic:void 0,publicKey:void 0};try{let a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i,encoding:s===Vr.link_mode?Np:Ts});Hc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:o,transportType:s,encryptedId:Wi(n)})):ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(La.expired,async t=>{let{topic:r,id:n}=z7(t.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Ie("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Ie("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(zm.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(zm.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!An(t,!1)){let{message:r}=Ie("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.core.pairing.pairings.get(t).expiry)){let{message:r}=Ie("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!An(t,!1)){let{message:r}=Ie("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});let{message:r}=Ie("EXPIRED",`session topic: ${t}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(t)){let{message:r}=Ie("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(An(t,!1)){let{message:r}=Ie("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{let{message:r}=Ie("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!Xge(t)){let{message:r}=Ie("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);let{message:r}=Ie("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}validateRequestExpiry(t){if(t&&!iye(t,lV)){let{message:r}=Ie("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${lV.min} and ${lV.max}`);throw new Error(r)}}},pV=class extends Ou{constructor(t,r){super(t,r,SGe,vV),this.core=t,this.logger=r}},hV=class extends Ou{constructor(t,r){super(t,r,IGe,vV),this.core=t,this.logger=r}},mV=class extends Ou{constructor(t,r){super(t,r,PGe,vV,n=>n.id),this.core=t,this.logger=r}},gV=class extends Ou{constructor(t,r){super(t,r,BGe,iP,()=>oP),this.core=t,this.logger=r}},yV=class extends Ou{constructor(t,r){super(t,r,kGe,iP),this.core=t,this.logger=r}},wV=class extends Ou{constructor(t,r){super(t,r,UGe,iP,n=>n.id),this.core=t,this.logger=r}},FGe=Object.defineProperty,zGe=(e,t,r)=>t in e?FGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,uV=(e,t,r)=>zGe(e,typeof t!="symbol"?t+"":t,r),bV=class{constructor(t,r){this.core=t,this.logger=r,uV(this,"authKeys"),uV(this,"pairingTopics"),uV(this,"requests"),this.authKeys=new gV(this.core,this.logger),this.pairingTopics=new yV(this.core,this.logger),this.requests=new wV(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},VGe=Object.defineProperty,jGe=(e,t,r)=>t in e?VGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,jt=(e,t,r)=>jGe(e,typeof t!="symbol"?t+"":t,r),xV=class e extends $_{constructor(t){super(t),jt(this,"protocol",t2e),jt(this,"version",r2e),jt(this,"name",cV.name),jt(this,"metadata"),jt(this,"core"),jt(this,"logger"),jt(this,"events",new sP.EventEmitter),jt(this,"engine"),jt(this,"session"),jt(this,"proposal"),jt(this,"pendingRequest"),jt(this,"auth"),jt(this,"signConfig"),jt(this,"on",(n,o)=>this.events.on(n,o)),jt(this,"once",(n,o)=>this.events.once(n,o)),jt(this,"off",(n,o)=>this.events.off(n,o)),jt(this,"removeListener",(n,o)=>this.events.removeListener(n,o)),jt(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),jt(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"update",async n=>{try{return await this.engine.update(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"request",async n=>{try{return await this.engine.request(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"find",n=>{try{return this.engine.find(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),jt(this,"authenticate",async(n,o)=>{try{return await this.engine.authenticate(n,o)}catch(s){throw this.logger.error(s.message),s}}),jt(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}}),this.name=t?.name||cV.name,this.metadata=T1e(t?.metadata),this.signConfig=t?.signConfig;let r=ox({logger:t?.logger||cV.logger,name:this.name});this.logger=r,this.core=t?.core||new Yye(t),this.session=new hV(this.core,this.logger),this.proposal=new pV(this.core,this.logger),this.pendingRequest=new mV(this.core,this.logger),this.engine=new fV(this),this.auth=new bV(this.core,this.logger)}static async init(t){let r=new e(t);return await r.initialize(),r}get context(){return sr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}},o2e=xV});function kV(e){return e==null||typeof e!="object"&&typeof e!="function"}function I2e(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function T2e(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}function UV(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lYe(e,t){return dx(e,void 0,e,new Map,t)}function dx(e,t,r,n=new Map,o=void 0){let s=o?.(e,t,r,n);if(s!=null)return s;if(kV(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){let i=new Array(e.length);n.set(e,i);for(let a=0;a{let i=t?.(r,n,o,s);if(i!=null)return i;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case P2e:case _2e:case N2e:{let a=new e.constructor(e?.valueOf());return Oy(a,e),a}case R2e:{let a={};return Oy(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}})}function i2e(e){return dYe(e)}function a2e(e){return e!==null&&typeof e=="object"&&T2e(e)==="[object Arguments]"}function c2e(e){return typeof e=="object"&&e!==null}function fYe(){}function pYe(e){return UV(e)}function hYe(e){if(typeof e!="object"||e==null)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!=="[object Object]"){let r=e[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable?!1:e.toString()===`[object ${r}]`}let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function mYe(e){if(kV(e))return e;if(Array.isArray(e)||UV(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e),r=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new r(e);if(e instanceof RegExp){let n=new r(e);return n.lastIndex=e.lastIndex,n}if(e instanceof DataView)return new r(e.buffer.slice(0));if(e instanceof Error){let n=new r(e.message);return n.stack=e.stack,n.name=e.name,n.cause=e.cause,n}if(typeof File<"u"&&e instanceof File)return new r([e],e.name,{type:e.type,lastModified:e.lastModified});if(typeof e=="object"){let n=Object.create(t);return Object.assign(n,e)}return e}function gYe(e,...t){let r=t.slice(0,-1),n=t[t.length-1],o=e;for(let s=0;s`${t.split(":")[0]}:${t.split(":")[1]}`)}function PYe(e,t){let r=Object.keys(t.namespaces).filter(o=>o.includes(e));if(!r.length)return[];let n=[];return r.forEach(o=>{let s=t.namespaces[o].accounts;n.push(...s)}),n}function f2e(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>{var n,o;return((n=r?.chains)==null?void 0:n.length)&&((o=r?.chains)==null?void 0:o.length)>0}))}function lP(e={},t={}){let r=f2e(p2e(e)),n=f2e(p2e(t));return yYe(r,n)}function p2e(e){var t,r,n,o,s;let i={};if(!xc(e))return i;for(let[a,c]of Object.entries(e)){let u=H5(a)?[a]:c.chains,d=c.methods||[],f=c.events||[],p=c.rpcMap||{},h=Ny(a);i[h]=TYe(cP(cP({},i[h]),c),{chains:ml(u,(t=i[h])==null?void 0:t.chains),methods:ml(d,(r=i[h])==null?void 0:r.methods),events:ml(f,(n=i[h])==null?void 0:n.events)}),(xc(p)||xc(((o=i[h])==null?void 0:o.rpcMap)||{}))&&(i[h].rpcMap=cP(cP({},p),(s=i[h])==null?void 0:s.rpcMap))}return i}function h2e(e){return e.includes(":")?e.split(":")[2]:e}function m2e(e){let t={};for(let[r,n]of Object.entries(e)){let o=n.methods||[],s=n.events||[],i=n.accounts||[],a=H5(r)?[r]:n.chains?n.chains:D2e(n.accounts);t[r]={chains:a,methods:o,events:s,accounts:i}}return t}function EV(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function NYe(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}async function ZYe(e,t){let r=bl(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,o=await Promise.allSettled(n.map(f=>GYe(r.reference,f,t))),s=o.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);o.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));let i=!s.length||s.some(f=>!f),a=s.every(f=>f?.status==="0x1"),c=s.every(f=>f?.status==="0x0"),u=s.some(f=>f?.status==="0x0"),d;return i?d=100:a?d=200:c?d=500:u&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function GYe(e,t,r){return await r(parseInt(e)).request(dr("eth_getTransactionReceipt",[t]))}async function YYe({sendCalls:e,storage:t}){let r=await t.getItem(fx);await t.setItem(fx,KYe(WYe({},r),{[e.result.id]:{request:e.request,result:e.result,expiry:pn(vYe)}}))}async function JYe({resultId:e,storage:t}){let r=await t.getItem(fx);if(r){delete r[e],await t.setItem(fx,r);for(let n in r)ka(r[n].expiry)&&delete r[n];await t.setItem(fx,r)}}async function QYe({resultId:e,storage:t}){let r=await t.getItem(fx),n=r?.[e];if(n&&!ka(n.expiry))return n;await JYe({resultId:e,storage:t})}var S2e,qGe,_2e,P2e,N2e,R2e,WGe,KGe,ZGe,GGe,YGe,JGe,QGe,XGe,eYe,tYe,rYe,nYe,oYe,sYe,iYe,aYe,cYe,l2e,wYe,bYe,O2e,aP,B2e,k2e,xYe,fx,vYe,DV,EYe,AYe,CYe,u2e,SYe,IYe,d2e,cP,TYe,L2e,px,AV,RYe,g2e,OYe,BYe,y2e,w2e,b2e,kYe,UYe,CV,x2e,DYe,LYe,MYe,HYe,$Ye,SV,PV,FYe,zYe,VYe,v2e,jYe,qYe,E2e,WYe,KYe,XYe,eJe,tJe,A2e,rJe,nJe,NV,IV,TV,Ry,RV,oJe,sJe,ux,OV,iJe,aJe,cJe,C2e,lJe,uJe,BV,W5,uP,Ma,dP,M2e=b(()=>{l();s2e();eP();$c();cw();rI();S2e=Ht(ks(),1);qGe="[object RegExp]",_2e="[object String]",P2e="[object Number]",N2e="[object Boolean]",R2e="[object Arguments]",WGe="[object Symbol]",KGe="[object Date]",ZGe="[object Map]",GGe="[object Set]",YGe="[object Array]",JGe="[object ArrayBuffer]",QGe="[object Object]",XGe="[object DataView]",eYe="[object Uint8Array]",tYe="[object Uint8ClampedArray]",rYe="[object Uint16Array]",nYe="[object Uint32Array]",oYe="[object Int8Array]",sYe="[object Int16Array]",iYe="[object Int32Array]",aYe="[object Float32Array]",cYe="[object Float64Array]";l2e="error",wYe="wss://relay.walletconnect.org",bYe="wc",O2e="universal_provider",aP=`${bYe}@2:${O2e}:`,B2e="https://rpc.walletconnect.org/v1/",k2e="generic",xYe=`${B2e}bundler`,fx="call_status",vYe=86400,DV={DEFAULT_CHAIN_CHANGED:"default_chain_changed"},EYe=Object.defineProperty,AYe=Object.defineProperties,CYe=Object.getOwnPropertyDescriptors,u2e=Object.getOwnPropertySymbols,SYe=Object.prototype.hasOwnProperty,IYe=Object.prototype.propertyIsEnumerable,d2e=(e,t,r)=>t in e?EYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,cP=(e,t)=>{for(var r in t||(t={}))SYe.call(t,r)&&d2e(e,r,t[r]);if(u2e)for(var r of u2e(t))IYe.call(t,r)&&d2e(e,r,t[r]);return e},TYe=(e,t)=>AYe(e,CYe(t));L2e={},px=e=>L2e[e],AV=(e,t)=>{L2e[e]=t},RYe=Object.defineProperty,g2e=Object.getOwnPropertySymbols,OYe=Object.prototype.hasOwnProperty,BYe=Object.prototype.propertyIsEnumerable,y2e=(e,t,r)=>t in e?RYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,w2e=(e,t)=>{for(var r in t||(t={}))OYe.call(t,r)&&y2e(e,r,t[r]);if(g2e)for(var r of g2e(t))BYe.call(t,r)&&y2e(e,r,t[r]);return e},b2e="eip155",kYe=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],UYe=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,CV=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,x2e=e=>Object.keys(e).filter(t=>kYe.includes(t)).reduce((t,r)=>(t[r]=DYe(e[r]),t),{}),DYe=e=>typeof e=="string"&&NYe(e)?JSON.parse(e):e,LYe=(e,t,r)=>{let{sessionProperties:n={},scopedProperties:o={}}=e,s={};if(!xc(o)&&!xc(n))return;let i=x2e(n);for(let a of r){let c=UYe(a);if(!c)continue;s[CV(c)]=i;let u=o?.[`${b2e}:${c}`];if(u){let d=u?.[`${b2e}:${c}:${t}`];s[CV(c)]=w2e(w2e({},s[CV(c)]),x2e(d||u))}}for(let[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0},MYe=Object.defineProperty,HYe=(e,t,r)=>t in e?MYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$Ye=(e,t,r)=>HYe(e,typeof t!="symbol"?t+"":t,r),PV=class e{constructor(t){$Ye(this,"storage"),this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,r){return await this.storage.setItem(t,r)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return SV||(SV=new e(t)),SV}},FYe=Object.defineProperty,zYe=Object.defineProperties,VYe=Object.getOwnPropertyDescriptors,v2e=Object.getOwnPropertySymbols,jYe=Object.prototype.hasOwnProperty,qYe=Object.prototype.propertyIsEnumerable,E2e=(e,t,r)=>t in e?FYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,WYe=(e,t)=>{for(var r in t||(t={}))jYe.call(t,r)&&E2e(e,r,t[r]);if(v2e)for(var r of v2e(t))qYe.call(t,r)&&E2e(e,r,t[r]);return e},KYe=(e,t)=>zYe(e,VYe(t));XYe=Object.defineProperty,eJe=Object.defineProperties,tJe=Object.getOwnPropertyDescriptors,A2e=Object.getOwnPropertySymbols,rJe=Object.prototype.hasOwnProperty,nJe=Object.prototype.propertyIsEnumerable,NV=(e,t,r)=>t in e?XYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,IV=(e,t)=>{for(var r in t||(t={}))rJe.call(t,r)&&NV(e,r,t[r]);if(A2e)for(var r of A2e(t))nJe.call(t,r)&&NV(e,r,t[r]);return e},TV=(e,t)=>eJe(e,tJe(t)),Ry=(e,t,r)=>NV(e,typeof t!="symbol"?t+"":t,r),RV=class{constructor(t){Ry(this,"name","eip155"),Ry(this,"client"),Ry(this,"chainId"),Ry(this,"namespace"),Ry(this,"httpProviders"),Ry(this,"events"),Ry(this,"storage"),this.namespace=t.namespace,this.events=px("events"),this.client=px("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=PV.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r);let n=this.chainId;this.chainId=parseInt(t),this.events.emit(DV.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){let n=r||U2e(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,px("disableProviderPing")))}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProviders(){let t={};return this.namespace.chains.forEach(r=>{var n;let o=parseInt(_Ye(r));t[o]=this.createHttpProvider(o,(n=this.namespace.rpcMap)==null?void 0:n[r])}),t}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(t){let r=t||this.chainId;return this.httpProviders[r]||(this.httpProviders=TV(IV({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(t){var r,n;let o=t.request.params?(r=t.request.params[0])==null?void 0:r.chainId:"0x0";o=o.startsWith("0x")?o:`0x${o}`;let s=parseInt(o,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:o}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var r,n,o,s,i;let a=(n=(r=t.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(o=t.request)==null?void 0:o.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");let u=this.client.session.get(t.topic),d=((i=u?.sessionProperties)==null?void 0:i.capabilities)||{},f=c.length>0?c.join(","):`0x${this.chainId.toString(16)}`,p=`${a}${f}`,h=d?.[p];if(h)return h;let y;try{y=LYe(u,a,c)}catch(x){console.warn("Failed to extract capabilities from session",x)}if(y)return y;let w=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:TV(IV({},u.sessionProperties||{}),{capabilities:TV(IV({},d||{}),{[p]:w})})})}catch(x){console.warn("Failed to update session with capabilities",x)}return w}async getCallStatus(t){var r,n,o;let s=this.client.session.get(t.topic),i=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(i){let u=this.getBundlerUrl(t.chainId,i);try{return await this.getUserOperationReceipt(u,t)}catch(d){console.warn("Failed to fetch call status from bundler",d,u)}}let a=(n=s.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}let c=await QYe({resultId:(o=t.request.params)==null?void 0:o[0],storage:this.storage});if(c)try{return await ZYe(c,this.getHttpProvider.bind(this))}catch(u){console.warn("Failed to fetch call status from stored send calls",u,c)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,r){var n;let o=new URL(t),s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dr("eth_getUserOperationReceipt",[(n=r.request.params)==null?void 0:n[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(t,r){return`${xYe}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${r}`}async sendCalls(t){var r,n,o;let s=await this.client.request(t),i=(r=t.request.params)==null?void 0:r[0],a=s?.id,c=s?.capabilities||{},u=(n=c?.caip345)==null?void 0:n.caip2,d=(o=c?.caip345)==null?void 0:o.transactionHashes;return!a||!u||!(d!=null&&d.length)||await YYe({sendCalls:{request:i,result:s},storage:this.storage}),s}},oJe=Object.defineProperty,sJe=(e,t,r)=>t in e?oJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ux=(e,t,r)=>sJe(e,typeof t!="symbol"?t+"":t,r),OV=class{constructor(t){ux(this,"name",k2e),ux(this,"client"),ux(this,"httpProviders"),ux(this,"events"),ux(this,"namespace"),ux(this,"chainId"),this.namespace=t.namespace,this.events=px("events"),this.client=px("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r);let n=this.chainId;this.chainId=t,this.events.emit(DV.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return bl(t).namespace}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var t,r;let n={};return(r=(t=this.namespace)==null?void 0:t.accounts)==null||r.forEach(o=>{var s,i;let a=bl(o),c=(i=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:i[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(o,c)}),n}getHttpProvider(t){let r=bl(t).reference,n=this.httpProviders[r];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return n}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProvider(t,r){let n=r||U2e(t,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,px("disableProviderPing")))}},iJe=Object.defineProperty,aJe=Object.defineProperties,cJe=Object.getOwnPropertyDescriptors,C2e=Object.getOwnPropertySymbols,lJe=Object.prototype.hasOwnProperty,uJe=Object.prototype.propertyIsEnumerable,BV=(e,t,r)=>t in e?iJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,W5=(e,t)=>{for(var r in t||(t={}))lJe.call(t,r)&&BV(e,r,t[r]);if(C2e)for(var r of C2e(t))uJe.call(t,r)&&BV(e,r,t[r]);return e},uP=(e,t)=>aJe(e,cJe(t)),Ma=(e,t,r)=>BV(e,typeof t!="symbol"?t+"":t,r),dP=class e{constructor(t){Ma(this,"client"),Ma(this,"namespaces"),Ma(this,"optionalNamespaces"),Ma(this,"sessionProperties"),Ma(this,"scopedProperties"),Ma(this,"events",new S2e.default),Ma(this,"rpcProviders",{}),Ma(this,"session"),Ma(this,"providerOpts"),Ma(this,"logger"),Ma(this,"uri"),Ma(this,"disableProviderPing",!1),Ma(this,"connectParams");var r,n;this.providerOpts=t,this.logger=ox({logger:(r=t.logger)!=null?r:l2e,name:(n=this.providerOpts.name)!=null?n:O2e}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){let r=new e(t);return await r.initialize(),r}async request(t,r,n){let[o,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(o).request({request:W5({},t),chainId:`${o}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(t,r,n,o){let s=new Date().getTime();this.request(t,n,o).then(i=>r(null,bo(s,i))).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:Rr("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();let{uri:n,response:o}=await this.client.authenticate(t,r);n&&(this.uri=n,this.events.emit("display_uri",n));let s=await o();if(this.session=s.session,this.session){let i=m2e(this.session.namespaces);this.namespaces=lP(this.namespaces,i),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){var r,n;let{uri:o,approval:s}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(n=this.connectParams)==null?void 0:n.walletPay});o&&(this.uri=o,this.events.emit("display_uri",o));let i=await s();this.session=i;let a=m2e(i.namespaces);return this.namespaces=lP(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;let[n,o]=this.validateChain(t);this.getProvider(n).setDefaultChain(o,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");let r=this.client.pairing.getAll();if(!El(r))return;for(let n of r)t.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var t,r;if(this.client=this.providerOpts.client||await o2e.init({core:this.providerOpts.core,logger:this.providerOpts.logger||l2e,relayUrl:this.providerOpts.relayUrl||wYe,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error(n,"Failed to get session"),new Error(`The provided session: ${(r=(t=this.providerOpts)==null?void 0:t.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{let n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");let t=[...new Set(Object.keys(this.session.namespaces).map(r=>Ny(r)))];AV("client",this.client),AV("events",this.events),AV("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;let n=PYe(r,this.session);if(n?.length===0)return;let o=D2e(n),s=lP(this.namespaces,this.optionalNamespaces),i=uP(W5({},s[r]),{accounts:n,chains:o});r==="eip155"?this.rpcProviders[r]=new RV({namespace:i}):this.rpcProviders[r]=new OV({namespace:i})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{var r;let{topic:n}=t;n===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{var r;let{params:n,topic:o}=t;if(o!==((r=this.session)==null?void 0:r.topic))return;let{event:s}=n;if(s.name==="accountsChanged"){let i=s.data;i&&El(i)&&this.events.emit("accountsChanged",i.map(h2e))}else if(s.name==="chainChanged"){let i=n.chainId,a=n.event.data,c=Ny(i),u=EV(i)!==EV(a)?`${c}:${EV(a)}`:i;this.onChainChanged({currentCaipChainId:u})}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{var n,o;if(t!==((n=this.session)==null?void 0:n.topic))return;let{namespaces:s}=r,i=(o=this.client)==null?void 0:o.session.get(t);this.session=uP(W5({},i),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{var r;t.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",uP(W5({},Rr("USER_DISCONNECTED")),{data:t.topic})))}),this.on(DV.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(uP(W5({},t),{internal:!0}))})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[k2e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var r;this.getProvider(t).updateNamespace((r=this.session)==null?void 0:r.namespaces[t])})}setNamespaces(t){let{namespaces:r={},optionalNamespaces:n={},sessionProperties:o,scopedProperties:s}=t;this.optionalNamespaces=lP(r,n),this.sessionProperties=o,this.scopedProperties=s}validateChain(t){let[r,n]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(i=>Ny(i)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];let o=Ny(Object.keys(this.namespaces)[0]),s=this.rpcProviders[o].getDefaultChain();return[o,s]}async requestAccounts(){let[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:r,internal:n=!1}){if(!this.namespaces)return;let[o,s]=this.validateChain(t);s&&(this.updateNamespaceChain(o,s),n?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:o,currentCaipChainId:t,previousCaipChainId:r})):this.getProvider(o).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:r,previousCaipChainId:n}){var o,s;try{if(n===r)return;let i=(s=(o=this.session)==null?void 0:o.namespaces[t])==null?void 0:s.accounts;if(!i)return;let a=i.filter(c=>c.includes(`${r}:`)).map(h2e);if(!El(a))return;this.events.emit("accountsChanged",a)}catch(i){this.logger.warn(i,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,r){if(!this.namespaces)return;let n=this.namespaces[t]?t:`${t}:${r}`,o={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=o}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,r){var n;let o=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${aP}/${t}${o}`,r)}async getFromStore(t){var r;let n=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${aP}/${t}${n}`)}async deleteFromStore(t){var r;let n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${aP}/${t}${n}`)}async cleanupStorage(){var t;try{if(((t=this.client)==null?void 0:t.session.length)>0)return;let r=await this.client.core.storage.getKeys();for(let n of r)n.startsWith(aP)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}});var fP,H2e=b(()=>{l();fP={interpolate(e,t,r){if(e.length!==2||t.length!==2)throw new Error("inputRange and outputRange must be an array of length 2");let n=e[0]||0,o=e[1]||0,s=t[0]||0,i=t[1]||0;return ro?i:(i-s)/(o-n)*(r-n)+s}}});var pP,hP,LV,$2e,K5,Zi,Er,F2e,MV,HV=b(()=>{l();pP=globalThis,hP=pP.ShadowRoot&&(pP.ShadyCSS===void 0||pP.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,LV=Symbol(),$2e=new WeakMap,K5=class{constructor(t,r,n){if(this._$cssResult$=!0,n!==LV)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=r}get styleSheet(){let t=this.o,r=this.t;if(hP&&t===void 0){let n=r!==void 0&&r.length===1;n&&(t=$2e.get(r)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&$2e.set(r,t))}return t}toString(){return this.cssText}},Zi=e=>new K5(typeof e=="string"?e:e+"",void 0,LV),Er=(e,...t)=>{let r=e.length===1?e[0]:t.reduce((n,o,s)=>n+(i=>{if(i._$cssResult$===!0)return i.cssText;if(typeof i=="number")return i;throw Error("Value passed to 'css' function must be a 'css' function result: "+i+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[s+1],e[0]);return new K5(r,e,LV)},F2e=(e,t)=>{if(hP)e.adoptedStyleSheets=t.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(let r of t){let n=document.createElement("style"),o=pP.litNonce;o!==void 0&&n.setAttribute("nonce",o),n.textContent=r.cssText,e.appendChild(n)}},MV=hP?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let r="";for(let n of t.cssRules)r+=n.cssText;return Zi(r)})(e):e});var dJe,fJe,pJe,hJe,mJe,gJe,mP,z2e,yJe,wJe,Z5,G5,gP,V2e,Op,Y5=b(()=>{l();HV();HV();({is:dJe,defineProperty:fJe,getOwnPropertyDescriptor:pJe,getOwnPropertyNames:hJe,getOwnPropertySymbols:mJe,getPrototypeOf:gJe}=Object),mP=globalThis,z2e=mP.trustedTypes,yJe=z2e?z2e.emptyScript:"",wJe=mP.reactiveElementPolyfillSupport,Z5=(e,t)=>e,G5={toAttribute(e,t){switch(t){case Boolean:e=e?yJe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let r=e;switch(t){case Boolean:r=e!==null;break;case Number:r=e===null?null:Number(e);break;case Object:case Array:try{r=JSON.parse(e)}catch{r=null}}return r}},gP=(e,t)=>!dJe(e,t),V2e={attribute:!0,type:String,converter:G5,reflect:!1,useDefault:!1,hasChanged:gP};Symbol.metadata??=Symbol("metadata"),mP.litPropertyMetadata??=new WeakMap;Op=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,r=V2e){if(r.state&&(r.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((r=Object.create(r)).wrapped=!0),this.elementProperties.set(t,r),!r.noAccessor){let n=Symbol(),o=this.getPropertyDescriptor(t,n,r);o!==void 0&&fJe(this.prototype,t,o)}}static getPropertyDescriptor(t,r,n){let{get:o,set:s}=pJe(this.prototype,t)??{get(){return this[r]},set(i){this[r]=i}};return{get:o,set(i){let a=o?.call(this);s?.call(this,i),this.requestUpdate(t,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??V2e}static _$Ei(){if(this.hasOwnProperty(Z5("elementProperties")))return;let t=gJe(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Z5("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Z5("properties"))){let r=this.properties,n=[...hJe(r),...mJe(r)];for(let o of n)this.createProperty(o,r[o])}let t=this[Symbol.metadata];if(t!==null){let r=litPropertyMetadata.get(t);if(r!==void 0)for(let[n,o]of r)this.elementProperties.set(n,o)}this._$Eh=new Map;for(let[r,n]of this.elementProperties){let o=this._$Eu(r,n);o!==void 0&&this._$Eh.set(o,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let r=[];if(Array.isArray(t)){let n=new Set(t.flat(1/0).reverse());for(let o of n)r.unshift(MV(o))}else t!==void 0&&r.push(MV(t));return r}static _$Eu(t,r){let n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,r=this.constructor.elementProperties;for(let n of r.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return F2e(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,r,n){this._$AK(t,n)}_$ET(t,r){let n=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,n);if(o!==void 0&&n.reflect===!0){let s=(n.converter?.toAttribute!==void 0?n.converter:G5).toAttribute(r,n.type);this._$Em=t,s==null?this.removeAttribute(o):this.setAttribute(o,s),this._$Em=null}}_$AK(t,r){let n=this.constructor,o=n._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let s=n.getPropertyOptions(o),i=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:G5;this._$Em=o;let a=i.fromAttribute(r,s.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,r,n,o=!1,s){if(t!==void 0){let i=this.constructor;if(o===!1&&(s=this[t]),n??=i.getPropertyOptions(t),!((n.hasChanged??gP)(s,r)||n.useDefault&&n.reflect&&s===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,n))))return;this.C(t,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,r,{useDefault:n,reflect:o,wrapped:s},i){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,i??r??this[t]),s!==!0||i!==void 0)||(this._$AL.has(t)||(this.hasUpdated||n||(r=void 0),this._$AL.set(t,r)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[o,s]of this._$Ep)this[o]=s;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[o,s]of n){let{wrapped:i}=s,a=this[o];i!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,s,a)}}let t=!1,r=this._$AL;try{t=this.shouldUpdate(r),t?(this.willUpdate(r),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(r)):this._$EM()}catch(n){throw t=!1,this._$EM(),n}t&&this._$AE(r)}willUpdate(t){}_$AE(t){this._$EO?.forEach(r=>r.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(r=>this._$ET(r,this[r])),this._$EM()}updated(t){}firstUpdated(t){}};Op.elementStyles=[],Op.shadowRootOptions={mode:"open"},Op[Z5("elementProperties")]=new Map,Op[Z5("finalized")]=new Map,wJe?.({ReactiveElement:Op}),(mP.reactiveElementVersions??=[]).push("2.1.2")});function ewe(e,t){if(!jV(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return q2e!==void 0?q2e.createHTML(t):t}function Dy(e,t,r=e,n){if(t===kp)return t;let o=n!==void 0?r._$Co?.[n]:r._$Cl,s=X5(t)?void 0:t._$litDirective$;return o?.constructor!==s&&(o?._$AO?.(!1),s===void 0?o=void 0:(o=new s(e),o._$AT(e,r,n)),n!==void 0?(r._$Co??=[])[n]=o:r._$Cl=o),o!==void 0&&(t=Dy(e,o._$AS(e,t.values),o,n)),t}var FV,j2e,yP,q2e,zV,Bp,VV,bJe,Uy,Q5,X5,jV,J2e,$V,J5,W2e,K2e,By,Z2e,G2e,Q2e,qV,V,He,X2e,kp,hn,Y2e,ky,twe,ev,wP,hx,Ly,bP,xP,vP,EP,rwe,xJe,nwe,Up=b(()=>{l();FV=globalThis,j2e=e=>e,yP=FV.trustedTypes,q2e=yP?yP.createPolicy("lit-html",{createHTML:e=>e}):void 0,zV="$lit$",Bp=`lit$${Math.random().toFixed(9).slice(2)}$`,VV="?"+Bp,bJe=`<${VV}>`,Uy=document,Q5=()=>Uy.createComment(""),X5=e=>e===null||typeof e!="object"&&typeof e!="function",jV=Array.isArray,J2e=e=>jV(e)||typeof e?.[Symbol.iterator]=="function",$V=`[ +\f\r]`,J5=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,W2e=/-->/g,K2e=/>/g,By=RegExp(`>|${$V}(?:([^\\s"'>=/]+)(${$V}*=${$V}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Z2e=/'/g,G2e=/"/g,Q2e=/^(?:script|style|textarea|title)$/i,qV=e=>(t,...r)=>({_$litType$:e,strings:t,values:r}),V=qV(1),He=qV(2),X2e=qV(3),kp=Symbol.for("lit-noChange"),hn=Symbol.for("lit-nothing"),Y2e=new WeakMap,ky=Uy.createTreeWalker(Uy,129);twe=(e,t)=>{let r=e.length-1,n=[],o,s=t===2?"":t===3?"":"",i=J5;for(let a=0;a"?(i=o??J5,f=-1):d[1]===void 0?f=-2:(f=i.lastIndex-d[2].length,u=d[1],i=d[3]===void 0?By:d[3]==='"'?G2e:Z2e):i===G2e||i===Z2e?i=By:i===W2e||i===K2e?i=J5:(i=By,o=void 0);let h=i===By&&e[a+1].startsWith("/>")?" ":"";s+=i===J5?c+bJe:f>=0?(n.push(u),c.slice(0,f)+zV+c.slice(f)+Bp+h):c+Bp+(f===-2?a:h)}return[ewe(e,s+(e[r]||"")+(t===2?"":t===3?"":"")),n]},ev=class e{constructor({strings:t,_$litType$:r},n){let o;this.parts=[];let s=0,i=0,a=t.length-1,c=this.parts,[u,d]=twe(t,r);if(this.el=e.createElement(u,n),ky.currentNode=this.el.content,r===2||r===3){let f=this.el.content.firstChild;f.replaceWith(...f.childNodes)}for(;(o=ky.nextNode())!==null&&c.length0){o.textContent=yP?yP.emptyScript:"";for(let h=0;h2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=hn}_$AI(t,r=this,n,o){let s=this.strings,i=!1;if(s===void 0)t=Dy(this,t,r,0),i=!X5(t)||t!==this._$AH&&t!==kp,i&&(this._$AH=t);else{let a=t,c,u;for(t=s[0],c=0;c{let n=r?.renderBefore??t,o=n._$litPart$;if(o===void 0){let s=r?.renderBefore??null;n._$litPart$=o=new hx(t.insertBefore(Q5(),s),s,void 0,r??{})}return o._$AI(e),o}});var WV,ie,vJe,owe=b(()=>{l();Y5();Y5();Up();Up();WV=globalThis,ie=class extends Op{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=nwe(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return kp}};ie._$litElement$=!0,ie.finalized=!0,WV.litElementHydrateSupport?.({LitElement:ie});vJe=WV.litElementPolyfillSupport;vJe?.({LitElement:ie});(WV.litElementVersions??=[]).push("4.2.2")});var swe=b(()=>{l();});var he=b(()=>{l();Y5();Up();owe();swe()});var iwe,tv,awe,cwe,EJe,AJe,CJe,SJe,IJe,TJe,AP,KV=b(()=>{l();iwe={black:"#202020",white:"#FFFFFF",white010:"rgba(255, 255, 255, 0.1)",accent010:"rgba(9, 136, 240, 0.1)",accent020:"rgba(9, 136, 240, 0.2)",accent030:"rgba(9, 136, 240, 0.3)",accent040:"rgba(9, 136, 240, 0.4)",accent050:"rgba(9, 136, 240, 0.5)",accent060:"rgba(9, 136, 240, 0.6)",accent070:"rgba(9, 136, 240, 0.7)",accent080:"rgba(9, 136, 240, 0.8)",accent090:"rgba(9, 136, 240, 0.9)",accent100:"rgba(9, 136, 240, 1.0)",accentSecondary010:"rgba(199, 185, 148, 0.1)",accentSecondary020:"rgba(199, 185, 148, 0.2)",accentSecondary030:"rgba(199, 185, 148, 0.3)",accentSecondary040:"rgba(199, 185, 148, 0.4)",accentSecondary050:"rgba(199, 185, 148, 0.5)",accentSecondary060:"rgba(199, 185, 148, 0.6)",accentSecondary070:"rgba(199, 185, 148, 0.7)",accentSecondary080:"rgba(199, 185, 148, 0.8)",accentSecondary090:"rgba(199, 185, 148, 0.9)",accentSecondary100:"rgba(199, 185, 148, 1.0)",productWalletKit:"#FFB800",productAppKit:"#FF573B",productCloud:"#0988F0",productDocumentation:"#008847",neutrals050:"#F6F6F6",neutrals100:"#F3F3F3",neutrals200:"#E9E9E9",neutrals300:"#D0D0D0",neutrals400:"#BBB",neutrals500:"#9A9A9A",neutrals600:"#6C6C6C",neutrals700:"#4F4F4F",neutrals800:"#363636",neutrals900:"#2A2A2A",neutrals1000:"#252525",semanticSuccess010:"rgba(48, 164, 107, 0.1)",semanticSuccess020:"rgba(48, 164, 107, 0.2)",semanticSuccess030:"rgba(48, 164, 107, 0.3)",semanticSuccess040:"rgba(48, 164, 107, 0.4)",semanticSuccess050:"rgba(48, 164, 107, 0.5)",semanticSuccess060:"rgba(48, 164, 107, 0.6)",semanticSuccess070:"rgba(48, 164, 107, 0.7)",semanticSuccess080:"rgba(48, 164, 107, 0.8)",semanticSuccess090:"rgba(48, 164, 107, 0.9)",semanticSuccess100:"rgba(48, 164, 107, 1.0)",semanticError010:"rgba(223, 74, 52, 0.1)",semanticError020:"rgba(223, 74, 52, 0.2)",semanticError030:"rgba(223, 74, 52, 0.3)",semanticError040:"rgba(223, 74, 52, 0.4)",semanticError050:"rgba(223, 74, 52, 0.5)",semanticError060:"rgba(223, 74, 52, 0.6)",semanticError070:"rgba(223, 74, 52, 0.7)",semanticError080:"rgba(223, 74, 52, 0.8)",semanticError090:"rgba(223, 74, 52, 0.9)",semanticError100:"rgba(223, 74, 52, 1.0)",semanticWarning010:"rgba(243, 161, 63, 0.1)",semanticWarning020:"rgba(243, 161, 63, 0.2)",semanticWarning030:"rgba(243, 161, 63, 0.3)",semanticWarning040:"rgba(243, 161, 63, 0.4)",semanticWarning050:"rgba(243, 161, 63, 0.5)",semanticWarning060:"rgba(243, 161, 63, 0.6)",semanticWarning070:"rgba(243, 161, 63, 0.7)",semanticWarning080:"rgba(243, 161, 63, 0.8)",semanticWarning090:"rgba(243, 161, 63, 0.9)",semanticWarning100:"rgba(243, 161, 63, 1.0)"},tv={core:{backgroundAccentPrimary:"#0988F0",backgroundAccentCertified:"#C7B994",backgroundWalletKit:"#FFB800",backgroundAppKit:"#FF573B",backgroundCloud:"#0988F0",backgroundDocumentation:"#008847",backgroundSuccess:"rgba(48, 164, 107, 0.20)",backgroundError:"rgba(223, 74, 52, 0.20)",backgroundWarning:"rgba(243, 161, 63, 0.20)",textAccentPrimary:"#0988F0",textAccentCertified:"#C7B994",textWalletKit:"#FFB800",textAppKit:"#FF573B",textCloud:"#0988F0",textDocumentation:"#008847",textSuccess:"#30A46B",textError:"#DF4A34",textWarning:"#F3A13F",borderAccentPrimary:"#0988F0",borderSecondary:"#C7B994",borderSuccess:"#30A46B",borderError:"#DF4A34",borderWarning:"#F3A13F",foregroundAccent010:"rgba(9, 136, 240, 0.1)",foregroundAccent020:"rgba(9, 136, 240, 0.2)",foregroundAccent040:"rgba(9, 136, 240, 0.4)",foregroundAccent060:"rgba(9, 136, 240, 0.6)",foregroundSecondary020:"rgba(199, 185, 148, 0.2)",foregroundSecondary040:"rgba(199, 185, 148, 0.4)",foregroundSecondary060:"rgba(199, 185, 148, 0.6)",iconAccentPrimary:"#0988F0",iconAccentCertified:"#C7B994",iconSuccess:"#30A46B",iconError:"#DF4A34",iconWarning:"#F3A13F",glass010:"rgba(255, 255, 255, 0.1)",zIndex:"9999"},dark:{overlay:"rgba(0, 0, 0, 0.50)",backgroundPrimary:"#202020",backgroundInvert:"#FFFFFF",textPrimary:"#FFFFFF",textSecondary:"#9A9A9A",textTertiary:"#BBBBBB",textInvert:"#202020",borderPrimary:"#2A2A2A",borderPrimaryDark:"#363636",borderSecondary:"#4F4F4F",foregroundPrimary:"#252525",foregroundSecondary:"#2A2A2A",foregroundTertiary:"#363636",iconDefault:"#9A9A9A",iconInverse:"#FFFFFF"},light:{overlay:"rgba(230 , 230, 230, 0.5)",backgroundPrimary:"#FFFFFF",borderPrimaryDark:"#E9E9E9",backgroundInvert:"#202020",textPrimary:"#202020",textSecondary:"#9A9A9A",textTertiary:"#6C6C6C",textInvert:"#FFFFFF",borderPrimary:"#E9E9E9",borderSecondary:"#D0D0D0",foregroundPrimary:"#F3F3F3",foregroundSecondary:"#E9E9E9",foregroundTertiary:"#D0D0D0",iconDefault:"#9A9A9A",iconInverse:"#202020"}},awe={1:"4px",2:"8px",10:"10px",3:"12px",4:"16px",6:"24px",5:"20px",8:"32px",16:"64px",20:"80px",32:"128px",64:"256px",128:"512px",round:"9999px"},cwe={0:"0px","01":"2px",1:"4px",2:"8px",3:"12px",4:"16px",5:"20px",6:"24px",7:"28px",8:"32px",9:"36px",10:"40px",12:"48px",14:"56px",16:"64px",20:"80px",32:"128px",64:"256px"},EJe={regular:"KHTeka",mono:"KHTekaMono"},AJe={regular:"400",medium:"500"},CJe={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},SJe={"h1-regular-mono":{lineHeight:"50px",letterSpacing:"-3px"},"h1-regular":{lineHeight:"50px",letterSpacing:"-1px"},"h1-medium":{lineHeight:"50px",letterSpacing:"-0.84px"},"h2-regular-mono":{lineHeight:"44px",letterSpacing:"-2.64px"},"h2-regular":{lineHeight:"44px",letterSpacing:"-0.88px"},"h2-medium":{lineHeight:"44px",letterSpacing:"-0.88px"},"h3-regular-mono":{lineHeight:"38px",letterSpacing:"-2.28px"},"h3-regular":{lineHeight:"38px",letterSpacing:"-0.76px"},"h3-medium":{lineHeight:"38px",letterSpacing:"-0.76px"},"h4-regular-mono":{lineHeight:"32px",letterSpacing:"-1.92px"},"h4-regular":{lineHeight:"32px",letterSpacing:"-0.32px"},"h4-medium":{lineHeight:"32px",letterSpacing:"-0.32px"},"h5-regular-mono":{lineHeight:"26px",letterSpacing:"-1.56px"},"h5-regular":{lineHeight:"26px",letterSpacing:"-0.26px"},"h5-medium":{lineHeight:"26px",letterSpacing:"-0.26px"},"h6-regular-mono":{lineHeight:"20px",letterSpacing:"-1.2px"},"h6-regular":{lineHeight:"20px",letterSpacing:"-0.6px"},"h6-medium":{lineHeight:"20px",letterSpacing:"-0.6px"},"lg-regular-mono":{lineHeight:"16px",letterSpacing:"-0.96px"},"lg-regular":{lineHeight:"18px",letterSpacing:"-0.16px"},"lg-medium":{lineHeight:"18px",letterSpacing:"-0.16px"},"md-regular-mono":{lineHeight:"14px",letterSpacing:"-0.84px"},"md-regular":{lineHeight:"16px",letterSpacing:"-0.14px"},"md-medium":{lineHeight:"16px",letterSpacing:"-0.14px"},"sm-regular-mono":{lineHeight:"12px",letterSpacing:"-0.72px"},"sm-regular":{lineHeight:"14px",letterSpacing:"-0.12px"},"sm-medium":{lineHeight:"14px",letterSpacing:"-0.12px"}},IJe={"ease-out-power-2":"cubic-bezier(0.23, 0.09, 0.08, 1.13)","ease-out-power-1":"cubic-bezier(0.12, 0.04, 0.2, 1.06)","ease-in-power-2":"cubic-bezier(0.92, -0.13, 0.77, 0.91)","ease-in-power-1":"cubic-bezier(0.88, -0.06, 0.8, 0.96)","ease-inout-power-2":"cubic-bezier(0.77, 0.09, 0.23, 1.13)","ease-inout-power-1":"cubic-bezier(0.88, 0.04, 0.12, 1.06)"},TJe={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},AP={colors:iwe,fontFamily:EJe,fontWeight:AJe,textSize:CJe,typography:SJe,tokens:{core:tv.core,theme:tv.dark},borderRadius:awe,spacing:cwe,durations:TJe,easings:IJe}});function CP(e){if(!e)return{};let t={};return t["font-family"]=e["--apkt-font-family"]??e["--w3m-font-family"]??"KHTeka",t.accent=e["--apkt-accent"]??e["--w3m-accent"]??"#0988F0",t["color-mix"]=e["--apkt-color-mix"]??e["--w3m-color-mix"]??"#000",t["color-mix-strength"]=e["--apkt-color-mix-strength"]??e["--w3m-color-mix-strength"]??0,t["font-size-master"]=e["--apkt-font-size-master"]??e["--w3m-font-size-master"]??"10px",t["border-radius-master"]=e["--apkt-border-radius-master"]??e["--w3m-border-radius-master"]??"4px",e["--apkt-z-index"]!==void 0?t["z-index"]=e["--apkt-z-index"]:e["--w3m-z-index"]!==void 0&&(t["z-index"]=e["--w3m-z-index"]),t}function fe(e,...t){return Er(e,...t.map(r=>typeof r=="function"?Zi(r($t)):Zi(r)))}var lwe,ku,$t,Rt=b(()=>{l();he();KV();lwe="--apkt";ku={createCSSVariables(e){let t={},r={};function n(s,i,a=""){for(let[c,u]of Object.entries(s)){let d=a?`${a}-${c}`:c;u&&typeof u=="object"&&Object.keys(u).length?(i[c]={},n(u,i[c],d)):typeof u=="string"&&(i[c]=`${lwe}-${d}`)}}function o(s,i){for(let[a,c]of Object.entries(s))c&&typeof c=="object"?(i[a]={},o(c,i[a])):typeof c=="string"&&(i[a]=`var(${c})`)}return n(e,t),o(t,r),{cssVariables:t,cssVariablesVarPrefix:r}},assignCSSVariables(e,t){let r={};function n(o,s,i){for(let[a,c]of Object.entries(o)){let u=i?`${i}-${a}`:a,d=s[a];c&&typeof c=="object"?n(c,d,u):typeof d=="string"&&(r[`${lwe}-${u}`]=d)}}return n(e,t),r},createRootStyles(e,t){let r={...AP,tokens:{...AP.tokens,theme:e==="light"?tv.light:tv.dark}},{cssVariables:n}=ku.createCSSVariables(r),o=ku.assignCSSVariables(n,r),s=ku.generateW3MVariables(t),i=ku.generateW3MOverrides(t),a=ku.generateScaledVariables(t),c=ku.generateBaseVariables(o),u={...o,...c,...s,...i,...a},d=ku.applyColorMixToVariables(t,u),f={...u,...d};return`:root {${Object.entries(f).map(([h,y])=>`${h}:${y.replace("/[:;{}]/g","")};`).join("")}}`},generateW3MVariables(e){if(!e)return{};let t=CP(e),r={};return r["--w3m-font-family"]=t["font-family"],r["--w3m-accent"]=t.accent,r["--w3m-color-mix"]=t["color-mix"],r["--w3m-color-mix-strength"]=`${t["color-mix-strength"]}%`,r["--w3m-font-size-master"]=t["font-size-master"],r["--w3m-border-radius-master"]=t["border-radius-master"],r},generateW3MOverrides(e){if(!e)return{};let t=CP(e),r={};if(e["--apkt-accent"]||e["--w3m-accent"]){let n=t.accent;r["--apkt-tokens-core-iconAccentPrimary"]=n,r["--apkt-tokens-core-borderAccentPrimary"]=n,r["--apkt-tokens-core-textAccentPrimary"]=n,r["--apkt-tokens-core-backgroundAccentPrimary"]=n}return(e["--apkt-font-family"]||e["--w3m-font-family"])&&(r["--apkt-fontFamily-regular"]=t["font-family"]),t["z-index"]!==void 0&&(r["--apkt-tokens-core-zIndex"]=`${t["z-index"]}`),r},generateScaledVariables(e){if(!e)return{};let t=CP(e),r={};if(e["--apkt-font-size-master"]||e["--w3m-font-size-master"]){let n=parseFloat(t["font-size-master"].replace("px",""));r["--apkt-textSize-h1"]=`${Number(n)*5}px`,r["--apkt-textSize-h2"]=`${Number(n)*4.4}px`,r["--apkt-textSize-h3"]=`${Number(n)*3.8}px`,r["--apkt-textSize-h4"]=`${Number(n)*3.2}px`,r["--apkt-textSize-h5"]=`${Number(n)*2.6}px`,r["--apkt-textSize-h6"]=`${Number(n)*2}px`,r["--apkt-textSize-large"]=`${Number(n)*1.6}px`,r["--apkt-textSize-medium"]=`${Number(n)*1.4}px`,r["--apkt-textSize-small"]=`${Number(n)*1.2}px`}if(e["--apkt-border-radius-master"]||e["--w3m-border-radius-master"]){let n=parseFloat(t["border-radius-master"].replace("px",""));r["--apkt-borderRadius-1"]=`${Number(n)}px`,r["--apkt-borderRadius-2"]=`${Number(n)*2}px`,r["--apkt-borderRadius-3"]=`${Number(n)*3}px`,r["--apkt-borderRadius-4"]=`${Number(n)*4}px`,r["--apkt-borderRadius-5"]=`${Number(n)*5}px`,r["--apkt-borderRadius-6"]=`${Number(n)*6}px`,r["--apkt-borderRadius-8"]=`${Number(n)*8}px`,r["--apkt-borderRadius-16"]=`${Number(n)*16}px`,r["--apkt-borderRadius-20"]=`${Number(n)*20}px`,r["--apkt-borderRadius-32"]=`${Number(n)*32}px`,r["--apkt-borderRadius-64"]=`${Number(n)*64}px`,r["--apkt-borderRadius-128"]=`${Number(n)*128}px`}return r},generateColorMixCSS(e,t){if(!e?.["--w3m-color-mix"]||!e["--w3m-color-mix-strength"])return"";let r=e["--w3m-color-mix"],n=e["--w3m-color-mix-strength"];if(!n||n===0)return"";let o=Object.keys(t||{}).filter(i=>{let a=i.includes("-tokens-core-background")||i.includes("-tokens-core-text")||i.includes("-tokens-core-border")||i.includes("-tokens-core-foreground")||i.includes("-tokens-core-icon")||i.includes("-tokens-theme-background")||i.includes("-tokens-theme-text")||i.includes("-tokens-theme-border")||i.includes("-tokens-theme-foreground")||i.includes("-tokens-theme-icon"),c=i.includes("-borderRadius-")||i.includes("-spacing-")||i.includes("-textSize-")||i.includes("-fontFamily-")||i.includes("-fontWeight-")||i.includes("-typography-")||i.includes("-duration-")||i.includes("-ease-")||i.includes("-path-")||i.includes("-width-")||i.includes("-height-")||i.includes("-visual-size-")||i.includes("-modal-width")||i.includes("-cover");return a&&!c});return o.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) { + :root { + ${o.map(i=>{let a=t?.[i]||"";return a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?`${i}: color-mix(in srgb, ${r} ${n}%, ${a});`:`${i}: color-mix(in srgb, ${r} ${n}%, var(${i}-base, ${a}));`}).join("")} + } + }`},generateBaseVariables(e){let t={},r=e["--apkt-tokens-theme-backgroundPrimary"];r&&(t["--apkt-tokens-theme-backgroundPrimary-base"]=r);let n=e["--apkt-tokens-core-backgroundAccentPrimary"];return n&&(t["--apkt-tokens-core-backgroundAccentPrimary-base"]=n),t},applyColorMixToVariables(e,t){let r={};t?.["--apkt-tokens-theme-backgroundPrimary"]&&(r["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),t?.["--apkt-tokens-core-backgroundAccentPrimary"]&&(r["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)");let n=CP(e),o=n["color-mix"],s=n["color-mix-strength"];if(!s||s===0)return r;let i=Object.keys(t||{}).filter(a=>{let c=a.includes("-tokens-core-background")||a.includes("-tokens-core-text")||a.includes("-tokens-core-border")||a.includes("-tokens-core-foreground")||a.includes("-tokens-core-icon")||a.includes("-tokens-theme-background")||a.includes("-tokens-theme-text")||a.includes("-tokens-theme-border")||a.includes("-tokens-theme-foreground")||a.includes("-tokens-theme-icon")||a.includes("-tokens-theme-overlay"),u=a.includes("-borderRadius-")||a.includes("-spacing-")||a.includes("-textSize-")||a.includes("-fontFamily-")||a.includes("-fontWeight-")||a.includes("-typography-")||a.includes("-duration-")||a.includes("-ease-")||a.includes("-path-")||a.includes("-width-")||a.includes("-height-")||a.includes("-visual-size-")||a.includes("-modal-width")||a.includes("-cover");return c&&!u});return i.length===0||i.forEach(a=>{let c=t?.[a]||"";a.endsWith("-base")||(a==="--apkt-tokens-theme-backgroundPrimary"||a==="--apkt-tokens-core-backgroundAccentPrimary"?r[a]=`color-mix(in srgb, ${o} ${s}%, var(${a}-base))`:c.includes("color-mix")||c.startsWith("#")||c.startsWith("rgb")?r[a]=`color-mix(in srgb, ${o} ${s}%, ${c})`:r[a]=`color-mix(in srgb, ${o} ${s}%, var(${a}-base, ${c}))`)}),r}},{cssVariablesVarPrefix:$t}=ku.createCSSVariables(AP)});function IP(e,t="dark"){My&&document.head.removeChild(My),My=document.createElement("style"),My.textContent=ku.createRootStyles(t,e),document.head.appendChild(My)}function ZV(e,t="dark"){if(SP=e,Hy=document.createElement("style"),Uu=document.createElement("style"),Sl=document.createElement("style"),Hy.textContent=mx(e).core.cssText,Uu.textContent=mx(e).dark.cssText,Sl.textContent=mx(e).light.cssText,document.head.appendChild(Hy),document.head.appendChild(Uu),document.head.appendChild(Sl),IP(e,t),rv(t),!(e?.["--apkt-font-family"]||e?.["--w3m-font-family"]))for(let[n,o]of Object.entries(Dp)){let s=document.createElement("link");s.rel="preload",s.href=o,s.as="font",s.type=n.includes("woff2")?"font/woff2":"font/woff",s.crossOrigin="anonymous",document.head.appendChild(s)}rv(t)}function rv(e="dark"){Uu&&Sl&&My&&(e==="light"?(IP(SP,e),Uu.removeAttribute("media"),Sl.media="enabled"):(IP(SP,e),Sl.removeAttribute("media"),Uu.media="enabled"))}function GV(e){if(SP=e,Hy&&Uu&&Sl){Hy.textContent=mx(e).core.cssText,Uu.textContent=mx(e).dark.cssText,Sl.textContent=mx(e).light.cssText;let t=e?.["--apkt-font-family"]||e?.["--w3m-font-family"];t&&(Hy.textContent=Hy.textContent?.replace("font-family: KHTeka",`font-family: ${t}`),Uu.textContent=Uu.textContent?.replace("font-family: KHTeka",`font-family: ${t}`),Sl.textContent=Sl.textContent?.replace("font-family: KHTeka",`font-family: ${t}`))}if(My){let t=Sl?.media==="enabled"?"light":"dark";IP(e,t)}}function mx(e){let t=!!(e?.["--apkt-font-family"]||e?.["--w3m-font-family"]);return{core:Er` + ${t?Er``:Er` + @font-face { + font-family: 'KHTeka'; + src: + url(${Zi(Dp["KHTeka-400-woff2"])}) format('woff2'), + url(${Zi(Dp["KHTeka-400-woff"])}) format('woff'); + font-weight: 400; + font-style: normal; + font-display: swap; + } + + @font-face { + font-family: 'KHTeka'; + src: + url(${Zi(Dp["KHTeka-300-woff2"])}) format('woff2'), + url(${Zi(Dp["KHTeka-300-woff"])}) format('woff'); + font-weight: 300; + font-style: normal; + } + + @font-face { + font-family: 'KHTekaMono'; + src: + url(${Zi(Dp["KHTekaMono-400-woff2"])}) format('woff2'), + url(${Zi(Dp["KHTekaMono-400-woff"])}) format('woff'); + font-weight: 400; + font-style: normal; + } + + @font-face { + font-family: 'KHTeka'; + src: + url(${Zi(Dp["KHTeka-400-woff2"])}) format('woff2'), + url(${Zi(Dp["KHTeka-400-woff"])}) format('woff'); + font-weight: 400; + font-style: normal; + } + `} + + @keyframes w3m-shake { + 0% { + transform: scale(1) rotate(0deg); + } + 20% { + transform: scale(1) rotate(-1deg); + } + 40% { + transform: scale(1) rotate(1.5deg); + } + 60% { + transform: scale(1) rotate(-1.5deg); + } + 80% { + transform: scale(1) rotate(1deg); + } + 100% { + transform: scale(1) rotate(0deg); + } + } + @keyframes w3m-iframe-fade-out { + 0% { + opacity: 1; + } + 100% { + opacity: 0; + } + } + @keyframes w3m-iframe-zoom-in { + 0% { + transform: translateY(50px); + opacity: 0; + } + 100% { + transform: translateY(0px); + opacity: 1; + } + } + @keyframes w3m-iframe-zoom-in-mobile { + 0% { + transform: scale(0.95); + opacity: 0; + } + 100% { + transform: scale(1); + opacity: 1; + } + } + :root { + --apkt-modal-width: 370px; + + --apkt-visual-size-inherit: inherit; + --apkt-visual-size-sm: 40px; + --apkt-visual-size-md: 55px; + --apkt-visual-size-lg: 80px; + + --apkt-path-network-sm: path( + 'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z' + ); + + --apkt-path-network-md: path( + 'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z' + ); + + --apkt-path-network-lg: path( + 'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z' + ); + + --apkt-width-network-sm: 36px; + --apkt-width-network-md: 48px; + --apkt-width-network-lg: 86px; + + --apkt-duration-dynamic: 0ms; + --apkt-height-network-sm: 40px; + --apkt-height-network-md: 54px; + --apkt-height-network-lg: 96px; + } + `,dark:Er` + :root { + } + `,light:Er` + :root { + } + `}}var My,Hy,Uu,Sl,SP,Dp,Me,Gt,Mt=b(()=>{l();he();Rt();Dp={"KHTeka-500-woff2":"https://fonts.reown.com/KHTeka-Medium.woff2","KHTeka-400-woff2":"https://fonts.reown.com/KHTeka-Regular.woff2","KHTeka-300-woff2":"https://fonts.reown.com/KHTeka-Light.woff2","KHTekaMono-400-woff2":"https://fonts.reown.com/KHTekaMono-Regular.woff2","KHTeka-500-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTeka-400-woff":"https://fonts.reown.com/KHTeka-Regular.woff","KHTeka-300-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTekaMono-400-woff":"https://fonts.reown.com/KHTekaMono-Regular.woff"};Me=Er` + div, + span, + iframe, + a, + img, + form, + button, + label, + *::after, + *::before { + margin: 0; + padding: 0; + box-sizing: border-box; + font-style: normal; + text-rendering: optimizeSpeed; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-tap-highlight-color: transparent; + backface-visibility: hidden; + } + + :host { + font-family: var(--apkt-fontFamily-regular); + } +`,Gt=Er` + button, + a { + cursor: pointer; + display: flex; + justify-content: center; + align-items: center; + position: relative; + + will-change: background-color, color, border, box-shadow, width, height, transform, opacity; + outline: none; + border: none; + text-decoration: none; + transition: + background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), + border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2); + will-change: + background-color, color, border, box-shadow, width, height, transform, opacity, scale, + border-radius; + } + + a:active:not([disabled]), + button:active:not([disabled]) { + scale: 0.975; + transform-origin: center; + } + + button:disabled { + cursor: default; + } + + input { + border: none; + outline: none; + appearance: none; + } +`});var hr,gx=b(()=>{l();hr={getSpacingStyles(e,t){if(Array.isArray(e))return e[t]?`var(--apkt-spacing-${e[t]})`:void 0;if(typeof e=="string")return`var(--apkt-spacing-${e})`},getFormattedDate(e){return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}).format(e)},formatCurrency(e=0,t={}){let r=Number(e);return isNaN(r)?"$0.00":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2,...t}).format(r)},getHostName(e){try{return new URL(e).hostname}catch{return""}},getTruncateString({string:e,charsStart:t,charsEnd:r,truncate:n}){return e.length<=t+r?e:n==="end"?`${e.substring(0,t)}...`:n==="start"?`...${e.substring(e.length-r)}`:`${e.substring(0,Math.floor(t))}...${e.substring(e.length-Math.floor(r))}`},generateAvatarColors(e){let r=e.toLowerCase().replace(/^0x/iu,"").replace(/[^a-f0-9]/gu,"").substring(0,6).padEnd(6,"0"),n=this.hexToRgb(r),o=getComputedStyle(document.documentElement).getPropertyValue("--w3m-border-radius-master"),i=100-3*Number(o?.replace("px","")),a=`${i}% ${i}% at 65% 40%`,c=[];for(let u=0;u<5;u+=1){let d=this.tintColor(n,.15*u);c.push(`rgb(${d[0]}, ${d[1]}, ${d[2]})`)}return` + --local-color-1: ${c[0]}; + --local-color-2: ${c[1]}; + --local-color-3: ${c[2]}; + --local-color-4: ${c[3]}; + --local-color-5: ${c[4]}; + --local-radial-circle: ${a} + `},hexToRgb(e){let t=parseInt(e,16),r=t>>16&255,n=t>>8&255,o=t&255;return[r,n,o]},tintColor(e,t){let[r,n,o]=e,s=Math.round(r+(255-r)*t),i=Math.round(n+(255-n)*t),a=Math.round(o+(255-o)*t);return[s,i,a]},isNumber(e){return{number:/^[0-9]+$/u}.number.test(e)},getColorTheme(e){return e||(typeof window<"u"&&window.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)")?.matches?"dark":"light":"dark")},splitBalance(e){let t=e.split(".");return t.length===2?[t[0],t[1]]:["0","00"]},roundNumber(e,t,r){return e.toString().length>=t?Number(e).toFixed(r):e},cssDurationToNumber(e){return e.endsWith("s")?Number(e.replace("s",""))*1e3:e.endsWith("ms")?Number(e.replace("ms","")):0},maskInput({value:e,decimals:t,integers:r}){if(e=e.replace(",","."),e===".")return"0.";let[n="",o]=e.split(".").map(d=>d.replace(/[^0-9]/gu,"")),s=r?n.substring(0,r):n,i=s.length===2?String(Number(s)):s,a=typeof t=="number"?o?.substring(0,t):o,c=typeof t!="number"||t>0;return(typeof a=="string"&&c?[i,a].join("."):i)??""},capitalize(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}}});var uwe=b(()=>{l();gx()});function _Je(e,t){let{kind:r,elements:n}=t;return{kind:r,elements:n,finisher(o){customElements.get(e)||customElements.define(e,o)}}}function PJe(e,t){return customElements.get(e)||customElements.define(e,t),t}function ne(e){return function(r){return typeof r=="function"?PJe(e,r):_Je(e,r)}}var Bt=b(()=>{l()});var Ve=b(()=>{l();H2e();Mt();gx();uwe();Bt();KV();Rt()});var Br,TP=b(()=>{l();ut();Br={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:Z.CHAIN.EVM,ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH",getSDKVersionWarningMessage(e,t){return` + @@@@@@@ @@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@ + @@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@ + @@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@ + @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ + @@@@@ @@@@@@@@@@@@@@@@@@ + +AppKit SDK version ${e} is outdated. Latest version is ${t}. Please update to the latest version for bug fixes and new features. + +Changelog: https://github.com/reown-com/appkit/releases +NPM Registry: https://www.npmjs.com/package/@reown/appkit`}}});var dwe,fwe=b(()=>{l();ut();TP();dwe={ConnectorExplorerIds:{[Z.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[Z.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[Z.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Br.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Br.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Br.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Br.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Br.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Br.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Br.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Br.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Br.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Br.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Br.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Br.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Br.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"},ConnectorImageIds:{[Z.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[Z.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[Z.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[Z.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[Z.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[Z.CONNECTOR_ID.INJECTED]:"Browser Wallet",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[Z.CONNECTOR_ID.COINBASE]:"Coinbase",[Z.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[Z.CONNECTOR_ID.LEDGER]:"Ledger",[Z.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[Z.CONNECTOR_ID.INJECTED]:"INJECTED",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[Z.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[Z.CONNECTOR_ID.AUTH]:"AUTH",[Br.CONNECTOR_TYPE_AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]}});var an,pwe=b(()=>{l();ut();ct();TP();an={getCaipTokens(e){if(!e)return;let t={};return Object.entries(e).forEach(([r,n])=>{t[`${Br.EIP155}:${r}`]=n}),t},isLowerCaseMatch(e,t){return e?.toLowerCase()===t?.toLowerCase()},getActiveNamespaceConnectedToAuth(){let e=$.state.activeChain;return Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(t=>re.getConnectorId(t)===Z.CONNECTOR_ID.AUTH&&t===e)},withRetry({conditionFn:e,intervalMs:t,maxRetries:r}){let n=0;return new Promise(o=>{async function s(){return n+=1,await e()?o(!0):n>=r?o(!1):(setTimeout(s,t),null)}s()})},userChainIdToChainNamespace(e){if(typeof e=="number")return Z.CHAIN.EVM;let[t]=e.split(":");return t},getOtherAuthNamespaces(e){return e?Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter(n=>n!==e):[]},getConnectorStorageInfo(e,t){let n=de.getConnections()[t]??[];return{hasDisconnected:de.isConnectorDisconnected(e,t),hasConnected:n.some(o=>an.isLowerCaseMatch(o.connectorId,e))}}}});var NJe,hi,hwe=b(()=>{l();ut();ct();NJe=new AbortController,hi={EmbeddedWalletAbortController:NJe,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"ORIGIN_NOT_ALLOWED"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{code:"APKT001",displayMessage:"Network Not Found",debugMessage:"The specified network is not recognized. Please ensure it is included in the `networks` array of your `createAppKit` configuration."},ORIGIN_NOT_ALLOWED:{code:"APKT002",displayMessage:"Invalid App Configuration",debugMessage:()=>`The origin ${G1()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com. [PID: ${Y.state.projectId}]`},IFRAME_LOAD_FAILED:{code:"APKT003",displayMessage:"Network Error: Wallet Load Failed",debugMessage:()=>"Failed to load the embedded wallet. This may be due to network issues or server downtime. Please check your network connection and try again shortly. Contact support if the issue persists."},IFRAME_REQUEST_TIMEOUT:{code:"APKT004",displayMessage:"Wallet Request Timeout",debugMessage:()=>"The request to the embedded wallet timed out. Please check your network connection and try again shortly. Contact support if the issue persists."},UNVERIFIED_DOMAIN:{code:"APKT005",displayMessage:"Unverified Domain",debugMessage:()=>"Embedded wallet load failed. Ensure your domain is verified in https://dashboard.reown.com."},JWT_TOKEN_NOT_VALID:{code:"APKT006",displayMessage:"Session Expired",debugMessage:"Your session is invalid or expired. Please check your system\u2019s date and time settings, then reconnect."},INVALID_PROJECT_ID:{code:"APKT007",displayMessage:"Invalid Project ID",debugMessage:"The specified project ID is invalid. Please visit https://dashboard.reown.com to obtain a valid project ID."},PROJECT_ID_NOT_CONFIGURED:{code:"APKT008",displayMessage:"Project ID Missing",debugMessage:"No project ID is configured. You can create and configure a project ID at https://dashboard.reown.com."},SERVER_ERROR_APP_CONFIGURATION:{code:"APKT009",displayMessage:"Server Error",debugMessage:e=>`Unable to fetch App Configuration. ${e}. Please check your network connection and try again shortly. Contact support if the issue persists.`},RATE_LIMITED_APP_CONFIGURATION:{code:"APKT010",displayMessage:"Rate Limited",debugMessage:"You have been rate limited while retrieving App Configuration. Please wait a few minutes and try again. Contact support if the issue persists."}},ALERT_WARNINGS:{LOCAL_CONFIGURATION_IGNORED:{debugMessage:e=>`[Reown Config Notice] ${e}`},INACTIVE_NAMESPACE_NOT_CONNECTED:{code:"APKTW001",displayMessage:"Inactive Namespace Not Connected",debugMessage:(e,t)=>`An error occurred while connecting an inactive namespace ${e}: "${t}"`},INVALID_EMAIL:{code:"APKTW002",displayMessage:"Invalid Email Address",debugMessage:"Please enter a valid email address"}}}});var _P,mwe=b(()=>{l();ct();_P={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:kH.asset,84532:UH.asset}},getTokenSymbolByAddress(e){if(!e)return;let[t]=Object.entries(_P.TOKEN_ADDRESSES_BY_SYMBOL).find(([r,n])=>Object.values(n).includes(e))??[];return t}}});var YV,gwe=b(()=>{l();gh();YV={createLogger(e,t="error"){let r=X2({level:t}),{logger:n}=Fl({opts:r});return n.error=(...o)=>{for(let s of o)if(s instanceof Error){e(s,...o);return}e(void 0,...o)},n}}});function QV(e,t){let r=new URL("https://rpc.walletconnect.org/v1/");return r.searchParams.set("chainId",e),r.searchParams.set("projectId",t),r.toString()}var RJe,JV,Du,ywe=b(()=>{l();R6();ut();ct();fwe();RJe="rpc.walletconnect.org";JV=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","eip155:80094","eip155:80069","eip155:560048","eip155:31","eip155:2818","eip155:57054","eip155:911867","eip155:534351","eip155:1112","eip155:534352","eip155:1111","eip155:146","eip155:130","eip155:1284","eip155:30","eip155:2810","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Du={extendRpcUrlWithProjectId(e,t){let r=!1;try{r=new URL(e).host===RJe}catch{r=!1}if(r){let n=new URL(e);return n.searchParams.has("projectId")||n.searchParams.set("projectId",t),n.toString()}return e},isCaipNetwork(e){return"chainNamespace"in e&&"caipNetworkId"in e},getChainNamespace(e){return this.isCaipNetwork(e)?e.chainNamespace:Z.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${Z.CHAIN.EVM}:${e.id}`},getDefaultRpcUrl(e,t,r){let n=e.rpcUrls?.default?.http?.[0];return JV.includes(t)?QV(t,r):n||""},extendCaipNetwork(e,{customNetworkImageUrls:t,projectId:r,customRpcUrls:n}){let o=this.getChainNamespace(e),s=this.getCaipNetworkId(e),i=e.rpcUrls?.default?.http?.[0],a=this.getDefaultRpcUrl(e,s,r),c=e?.rpcUrls?.chainDefault?.http?.[0]||i,u=n?.[s]?.map(p=>p.url)||[],d=[...u,...a?[a]:[]],f=[...u];return c&&!f.includes(c)&&f.push(c),{...e,chainNamespace:o,caipNetworkId:s,assets:{imageId:dwe.NetworkImageIds[e.id],imageUrl:t?.[e.id]},rpcUrls:{...e.rpcUrls,default:{http:d},chainDefault:{http:f}}}},extendCaipNetworks(e,{customNetworkImageUrls:t,projectId:r,customRpcUrls:n}){return e.map(o=>Du.extendCaipNetwork(o,{customNetworkImageUrls:t,customRpcUrls:n,projectId:r}))},getViemTransport(e,t,r){let n=[];return r?.forEach(o=>{n.push(ry(o.url,o.config))}),JV.includes(e.caipNetworkId)&&n.push(ry(QV(e.caipNetworkId,t),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),e?.rpcUrls?.default?.http?.forEach(o=>{n.push(ry(o))}),G3(n)},extendWagmiTransports(e,t,r){if(JV.includes(e.caipNetworkId)){let n=this.getDefaultRpcUrl(e,e.caipNetworkId,t);return G3([r,ry(n)])}return r},getUnsupportedNetwork(e){return{id:e.split(":")[1],caipNetworkId:e,name:Z.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(e){let t=de.getActiveCaipNetworkId(),r=$.getAllRequestedCaipNetworks(),n=Array.from($.state.chains?.keys()||[]),o=t?.split(":")[0],s=o?n.includes(o):!1,i=r?.find(c=>c.caipNetworkId===t);return s&&!i&&t?this.getUnsupportedNetwork(t):i||e||r?.[0]}}});var Il=b(()=>{l();TP();pwe();hwe();mwe();gwe();ywe()});var nv,wwe=b(()=>{l();nv={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603}});var PP,bwe=b(()=>{l();RH();R6();ut();ct();ct();wwe();PP=class extends r5{async setUniversalProvider(t){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new n5({provider:t,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(t){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(t.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(t){console.warn("UniversalAdapter:disconnect - error",t)}return{connections:[]}}syncConnections(){return Promise.resolve()}async writeSolanaTransaction(){return Promise.resolve({hash:""})}async getAccounts({namespace:t}){let n=this.provider?.session?.namespaces?.[t]?.accounts?.map(o=>{let[,,s]=o.split(":");return s}).filter((o,s,i)=>i.indexOf(o)===s)||[];return Promise.resolve({accounts:n.map(o=>se.createAccount(t,o,t==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(t){if(!(t.caipNetwork&&Ye.BALANCE_SUPPORTED_CHAINS.includes(t.caipNetwork?.chainNamespace))||t.caipNetwork?.testnet)return{balance:"0.00",symbol:t.caipNetwork?.nativeCurrency.symbol||""};let n=$.getAccountData();if(n?.balanceLoading&&t.chainId===$.state.activeCaipNetwork?.id)return{balance:n?.balance||"0.00",symbol:n?.balanceSymbol||""};let s=(await $.fetchTokenBalance()).find(i=>i.chainId===`${t.caipNetwork?.chainNamespace}:${t.chainId}`&&i.symbol===t.caipNetwork?.nativeCurrency.symbol);return{balance:s?.quantity.numeric||"0.00",symbol:s?.symbol||t.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(t){let{provider:r,message:n,address:o}=t;if(!r)throw new Error("UniversalAdapter:signMessage - provider is undefined");let s="";return $.state.activeCaipNetwork?.chainNamespace===Z.CHAIN.SOLANA?s=(await r.request({method:"solana_signMessage",params:{message:wm.encode(new TextEncoder().encode(n)),pubkey:o}},$.state.activeCaipNetwork?.caipNetworkId)).signature:s=await r.request({method:"personal_sign",params:[n,o]},$.state.activeCaipNetwork?.caipNetworkId),{signature:s}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(t){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(t){let{caipNetwork:r}=t,n=this.getWalletConnectConnector();if(r.chainNamespace===Z.CHAIN.EVM)try{await n.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:wr(r.id)}]})}catch(o){if(o.code===nv.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||o.code===nv.ERROR_INVALID_CHAIN_ID||o.code===nv.ERROR_CODE_DEFAULT||o?.data?.originalError?.code===nv.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await n.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:wr(r.id),rpcUrls:[r?.rpcUrls.chainDefault?.http],chainName:r.name,nativeCurrency:r.nativeCurrency,blockExplorerUrls:[r.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(r.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(n=>n.type==="WALLET_CONNECT")?.provider}}});var OJe,NP,xwe,vwe=b(()=>{l();ct();Il();OJe=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication","headless"],NP={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;let t=e.config;return!!e.isEnabled&&t.includes("email")},processFallback:e=>e===void 0?Ye.DEFAULT_REMOTE_FEATURES.email:!!e},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;let t=e.config;return e.isEnabled&&t.length>0?t.filter(r=>r!=="email"):!1},processFallback:e=>e===void 0?Ye.DEFAULT_REMOTE_FEATURES.socials:typeof e=="boolean"?e?Ye.DEFAULT_REMOTE_FEATURES.socials:!1:e},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;let t=e.config;return e.isEnabled&&t.length>0?t:!1},processFallback:e=>e===void 0?Ye.DEFAULT_REMOTE_FEATURES.swaps:typeof e=="boolean"?e?Ye.DEFAULT_REMOTE_FEATURES.swaps:!1:e},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;let t=e.config;return e.isEnabled&&t.length>0?t:!1},processFallback:e=>e===void 0?Ye.DEFAULT_REMOTE_FEATURES.onramp:typeof e=="boolean"?e?Ye.DEFAULT_REMOTE_FEATURES.onramp:!1:e},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:e=>e===void 0?Ye.DEFAULT_REMOTE_FEATURES.activity:!!e},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:e=>e===void 0?Ye.DEFAULT_REMOTE_FEATURES.reownBranding:!!e},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>e.isEnabled&&(e.config??[]),processFallback:e=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:()=>Ye.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:()=>Ye.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:()=>Ye.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:e=>typeof e>"u"?Ye.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!e},headless:{apiFeatureName:"headless",localFeatureName:"headless",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>!!e.isEnabled,processFallback:()=>Ye.DEFAULT_REMOTE_FEATURES.headless}},xwe={localSettingsOverridden:new Set,getApiConfig(e,t){return t?.find(r=>r.id===e)},addWarning(e,t){if(e!==void 0){let r=NP[t],n=r.isLegacy?`"features.${r.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(n)}},processFeature(e,t,r,n,o){let s=NP[e],i=t[s.localFeatureName];if(o&&!s.isAvailableOnBasic)return!1;if(n){let a=this.getApiConfig(s.apiFeatureName,r);return a?.config===null?this.processFallbackFeature(e,i):a?.config?(i!==void 0&&this.addWarning(i,e),this.processApiFeature(e,a)):!1}return this.processFallbackFeature(e,i)},processApiFeature(e,t){return NP[e].processApi(t)},processFallbackFeature(e,t){return NP[e].processFallback(t)},async fetchRemoteFeatures(e){let t=e.basic??!1,r=e.features||{};this.localSettingsOverridden.clear();let n=null,o=!1;try{n=await ge.fetchProjectConfig(),o=n!=null}catch(i){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",i)}let s=o&&!t?Ye.DEFAULT_REMOTE_FEATURES:Ye.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(let i of OJe){let a=this.processFeature(i,r,n,o,t);Object.assign(s,{[i]:a})}}catch(i){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",i),Ye.DEFAULT_REMOTE_FEATURES}if(o&&this.localSettingsOverridden.size>0){let i=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;sn.open({debugMessage:hi.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(i)},"warning")}return s}}});var ov,XV=b(()=>{l();ut();$r();ov=class{constructor(t){this.getNonce=t.getNonce}async createMessage(t){let r={accountAddress:t.accountAddress,chainId:t.chainId,version:"1",domain:typeof document>"u"?"Unknown Domain":document.location.host,uri:typeof document>"u"?"Unknown URI":document.location.href,resources:this.resources,nonce:await this.getNonce(t),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(r,{toString:()=>this.stringify(r)})}stringify(t){let r=this.getNetworkName(t.chainId);return[`${t.domain} wants you to sign in with your ${r} account:`,t.accountAddress,t.statement?` +${t.statement} +`:"",`URI: ${t.uri}`,`Version: ${t.version}`,`Chain ID: ${t.chainId}`,`Nonce: ${t.nonce}`,t.issuedAt&&`Issued At: ${t.issuedAt}`,t.expirationTime&&`Expiration Time: ${t.expirationTime}`,t.notBefore&&`Not Before: ${t.notBefore}`,t.requestId&&`Request ID: ${t.requestId}`,t.resources?.length&&t.resources.reduce((n,o)=>`${n} +- ${o}`,"Resources:")].filter(n=>typeof n=="string").join(` +`).trim()}getNetworkName(t){let r=$.getAllRequestedCaipNetworks();return V1.getNetworkNameByCaipNetworkId(r,t)}stringifyDate(t){return t.toISOString()}}});function BJe(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid token");let r=t[1];if(typeof r!="string")throw new Error("Invalid token");let n=r.replace(/-/gu,"+").replace(/_/gu,"/"),o=n.padEnd(n.length+(4-n.length%4)%4,"=");return JSON.parse(atob(o))}var ej,Ewe=b(()=>{l();ut();Cu();lp();$r();yc();XV();ej=class{constructor(t={}){this.otpUuid=null,this.listeners={sessionChanged:[]},this.localAuthStorageKey=t.localAuthStorageKey||Fe.SIWX_AUTH_TOKEN,this.localNonceStorageKey=t.localNonceStorageKey||Fe.SIWX_NONCE_TOKEN,this.required=t.required??!0,this.messenger=new ov({getNonce:this.getNonce.bind(this)})}async createMessage(t){return this.messenger.createMessage(t)}async addSession(t){let r=await this.request({method:"POST",key:"authenticate",body:{data:t.data,message:t.message,signature:t.signature,clientId:this.getClientId(),walletInfo:this.getWalletInfo()},headers:["nonce","otp"]});this.setStorageToken(r.token,this.localAuthStorageKey),this.emit("sessionChanged",t),this.setAppKitAccountUser(BJe(r.token)),this.otpUuid=null}async getSessions(t,r){try{if(!this.getStorageToken(this.localAuthStorageKey))return[];let n=await this.request({method:"GET",key:"me",query:{},headers:["auth"]});if(!n)return[];let o=n.address.toLowerCase()===r.toLowerCase(),s=n.caip2Network===t;if(!o||!s)return[];let i={data:{accountAddress:n.address,chainId:n.caip2Network},message:"",signature:""};return this.emit("sessionChanged",i),this.setAppKitAccountUser(n),[i]}catch{return[]}}async revokeSession(t,r){return Promise.resolve(this.clearStorageTokens())}async setSessions(t){if(t.length===0)this.clearStorageTokens();else{let r=t.find(n=>n.data.chainId===oy()?.caipNetworkId)||t[0];await this.addSession(r)}}getRequired(){return this.required}async getSessionAccount(){if(!this.getStorageToken(this.localAuthStorageKey))throw new Error("Not authenticated");return this.request({method:"GET",key:"me",body:void 0,query:{includeAppKitAccount:!0},headers:["auth"]})}async setSessionAccountMetadata(t=null){if(!this.getStorageToken(this.localAuthStorageKey))throw new Error("Not authenticated");return this.request({method:"PUT",key:"account-metadata",body:{metadata:t},headers:["auth"]})}on(t,r){return this.listeners[t].push(r),()=>{this.listeners[t]=this.listeners[t].filter(n=>n!==r)}}removeAllListeners(){Object.keys(this.listeners).forEach(r=>{this.listeners[r]=[]})}async requestEmailOtp({email:t,account:r}){let n=await this.request({method:"POST",key:"otp",body:{email:t,account:r}});return this.otpUuid=n.uuid,this.messenger.resources=[`email:${t}`],n}confirmEmailOtp({code:t}){return this.request({method:"PUT",key:"otp",body:{code:t},headers:["otp"]})}async request({method:t,key:r,query:n,body:o,headers:s}){let{projectId:i,st:a,sv:c}=this.getSDKProperties(),u=new URL(`${Z.W3M_API_URL}/auth/v1/${String(r)}`);u.searchParams.set("projectId",i),u.searchParams.set("st",a),u.searchParams.set("sv",c),n&&Object.entries(n).forEach(([f,p])=>u.searchParams.set(f,String(p)));let d=await fetch(u,{method:t,body:o?JSON.stringify(o):void 0,headers:Array.isArray(s)?s.reduce((f,p)=>{switch(p){case"nonce":f["x-nonce-jwt"]=`Bearer ${this.getStorageToken(this.localNonceStorageKey)}`;break;case"auth":f.Authorization=`Bearer ${this.getStorageToken(this.localAuthStorageKey)}`;break;case"otp":this.otpUuid&&(f["x-otp"]=this.otpUuid);break;default:break}return f},{}):void 0});if(!d.ok)throw new Error(await d.text());return d.headers.get("content-type")?.includes("application/json")?d.json():null}getStorageToken(t){return Le.getItem(t)}setStorageToken(t,r){Le.setItem(r,t)}clearStorageTokens(){this.otpUuid=null,Le.removeItem(this.localAuthStorageKey),Le.removeItem(this.localNonceStorageKey),this.emit("sessionChanged",void 0)}async getNonce(){let{nonce:t,token:r}=await this.request({method:"GET",key:"nonce"});return this.setStorageToken(r,this.localNonceStorageKey),t}getClientId(){return ze.state.clientId}getWalletInfo(){let t=$.getAccountData()?.connectedWalletInfo;if(!t)return;if("social"in t&&"identifier"in t){let s=t.social,i=t.identifier;return{type:"social",social:s,identifier:i}}let{name:r,icon:n}=t,o="unknown";switch(t.type){case"EXTERNAL":case"INJECTED":case"ANNOUNCED":o="extension";break;case"WALLET_CONNECT":o="walletconnect";break;default:o="unknown"}return{type:o,name:r,icon:n}}getSDKProperties(){return ge._getSdkProperties()}emit(t,r){this.listeners[t].forEach(n=>n(r))}setAppKitAccountUser(t){let{email:r}=t;r&&Object.values(Z.CHAIN).forEach(n=>{$.setAccountProp("user",{email:r},n)})}}});var Awe=b(()=>{l();Ewe();XV()});var Cwe={};Te(Cwe,{ReownAuthentication:()=>ej,ReownAuthenticationMessenger:()=>ov});var Swe=b(()=>{l();Awe()});var RP,Iwe=b(()=>{l();M2e();ut();ct();Ve();Il();bwe();vwe();RP=class{constructor(t){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(r,n)=>{if(r){let o=$.getCaipNetworks(r)?.find(a=>a.id===n);if(o)return o;let s=$.getNetworkData(r)?.caipNetwork;return s||$.getRequestedCaipNetworks(r).filter(a=>a.chainNamespace===r)?.[0]}return $.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{let r=this.getCaipNetwork();if(r)return r.id},this.getCaipNetworks=r=>$.getCaipNetworks(r),this.getActiveChainNamespace=()=>$.state.activeChain,this.setRequestedCaipNetworks=(r,n)=>{$.setRequestedCaipNetworks(r,n)},this.getApprovedCaipNetworkIds=()=>$.getAllApprovedCaipNetworkIds(),this.getCaipAddress=r=>$.state.activeChain===r||!r?$.state.activeCaipAddress:$.state.chains.get(r)?.accountState?.caipAddress,this.setClientId=r=>{ze.setClientId(r)},this.getProvider=r=>ar.getProvider(r),this.getProviderType=r=>ar.getProviderId(r),this.getPreferredAccountType=r=>Fr(r),this.setCaipAddress=(r,n,o=!1)=>{$.setAccountProp("caipAddress",r,n,o),$.setAccountProp("address",se.getPlainAddress(r),n,o)},this.setBalance=(r,n,o)=>{$.setAccountProp("balance",r,o),$.setAccountProp("balanceSymbol",n,o)},this.setProfileName=(r,n)=>{$.setAccountProp("profileName",r,n)},this.setProfileImage=(r,n)=>{$.setAccountProp("profileImage",r,n)},this.setUser=(r,n)=>{$.setAccountProp("user",r,n)},this.resetAccount=r=>{$.resetAccount(r)},this.setCaipNetwork=r=>{$.setActiveCaipNetwork(r)},this.setCaipNetworkOfNamespace=(r,n)=>{$.setChainNetworkData(n,{caipNetwork:r})},this.setStatus=(r,n)=>{$.setAccountProp("status",r,n),re.isConnected()?de.setConnectionStatus("connected"):de.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=r=>$.getAccountData(r)?.address,this.setConnectors=r=>{let n=[...re.state.allConnectors,...r];re.setConnectors(n)},this.setConnections=(r,n)=>{de.setConnections(r,n),ee.setConnections(r,n)},this.fetchIdentity=r=>ze.fetchIdentity(r),this.getReownName=r=>bm.getNamesForAddress(r),this.getConnectors=()=>re.getConnectors(),this.getConnectorImage=r=>St.getConnectorImage(r),this.getConnections=r=>this.remoteFeatures.multiWallet?fp.getConnectionsData(r).connections:(sn.open(Z.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=r=>this.remoteFeatures.multiWallet?fp.getConnectionsData(r).recentConnections:(sn.open(Z.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async r=>{if(!this.remoteFeatures.multiWallet){sn.open(Z.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await ee.switchConnection(r)},this.deleteConnection=r=>{if(!this.remoteFeatures.multiWallet){sn.open(Z.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}de.deleteAddressFromConnection(r),ee.syncStorageConnections()},this.setConnectedWalletInfo=(r,n)=>{let o=ar.getProviderId(n),s=r?{...r,type:o}:void 0;$.setAccountProp("connectedWalletInfo",s,n)},this.getIsConnectedState=()=>!!$.state.activeCaipAddress,this.addAddressLabel=(r,n,o)=>{let s=$.getAccountData(o)?.addressLabels||{};$.setAccountProp("addressLabels",{...s,[r]:n},o)},this.removeAddressLabel=(r,n)=>{let o=$.getAccountData(n)?.addressLabels||{};$.setAccountProp("addressLabels",{...o,[r]:void 0},n)},this.getAddress=r=>{let n=r||$.state.activeChain;return $.getAccountData(n)?.address},this.resetNetwork=r=>{$.resetNetwork(r)},this.addConnector=r=>{re.addConnector(r)},this.resetWcConnection=()=>{ee.resetWcConnection()},this.setAddressExplorerUrl=(r,n)=>{$.setAccountProp("addressExplorerUrl",r,n)},this.setSmartAccountDeployed=(r,n)=>{$.setAccountProp("smartAccountDeployed",r,n)},this.setPreferredAccountType=(r,n)=>{$.setAccountProp("preferredAccountType",r,n)},this.setEIP6963Enabled=r=>{Y.setEIP6963Enabled(r)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=t,this.version=t.sdkVersion,this.caipNetworks=this.extendCaipNetworks(t),this.chainNamespaces=this.getChainNamespacesSet(t.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(t),this.chainAdapters=this.createAdapters(t.adapters),this.readyPromise=this.initialize(t)}getChainNamespacesSet(t,r){let n=t?.map(s=>s.namespace).filter(s=>!!s);if(n?.length)return[...new Set(n)];let o=r?.map(s=>s.chainNamespace);return[...new Set(o)]}async initialize(t){if(this.initializeProjectSettings(t),this.initControllers(t),await this.initChainAdapters(),this.sendInitializeEvent(t),t.features?.headless&&!Dn.hasInjectedConnectors()&&ge.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1,fetchRecommendedWallets:!0}),Y.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),!t.basic&&!t.manualWCControl&&(this.remoteFeatures=await xwe.fetchRemoteFeatures(t)),await ge.fetchUsage(),Y.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&t5.setOnrampProviders(this.remoteFeatures.onramp),(Y.state.remoteFeatures?.email||Array.isArray(Y.state.remoteFeatures?.socials)&&Y.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),Y.state.features?.reownAuthentication||Y.state.remoteFeatures?.reownAuthentication){let{ReownAuthentication:r}=await Promise.resolve().then(()=>(Swe(),Cwe)),n=Y.state.siwx;n instanceof r||(n&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),Y.setSIWX(new r))}}async openSend(t){let r=t.namespace||$.state.activeChain,n=this.getCaipAddress(r),o=this.getCaipNetwork(r)?.id;if(!n)throw new Error("openSend: caipAddress not found");if(o?.toString()!==t.chainId.toString()){let s=$.getCaipNetworkById(t.chainId,r);if(!s)throw new Error(`openSend: caipNetwork with chainId ${t.chainId} not found`);await this.switchNetwork(s,{throwOnFailure:!0})}try{let s=_P.getTokenSymbolByAddress(t.assetAddress);s&&await ge.fetchTokenImages([s])}catch{}return await De.open({view:"WalletSend",data:{send:t}}),new Promise((s,i)=>{let a=xt.subscribeKey("hash",d=>{d&&(u(),s({hash:d}))}),c=De.subscribe(d=>{d.open||(u(),i(new Error("Modal closed")))}),u=this.createCleanupHandler([a,c])})}toModalOptions(){function t(n){return n?.view==="Swap"}function r(n){return n?.view==="WalletSend"}return{isSwap:t,isSend:r}}async checkAllowedOrigins(){try{let t=await ge.fetchAllowedOrigins();if(!se.isClient())return;let r=window.location.origin;cl.isOriginAllowed(r,t,Z.DEFAULT_ALLOWED_ANCESTORS)||sn.open(hi.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(t){if(!(t instanceof Error))return;switch(t.message){case"RATE_LIMITED":sn.open(hi.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{let r=t.cause instanceof Error?t.cause:t;sn.open({displayMessage:hi.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:hi.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(r.message)},"error");break}default:break}}}createCleanupHandler(t){return()=>{t.forEach(r=>{try{r()}catch{}})}}sendInitializeEvent(t){let{...r}=t;delete r.adapters,delete r.universalProvider,Ae.sendEvent({type:"track",event:"INITIALIZE",properties:{...r,networks:t.networks.map(n=>n.id),siweConfig:{options:t.siweConfig?.options||{}}}})}initControllers(t){this.initializeOptionsController(t),this.initializeChainController(t),this.initializeThemeController(t),this.initializeConnectionController(t),this.initializeConnectorController()}initAdapterController(){iy.initialize(this.chainAdapters)}initializeThemeController(t){t.themeMode&&nn.setThemeMode(t.themeMode),t.themeVariables&&nn.setThemeVariables(t.themeVariables)}initializeChainController(t){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");$.initialize(t.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});let r=this.getDefaultNetwork();r&&$.setActiveCaipNetwork(r)}initializeConnectionController(t){ee.initialize(t.adapters??[]),ee.setWcBasic(t.basic??!1)}initializeConnectorController(){re.initialize(this.chainNamespaces)}initializeProjectSettings(t){Y.setProjectId(t.projectId),Y.setSdkVersion(t.sdkVersion)}initializeOptionsController(t){Y.setDebug(t.debug!==!1),Y.setEnableWalletGuide(t.enableWalletGuide!==!1),Y.setEnableWallets(t.enableWallets!==!1),Y.setEIP6963Enabled(t.enableEIP6963!==!1),Y.setEnableNetworkSwitch(t.enableNetworkSwitch!==!1),Y.setEnableReconnect(t.enableReconnect!==!1),Y.setEnableMobileFullScreen(t.enableMobileFullScreen===!0),Y.setCoinbasePreference(t.coinbasePreference),Y.setEnableAuthLogger(t.enableAuthLogger!==!1),Y.setCustomRpcUrls(t.customRpcUrls),Y.setEnableEmbedded(t.enableEmbedded),Y.setAllWallets(t.allWallets),Y.setIncludeWalletIds(t.includeWalletIds),Y.setExcludeWalletIds(t.excludeWalletIds),Y.setFeaturedWalletIds(t.featuredWalletIds),Y.setTokens(t.tokens),Y.setTermsConditionsUrl(t.termsConditionsUrl),Y.setPrivacyPolicyUrl(t.privacyPolicyUrl),Y.setCustomWallets(t.customWallets),Y.setFeatures(t.features),Y.setAllowUnsupportedChain(t.allowUnsupportedChain),Y.setUniversalProviderConfigOverride(t.universalProviderConfigOverride),Y.setPreferUniversalLinks(t.experimental_preferUniversalLinks),Y.setDefaultAccountTypes(t.defaultAccountTypes);let r=this.getDefaultMetaData();if(!t.metadata&&r&&(t.metadata=r),Y.setMetadata(t.metadata),Y.setDisableAppend(t.disableAppend),Y.setEnableEmbedded(t.enableEmbedded),Y.setSIWX(t.siwx),this.features=Y.state.features??{},!t.projectId){sn.open(hi.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(t.adapters?.find(o=>o.namespace===Z.CHAIN.EVM)&&t.siweConfig){if(t.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");Y.setSIWX(t.siweConfig.mapToSIWX())}}getDefaultMetaData(){return se.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(t){let r=this.getActiveChainNamespace();if(r){let n=Du.getUnsupportedNetwork(`${r}:${t}`);$.setActiveCaipNetwork(n)}}getDefaultNetwork(){return Du.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(t,r){return Du.extendCaipNetwork(t,{customNetworkImageUrls:r.chainImages,projectId:r.projectId})}extendCaipNetworks(t){return Du.extendCaipNetworks(t.networks,{customNetworkImageUrls:t.chainImages,customRpcUrls:t.customRpcUrls,projectId:t.projectId})}extendDefaultCaipNetwork(t){let r=t.networks.find(o=>o.id===t.defaultNetwork?.id);return r?Du.extendCaipNetwork(r,{customNetworkImageUrls:t.chainImages,customRpcUrls:t.customRpcUrls,projectId:t.projectId}):void 0}async disconnectConnector(t,r){try{this.setLoading(!0,t);let n={connections:[]},o=this.getAdapter(t);return($.state.chains.get(t)?.accountState?.caipAddress||!Y.state.enableReconnect)&&o?.disconnect&&(n=await o.disconnect({id:r})),this.setLoading(!1,t),n}catch(n){throw this.setLoading(!1,t),new Error(`Failed to disconnect chains: ${n.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{let t=$.state.activeChain,r=this.getAdapter(t),n=this.getCaipNetwork(t)?.id,o=ee.getConnections(t),s=this.remoteFeatures.multiWallet,i=o.length>0;if(!r)throw new Error("Adapter not found");let a=await r.connectWalletConnect(n);(!i||!s)&&this.close(),this.setClientId(a?.clientId||null),de.setConnectedNamespaces([...$.state.chains.keys()]),await this.syncWalletConnectAccount(),await _o.initializeIfEnabled()},connectExternal:async t=>{let r=await this.onConnectExternal(t);return await this.connectInactiveNamespaces(t,r),r?{address:r.address}:void 0},reconnectExternal:async({id:t,info:r,type:n,provider:o})=>{let s=$.state.activeChain,i=this.getAdapter(s);if(!s)throw new Error("reconnectExternal: namespace not found");if(!i)throw new Error("reconnectExternal: adapter not found");i?.reconnect&&(await i?.reconnect({id:t,info:r,type:n,provider:o,chainId:this.getCaipNetwork()?.id}),de.addConnectedNamespace(s),this.syncConnectedWalletInfo(s))},disconnectConnector:async t=>{await this.disconnectConnector(t.namespace,t.id)},disconnect:async t=>{let{id:r,chainNamespace:n,initialDisconnect:o}=t||{},s=n||$.state.activeChain,i=re.getConnectorId(s),a=r===Z.CONNECTOR_ID.AUTH||i===Z.CONNECTOR_ID.AUTH,c=r===Z.CONNECTOR_ID.WALLET_CONNECT||i===Z.CONNECTOR_ID.WALLET_CONNECT;try{let u=Array.from($.state.chains.keys()),d=n?[n]:u;(c||a)&&(d=u);let f=d.map(async y=>{let w=re.getConnectorId(y),x=r||w,v=await this.disconnectConnector(y,x);v&&(a&&de.deleteConnectedSocialProvider(),v.connections.forEach(T=>{de.addDisconnectedConnectorId(T.connectorId,y)})),o&&this.onDisconnectNamespace({chainNamespace:y,closeModal:!1})}),p=await Promise.allSettled(f);xt.resetSend(),ee.resetWcConnection(),_o.getSIWX()?.signOutOnDisconnect&&await _o.clearSessions(),re.setFilterByNamespace(void 0),ee.syncStorageConnections();let h=p.filter(y=>y.status==="rejected");if(h.length>0)throw new Error(h.map(y=>y.reason.message).join(", "));Ae.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(u){throw new Error(`Failed to disconnect chains: ${u.message}`)}},checkInstalled:t=>t?t.some(r=>!!window.ethereum?.[String(r)]):!!window.ethereum,signMessage:async t=>{let r=$.state.activeChain,n=this.getAdapter($.state.activeChain);if(!r)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");let o=this.getAddress(r);if(!o)throw new Error("signMessage: address not found");return(await n?.signMessage({message:t,address:o,provider:ar.getProvider(r)}))?.signature||""},sendTransaction:async t=>{let r=t.chainNamespace;if(!r)throw new Error("sendTransaction: namespace not found");if(Ye.SEND_SUPPORTED_NAMESPACES.includes(r)){let n=this.getAdapter(r);if(!n)throw new Error("sendTransaction: adapter not found");let o=ar.getProvider(r);return(await n?.sendTransaction({...t,caipNetwork:this.getCaipNetwork(),provider:o}))?.hash||""}return""},estimateGas:async t=>{let r=t.chainNamespace;if(r===Z.CHAIN.EVM){let n=this.getAdapter(r);if(!n)throw new Error("estimateGas: adapter is required but got undefined");let o=ar.getProvider(r),s=this.getCaipNetwork();if(!s)throw new Error("estimateGas: caipNetwork is required but got undefined");return(await n?.estimateGas({...t,provider:o,caipNetwork:s}))?.gas||0n}return 0n},getEnsAvatar:async()=>{let t=$.state.activeChain;if(!t)throw new Error("getEnsAvatar: namespace is required but got undefined");let r=this.getAddress(t);if(!r)throw new Error("getEnsAvatar: address not found");return await this.syncIdentity({address:r,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:t}),$.getAccountData()?.profileImage||!1},getEnsAddress:async t=>await cl.resolveReownName(t),writeContract:async t=>{let r=$.state.activeChain,n=this.getAdapter(r);if(!r)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");let o=this.getCaipNetwork(),s=this.getCaipAddress(),i=ar.getProvider(r);if(!o||!s)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await n?.writeContract({...t,caipNetwork:o,provider:i,caipAddress:s}))?.hash},writeSolanaTransaction:async t=>{let r=$.state.activeChain,n=this.getAdapter(r);if(!r)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");let o=this.getCaipNetwork(),s=this.getCaipAddress(),i=ar.getProvider(r);if(!o||!s)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await n?.writeSolanaTransaction({...t,caipNetwork:o,provider:i,caipAddress:s}))?.hash},parseUnits:(t,r)=>{let n=this.getAdapter($.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return n?.parseUnits({value:t,decimals:r})??0n},formatUnits:(t,r)=>{let n=this.getAdapter($.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return n?.formatUnits({value:t,decimals:r})??"0"},getCapabilities:async t=>{let r=this.getAdapter($.state.activeChain);if(!r)throw new Error("getCapabilities: adapter is required but got undefined");return await r?.getCapabilities(t)},grantPermissions:async t=>{let r=this.getAdapter($.state.activeChain);if(!r)throw new Error("grantPermissions: adapter is required but got undefined");return await r?.grantPermissions(t)},revokePermissions:async t=>{let r=this.getAdapter($.state.activeChain);if(!r)throw new Error("revokePermissions: adapter is required but got undefined");return r?.revokePermissions?await r.revokePermissions(t):"0x"},walletGetAssets:async t=>{let r=this.getAdapter($.state.activeChain);if(!r)throw new Error("walletGetAssets: adapter is required but got undefined");return await r?.walletGetAssets(t)??{}},updateBalance:t=>{let r=this.getAddress(t),n=this.getCaipNetwork(t);!n||!r||this.updateNativeBalance(r,n?.id,t)}},ee.setClient(this.connectionControllerClient)}async onConnectExternal(t){let r=$.state.activeChain,n=t.chain||r,o=this.getAdapter(n),s=!0;if(t.type===Br.CONNECTOR_TYPE_AUTH&&Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(f=>re.getConnectorId(f)===Z.CONNECTOR_ID.AUTH)&&t.chain!==r&&(s=!1),t.chain&&t.chain!==r&&!t.caipNetwork){let u=this.getCaipNetworks().find(d=>d.chainNamespace===t.chain);u&&s&&this.setCaipNetwork(u)}if(!n)throw new Error("connectExternal: namespace not found");if(!o)throw new Error("connectExternal: adapter not found");let i=this.getCaipNetwork(n),a=t.caipNetwork||i,c=await o.connect({id:t.id,address:t.address,info:t.info,type:t.type,provider:t.provider,socialUri:t.socialUri,chainId:t.caipNetwork?.id||i?.id,rpcUrl:t.caipNetwork?.rpcUrls?.default?.http?.[0]||i?.rpcUrls?.default?.http?.[0]});if(c)return de.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),de.removeDisconnectedConnectorId(t.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(t,r){let n=t.type===Br.CONNECTOR_TYPE_AUTH,o=an.getOtherAuthNamespaces(r?.connectedCaipNetwork?.chainNamespace),s=$.state.activeCaipNetwork,i=this.getAdapter(s?.chainNamespace);n&&(await Promise.all(o.map(async a=>{try{let c=ar.getProvider(a),u=this.getCaipNetwork(a);await this.getAdapter(a)?.connect({...t,provider:c,socialUri:void 0,chainId:u?.id,rpcUrl:u?.rpcUrls?.default?.http?.[0]})&&(de.addConnectedNamespace(a),de.removeDisconnectedConnectorId(t.id,a),this.setStatus("connected",a),this.syncConnectedWalletInfo(a))}catch(c){sn.warn(hi.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,hi.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(a,c instanceof Error?c.message:void 0),hi.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),s&&await i?.switchNetwork({caipNetwork:s}))}getApprovedCaipNetworksData(){if(ar.getProviderId($.state.activeChain)===Br.CONNECTOR_TYPE_WALLET_CONNECT){let r=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(r)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(t){let r=t.chainNamespace;if(this.getAddressByChainNamespace(t.chainNamespace)){let o=ar.getProviderId(r);if(t.chainNamespace===$.state.activeChain)await this.getAdapter(r)?.switchNetwork({caipNetwork:t});else if(this.setCaipNetwork(t),o===Br.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{let s=this.getAddressByChainNamespace(r);s&&this.syncAccount({address:s,chainId:t.id,chainNamespace:r})}}else this.setCaipNetwork(t)}getChainsFromNamespaces(t={}){return Object.values(t).flatMap(r=>{let n=r.chains||[],o=r.accounts.map(s=>{let{chainId:i,chainNamespace:a}=lt.parseCaipAddress(s);return`${a}:${i}`});return Array.from(new Set([...n,...o]))})}createAdapters(t){return this.createClients(),this.chainNamespaces.reduce((r,n)=>{let o=t?.find(s=>s.namespace===n);return o?(o.construct({namespace:n,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:s})=>s===n)}),r[n]=o):r[n]=new PP({namespace:n,networks:this.getCaipNetworks()}),r},{})}async initChainAdapter(t){this.onConnectors(t),this.listenAdapter(t);let r=this.getAdapter(t);if(!r)throw new Error("adapter not found");await r.syncConnectors(),await this.createUniversalProviderForAdapter(t)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async t=>{await this.initChainAdapter(t)})),this.initAdapterController()}onConnectors(t){this.getAdapter(t)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(t){let r=this.getAdapter(t);if(!r)return;let n=de.getConnectionStatus();Y.state.enableReconnect===!1?this.setStatus("disconnected",t):n==="connected"?this.setStatus("connecting",t):n==="disconnected"?(de.clearAddressCache(),this.setStatus(n,t)):this.setStatus(n,t),r.on("switchNetwork",({address:o,chainId:s})=>{let i=this.getCaipNetworks().find(u=>u.id.toString()===s.toString()||u.caipNetworkId.toString()===s.toString()),a=$.state.activeChain===t,c=$.state.chains.get(t)?.accountState?.address;if(i){let u=a&&o?o:c;u&&this.syncAccount({address:u,chainId:i.id,chainNamespace:t})}else this.setUnsupportedNetwork(s)}),r.on("disconnect",()=>{let o=this.remoteFeatures.multiWallet,s=Array.from(ee.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:t,closeModal:!o||s.length===0})}),r.on("connections",o=>{this.setConnections(o,t)}),r.on("pendingTransactions",()=>{let o=this.getAddress(t),s=$.state.activeCaipNetwork;!o||!s?.id||this.updateNativeBalance(o,s.id,s.chainNamespace)}),r.on("accountChanged",({address:o,chainId:s,connector:i})=>{this.handlePreviousConnectorConnection(i);let a=$.state.activeChain===t;i?.provider&&(this.syncProvider({id:i.id,type:i.type,provider:i?.provider,chainNamespace:t}),this.syncConnectedWalletInfo(t));let c=$.getNetworkData(t)?.caipNetwork?.id,u=s||c;a&&u?this.syncAccount({address:o,chainId:u,chainNamespace:t}):!a&&u?(this.syncAccountInfo(o,u,t),this.syncBalance({address:o,chainId:u,chainNamespace:t})):this.syncAccountInfo(o,s,t),de.addConnectedNamespace(t)})}async handlePreviousConnectorConnection(t){let r=t?.chain,n=t?.id,o=re.getConnectorId(r),s=Y.state.remoteFeatures?.multiWallet,a=r&&n&&o&&o!==n&&!s;try{a&&await ee.disconnect({id:o,namespace:r})}catch(c){console.warn("Error disconnecting previous connector",c)}}async createUniversalProviderForAdapter(t){await this.getUniversalProvider(),this.universalProvider&&await this.chainAdapters?.[t]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(t=>this.syncNamespaceConnection(t)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(t=>ee.disconnect({namespace:t,initialDisconnect:!0})))}catch(t){console.error("Error disconnecting existing connections:",t)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();let t=this.getAddress();this.getCaipAddress()||de.deleteRecentWallet();let r=de.getRecentWallet();Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:se.isMobile()?"mobile":"qrcode",name:r?.name||"Unknown",reconnect:!0,view:J.state.view,walletRank:r?.order}})}async syncNamespaceConnection(t){try{t===Z.CHAIN.EVM&&se.isSafeApp()&&re.setConnectorId(Z.CONNECTOR_ID.SAFE,t);let r=re.getConnectorId(t);switch(this.setStatus("connecting",t),r){case Z.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case Z.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(t)}}catch(r){console.warn("AppKit couldn't sync existing connection",r),this.setStatus("disconnected",t)}}onDisconnectNamespace(t){let{chainNamespace:r,closeModal:n}=t||{};$.resetAccount(r),$.resetNetwork(r),de.removeConnectedNamespace(r);let o=Array.from($.state.chains.keys());(r?[r]:o).forEach(i=>de.addDisconnectedConnectorId(re.getConnectorId(i)||"",i)),re.removeConnectorId(r),ar.resetChain(r),this.setUser(null,r),this.setStatus("disconnected",r),this.setConnectedWalletInfo(null,r),n!==!1&&De.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(t=>{let r=this.getAdapter(t),n=this.getCaipAddress(t),o=this.getCaipNetwork(t);return r?.syncConnections({connectToFirstConnector:!n,caipNetwork:o})}))}async syncAdapterConnection(t){let r=this.getAdapter(t),n=this.getCaipNetwork(t),o=re.getConnectorId(t),i=re.getConnectors(t).find(a=>a.id===o);try{if(!r||!i)throw new Error(`Adapter or connector not found for namespace ${t}`);if(!n?.id)throw new Error("CaipNetwork not found");let a=await r?.syncConnection({namespace:t,id:i.id,chainId:n.id,rpcUrl:n?.rpcUrls?.default?.http?.[0]});a?(this.syncProvider({...a,chainNamespace:t}),await this.syncAccount({...a,chainNamespace:t}),this.setStatus("connected",t),Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:a.address,properties:{method:"browser",name:i.info?.name||i.name||"Unknown",reconnect:!0,view:J.state.view,walletRank:i?.explorerWallet?.order}})):this.setStatus("disconnected",t)}catch{this.onDisconnectNamespace({chainNamespace:t,closeModal:!1})}}async syncWalletConnectAccount(){let t=Object.keys(this.universalProvider?.session?.namespaces||{}),r=this.chainNamespaces.map(async n=>{let o=this.getAdapter(n);if(!o)return;let s=this.universalProvider?.session?.namespaces?.[n]?.accounts||[],i=$.state.activeCaipNetwork?.id,a=s.find(u=>{let{chainId:d}=lt.parseCaipAddress(u);return d===i?.toString()})||s[0];if(a){let u=lt.validateCaipAddress(a),{chainId:d,address:f}=lt.parseCaipAddress(u);if(ar.setProviderId(n,Br.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&$.state.activeCaipNetwork&&o.namespace!==Z.CHAIN.EVM){let p=o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:$.state.activeCaipNetwork});ar.setProvider(n,p)}else ar.setProvider(n,this.universalProvider);re.setConnectorId(Z.CONNECTOR_ID.WALLET_CONNECT,n),de.addConnectedNamespace(n),await this.syncAccount({address:f,chainId:d,chainNamespace:n})}else t.includes(n)&&this.setStatus("disconnected",n);let c=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(n),$.setApprovedCaipNetworksData(n,{approvedCaipNetworkIds:c.approvedCaipNetworkIds,supportsAllNetworks:c.supportsAllNetworks})});await Promise.all(r)}syncProvider({type:t,provider:r,id:n,chainNamespace:o}){ar.setProviderId(o,t),ar.setProvider(o,r),re.setConnectorId(n,o)}async syncAccount(t){let r=t.chainNamespace===$.state.activeChain,n=$.getCaipNetworkByNamespace(t.chainNamespace,t.chainId),{address:o,chainId:s,chainNamespace:i}=t,{chainId:a}=de.getActiveNetworkProps(),c=n?.id||a,u=$.state.activeCaipNetwork?.name===Z.UNSUPPORTED_NETWORK_NAME,d=$.getNetworkProp("supportsAllNetworks",i);if(this.setStatus("connected",i),!(u&&!d)&&c){let f=this.getCaipNetworks().find(w=>w.id.toString()===c.toString()),p=this.getCaipNetworks().find(w=>w.chainNamespace===i);if(!d&&!f&&!p){let w=this.getApprovedCaipNetworkIds()||[],x=w.find(T=>lt.parseCaipNetworkId(T)?.chainId===c.toString()),v=w.find(T=>lt.parseCaipNetworkId(T)?.chainNamespace===i);f=this.getCaipNetworks().find(T=>T.caipNetworkId===x),p=this.getCaipNetworks().find(T=>T.caipNetworkId===v||"deprecatedCaipNetworkId"in T&&T.deprecatedCaipNetworkId===v)}let h=f||p;h?.chainNamespace===$.state.activeChain?Y.state.enableNetworkSwitch&&!Y.state.allowUnsupportedChain&&$.state.activeCaipNetwork?.name===Z.UNSUPPORTED_NETWORK_NAME?$.showUnsupportedChainUI():this.setCaipNetwork(h):r||n&&this.setCaipNetworkOfNamespace(n,i),this.syncConnectedWalletInfo(i);let y=this.getAddress(i);an.isLowerCaseMatch(o,y)||this.syncAccountInfo(o,h?.id,i),r?await this.syncBalance({address:o,chainId:h?.id,chainNamespace:i}):await this.syncBalance({address:o,chainId:n?.id,chainNamespace:i}),this.syncIdentity({address:o,chainId:s,chainNamespace:i})}}async syncAccountInfo(t,r,n){let o=this.getCaipAddress(n),s=r||o?.split(":")[1];if(!s)return;let i=`${n}:${s}:${t}`;this.setCaipAddress(i,n,!0),await this.syncIdentity({address:t,chainId:s,chainNamespace:n})}async syncReownName(t,r){try{let n=await this.getReownName(t);if(n[0]){let o=n[0];this.setProfileName(o.name,r)}else this.setProfileName(null,r)}catch{this.setProfileName(null,r)}}syncConnectedWalletInfo(t){let r=re.getConnectorId(t),n=ar.getProviderId(t);if(n===Br.CONNECTOR_TYPE_ANNOUNCED||n===Br.CONNECTOR_TYPE_INJECTED){if(r){let s=this.getConnectors().find(i=>{let a=i.id===r,c=i.info?.rdns===r,u=i.connectors?.some(d=>d.id===r||d.info?.rdns===r);return a||c||!!u});if(s){let{info:i,name:a,imageUrl:c}=s,u=c||this.getConnectorImage(s);this.setConnectedWalletInfo({name:a,icon:u,...i},t)}}}else if(n===Br.CONNECTOR_TYPE_WALLET_CONNECT){let o=ar.getProvider(t);o?.session&&this.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0]},t)}else if(r&&(r===Z.CONNECTOR_ID.COINBASE_SDK||r===Z.CONNECTOR_ID.COINBASE)){let o=this.getConnectors().find(c=>c.id===r),s=o?.name||"Coinbase Wallet",i=o?.imageUrl||this.getConnectorImage(o),a=o?.info;this.setConnectedWalletInfo({...a,name:s,icon:i},t)}}async syncBalance(t){!V1.getNetworksByNamespace(this.getCaipNetworks(),t.chainNamespace).find(n=>n.id.toString()===t.chainId?.toString())||!t.chainId||await this.updateNativeBalance(t.address,t.chainId,t.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(t,r,n){let o=this.getAdapter(n),s=$.getCaipNetworkByNamespace(n,r);if(o){let i=await o.getBalance({address:t,chainId:r,caipNetwork:s,tokens:this.options.tokens});return this.setBalance(i.balance,i.symbol,n),i}}async initializeUniversalAdapter(){let t=YV.createLogger((o,...s)=>{o&&this.handleAlertError(o),console.error(...s)}),r={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:t};Y.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await dP.init(r);let n=this.universalProvider.disconnect.bind(this.universalProvider);this.universalProvider.disconnect=async()=>{try{return await n()}catch(o){if(o instanceof Error&&o.message.includes("Missing or invalid. Record was recently deleted"))return;throw o}},Y.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(t=>{cl.listenWcProvider({universalProvider:this.universalProvider,namespace:t,onDisplayUri:r=>{ee.setUri(r)},onConnect:r=>{let{address:n}=se.getAccount(r[0]);for(let o of this.chainNamespaces)de.removeDisconnectedConnectorId(Z.CONNECTOR_ID.WALLET_CONNECT,o);ee.finalizeWcConnection(n)},onDisconnect:()=>{$.state.noAdapters&&this.resetAccount(t),ee.resetWcConnection()},onChainChanged:r=>{let n=$.state.activeChain,o=n&&re.state.activeConnectorIds[n]===Z.CONNECTOR_ID.WALLET_CONNECT;if(n===t&&($.state.noAdapters||o)){let s=this.getCaipNetworks().find(a=>a.id.toString()===r.toString()||a.caipNetworkId.toString()===r.toString()),i=this.getCaipNetwork();if(!s){this.setUnsupportedNetwork(r);return}i?.id.toString()!==s?.id.toString()&&i?.chainNamespace===s?.chainNamespace&&this.setCaipNetwork(s)}},onAccountsChanged:r=>{let n=$.state.activeChain,o=n&&re.state.activeConnectorIds[n]===Z.CONNECTOR_ID.WALLET_CONNECT;if(n===t&&($.state.noAdapters||o)){let s=r?.[0];s&&this.syncAccount({address:s.address,chainId:s.chainId,chainNamespace:s.chainNamespace})}}})})}createUniversalProvider(){return!this.universalProviderInitPromise&&se.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(t){Ae.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:t instanceof Error?t.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",t)}return this.universalProvider}getDisabledCaipNetworks(){let t=$.getAllApprovedCaipNetworkIds(),r=$.getAllRequestedCaipNetworks();return se.sortRequestedNetworks(t,r).filter(o=>$.isCaipNetworkDisabled(o))}handleAlertError(t){let r=Object.entries(hi.UniversalProviderErrors).find(([,{message:a}])=>t.message.includes(a)),[n,o]=r??[],{message:s,alertErrorKey:i}=o??{};if(n&&s&&!this.reportedAlertErrors[n]){let a=hi.ALERT_ERRORS[i];a&&(sn.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(t){if(t)return this.chainAdapters?.[t]}createAdapter(t){if(!t)return;let r=t.namespace;if(!r)return;this.createClients();let n=t;n.namespace=r,n.construct({namespace:r,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:o})=>o===r)}),this.chainNamespaces.includes(r)||this.chainNamespaces.push(r),this.chainAdapters&&(this.chainAdapters[r]=n)}async open(t){await this.injectModalUi(),t?.uri&&ee.setUri(t.uri);let{isSwap:r,isSend:n}=this.toModalOptions();return r(t)?De.open({...t,data:{swap:t.arguments}}):n(t)&&t.arguments?this.openSend(t.arguments):De.open(t)}async close(){await this.injectModalUi(),De.close()}setLoading(t,r){De.setLoading(t,r)}async disconnect(t){await ee.disconnect({namespace:t})}getSIWX(){return Y.state.siwx}getError(){return""}getChainId(){return $.state.activeCaipNetwork?.id}async switchNetwork(t,{throwOnFailure:r=!1}={}){let n=this.getCaipNetworks().find(o=>o.id===t.id);if(!n){sn.open(hi.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await $.switchActiveNetwork(n,{throwOnFailure:r})}getWalletProvider(){return $.state.activeChain?ar.state.providers[$.state.activeChain]:null}getWalletProviderType(){return ar.getProviderId($.state.activeChain)}subscribeProviders(t){return ar.subscribeProviders(t)}getThemeMode(){return nn.state.themeMode}getThemeVariables(){return nn.state.themeVariables}setThemeMode(t){nn.setThemeMode(t),rv(nn.state.themeMode)}setTermsConditionsUrl(t){Y.setTermsConditionsUrl(t)}setPrivacyPolicyUrl(t){Y.setPrivacyPolicyUrl(t)}setThemeVariables(t){nn.setThemeVariables(t),GV(nn.state.themeVariables)}subscribeTheme(t){return nn.subscribe(t)}subscribeConnections(t){return this.remoteFeatures.multiWallet?ee.subscribe(t):(sn.open(Z.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(t){return t?$.state.chains.get(t)?.accountState?.connectedWalletInfo:$.getAccountData()?.connectedWalletInfo}getAccount(t){let r=t||$.state.activeChain,n=re.getAuthConnector(r),o=$.getAccountData(r),s=de.getConnectedConnectorId($.state.activeChain),i=ee.getConnections(r);if(!r)throw new Error("AppKit:getAccount - namespace is required");let a=i.flatMap(c=>c.accounts.map(({address:u,type:d,publicKey:f})=>se.createAccount(r,u,d||"eoa",f)));if(o)return{allAccounts:a,caipAddress:o.caipAddress,address:se.getPlainAddress(o.caipAddress),isConnected:!!o.caipAddress,status:o.status,embeddedWalletInfo:n&&s===Z.CONNECTOR_ID.AUTH?{user:o.user?{...o.user,username:de.getConnectedSocialUsername()}:void 0,authProvider:o.socialProvider||"email",accountType:Fr(r),isSmartAccountDeployed:!!o.smartAccountDeployed}:void 0}}subscribeAccount(t,r){let n=[],o=()=>{let i=this.getAccount(r);i&&t(i)};if(r){let i=$.subscribeChainProp("accountState",o,r);n.push(i)}else{let i=$.subscribe(o);n.push(i)}let s=re.subscribe(o);return n.push(s),()=>{n.forEach(i=>i())}}subscribeNetwork(t){return $.subscribe(({activeCaipNetwork:r})=>{t({caipNetwork:r,chainId:r?.id,caipNetworkId:r?.caipNetworkId})})}subscribeWalletInfo(t,r){return r?$.subscribeChainProp("accountState",n=>t(n?.connectedWalletInfo),r):$.subscribeChainProp("accountState",n=>t(n?.connectedWalletInfo))}subscribeShouldUpdateToAddress(t){return $.subscribeChainProp("accountState",r=>t(r?.shouldUpdateToAddress))}subscribeCaipNetworkChange(t){return $.subscribeKey("activeCaipNetwork",t)}getState(){return ws.state}getRemoteFeatures(){return Y.state.remoteFeatures}subscribeState(t){return ws.subscribe(t)}subscribeRemoteFeatures(t){return Y.subscribeKey("remoteFeatures",t)}showErrorMessage(t){Je.showError(t)}showSuccessMessage(t){Je.showSuccess(t)}getEvent(){return{...Ae.state}}subscribeEvents(t){return Ae.subscribe(t)}replace(t){J.replace(t)}redirect(t){J.push(t)}popTransactionStack(t){J.popTransactionStack(t)}isOpen(){return De.state.open}isTransactionStackEmpty(){return J.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(t){Y.setFeatures(t)}updateRemoteFeatures(t){Y.setRemoteFeatures(t)}updateOptions(t){let n={...Y.state||{},...t};Y.setOptions(n)}setConnectMethodsOrder(t){Y.setConnectMethodsOrder(t)}setWalletFeaturesOrder(t){Y.setWalletFeaturesOrder(t)}setCollapseWallets(t){Y.setCollapseWallets(t)}setSocialsOrder(t){Y.setSocialsOrder(t)}getConnectMethodsOrder(){return ys.getConnectOrderMethod(Y.state.features,re.getConnectors())}addNetwork(t,r){if(this.chainAdapters&&!this.chainAdapters[t])throw new Error(`Adapter for namespace ${t} doesn't exist`);let n=this.extendCaipNetwork(r,this.options);this.getCaipNetworks().find(o=>o.id===n.id)||$.addNetwork(n)}removeNetwork(t,r){if(this.chainAdapters&&!this.chainAdapters[t])throw new Error(`Adapter for namespace ${t} doesn't exist`);this.getCaipNetworks().find(o=>o.id===r)&&$.removeNetwork(t,r)}}});var Twe=b(()=>{l();});function q(e){return(t,r)=>typeof r=="object"?UJe(e,t,r):((n,o,s)=>{let i=o.hasOwnProperty(s);return o.constructor.createProperty(s,n),i?Object.getOwnPropertyDescriptor(o,s):void 0})(e,t,r)}var kJe,UJe,tj=b(()=>{l();Y5();kJe={attribute:!0,type:String,converter:G5,reflect:!1,hasChanged:gP},UJe=(e=kJe,t,r)=>{let{kind:n,metadata:o}=r,s=globalThis.litPropertyMetadata.get(o);if(s===void 0&&globalThis.litPropertyMetadata.set(o,s=new Map),n==="setter"&&((e=Object.create(e)).wrapped=!0),s.set(r.name,e),n==="accessor"){let{name:i}=r;return{set(a){let c=t.get.call(this);t.set.call(this,a),this.requestUpdate(i,c,e,!0,a)},init(a){return a!==void 0&&this.C(i,void 0,e,a),a}}}if(n==="setter"){let{name:i}=r;return function(a){let c=this[i];t.call(this,a),this.requestUpdate(i,c,e,!0,a)}}throw Error("Unsupported decorator location: "+n)}});function le(e){return q({...e,state:!0,attribute:!1})}var _we=b(()=>{l();tj();});var Pwe=b(()=>{l();});var yx=b(()=>{l();});var Nwe=b(()=>{l();yx();});var Rwe=b(()=>{l();yx();});var Owe=b(()=>{l();yx();});var Bwe=b(()=>{l();yx();});var kwe=b(()=>{l();yx();});var $e=b(()=>{l();Twe();tj();_we();Pwe();Nwe();Rwe();Owe();Bwe();kwe()});var Uwe,Dwe=b(()=>{l();he();Uwe=Er` + :host { + display: flex; + width: inherit; + height: inherit; + box-sizing: border-box; + } +`});var Gi,Ns,$y=b(()=>{l();he();$e();Mt();gx();Bt();Dwe();Gi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ns=class extends ie{render(){return this.style.cssText=` + flex-direction: ${this.flexDirection}; + flex-wrap: ${this.flexWrap}; + flex-basis: ${this.flexBasis}; + flex-grow: ${this.flexGrow}; + flex-shrink: ${this.flexShrink}; + align-items: ${this.alignItems}; + justify-content: ${this.justifyContent}; + column-gap: ${this.columnGap&&`var(--apkt-spacing-${this.columnGap})`}; + row-gap: ${this.rowGap&&`var(--apkt-spacing-${this.rowGap})`}; + gap: ${this.gap&&`var(--apkt-spacing-${this.gap})`}; + padding-top: ${this.padding&&hr.getSpacingStyles(this.padding,0)}; + padding-right: ${this.padding&&hr.getSpacingStyles(this.padding,1)}; + padding-bottom: ${this.padding&&hr.getSpacingStyles(this.padding,2)}; + padding-left: ${this.padding&&hr.getSpacingStyles(this.padding,3)}; + margin-top: ${this.margin&&hr.getSpacingStyles(this.margin,0)}; + margin-right: ${this.margin&&hr.getSpacingStyles(this.margin,1)}; + margin-bottom: ${this.margin&&hr.getSpacingStyles(this.margin,2)}; + margin-left: ${this.margin&&hr.getSpacingStyles(this.margin,3)}; + width: ${this.width}; + `,V``}};Ns.styles=[Me,Uwe];Gi([q()],Ns.prototype,"flexDirection",void 0);Gi([q()],Ns.prototype,"flexWrap",void 0);Gi([q()],Ns.prototype,"flexBasis",void 0);Gi([q()],Ns.prototype,"flexGrow",void 0);Gi([q()],Ns.prototype,"flexShrink",void 0);Gi([q()],Ns.prototype,"alignItems",void 0);Gi([q()],Ns.prototype,"justifyContent",void 0);Gi([q()],Ns.prototype,"columnGap",void 0);Gi([q()],Ns.prototype,"rowGap",void 0);Gi([q()],Ns.prototype,"gap",void 0);Gi([q()],Ns.prototype,"padding",void 0);Gi([q()],Ns.prototype,"margin",void 0);Gi([q()],Ns.prototype,"width",void 0);Ns=Gi([ne("wui-flex")],Ns)});var jr=b(()=>{l();$y()});var Ce,Lwe=b(()=>{l();Up();Ce=e=>e??hn});var kr=b(()=>{l();Lwe()});var Hwe,DJe,$we,Mwe,rj,nj,T0r,_0r,Fwe=b(()=>{l();Up();Hwe=Symbol.for(""),DJe=e=>{if(e?.r===Hwe)return e?._$litStatic$},$we=e=>({_$litStatic$:e,r:Hwe}),Mwe=new Map,rj=e=>(t,...r)=>{let n=r.length,o,s,i=[],a=[],c,u=0,d=!1;for(;u{l();Fwe()});var Vwe,jwe=b(()=>{l();he();Vwe=He` + + + + + + + + + + + + + +`});var qwe,Wwe=b(()=>{l();he();qwe=He` + + + + + + + + + + + + + +`});var Kwe,Zwe=b(()=>{l();he();Kwe=He` + + + +`});var Gwe,Ywe=b(()=>{l();he();Gwe=He` + + +`});var Jwe,Qwe=b(()=>{l();he();Jwe=He` + + + + + + + + + + + + + + + + + + + +`});var Xwe,ebe=b(()=>{l();he();Xwe=He` + + +`});var tbe,rbe=b(()=>{l();he();tbe=He` + +`});var nbe,obe=b(()=>{l();he();nbe=He` + + + + + + + + + + +`});var sbe,ibe=b(()=>{l();he();sbe=He` + + +`});var abe,cbe=b(()=>{l();he();abe=He` + +`});var lbe,ube=b(()=>{l();he();lbe=He` + + + + + + + + + + + + + + + +`});var dbe,fbe=b(()=>{l();he();dbe=He` + + + + +`});var pbe,hbe=b(()=>{l();he();pbe=He` + + + + + + + + + + + + + +`});var mbe,gbe=b(()=>{l();he();mbe=He` + + + + +`});var ybe,wbe=b(()=>{l();he();ybe=He` + + +`});var bbe,xbe=b(()=>{l();he();bbe=He` + + +`});var vbe,Ebe=b(()=>{l();he();vbe=He` + + + + +`});var Abe,Cbe=b(()=>{l();he();Abe=He` + + + + + + + + + + + + +`});var Sbe,Ibe=b(()=>{l();he();Sbe=He` + + + +`});var Tbe,_be=b(()=>{l();he();Tbe=He` + + + + + + + + + + + + + + +`});var Pbe,Nbe=b(()=>{l();he();Pbe=He` + + + +`});var Rbe,Obe=b(()=>{l();he();Rbe=He` + + + + + + + + + + + + + +`});var Bbe,kbe=b(()=>{l();he();Bbe=He` + +`});var Ube,Dbe,Lbe,Mbe,Hbe=b(()=>{l();he();Ube=He` + + + +`,Dbe=He` + + + +`,Lbe=He` + + + + + + + + + + + +`,Mbe=He` + + + + + + +`});var oj,$be=b(()=>{l();he();oj=He` + + + + + + + +`});var Fbe,zbe=b(()=>{l();he();Fbe=Er` + :host { + display: flex; + justify-content: center; + align-items: center; + aspect-ratio: 1 / 1; + color: var(--local-color); + width: var(--local-width); + } + + svg { + height: inherit; + width: inherit; + object-fit: contain; + object-position: center; + } +`});var BP,kP,sj,Vbe,sv,jbe,be,qbe,ij,et=b(()=>{l();BP=globalThis,kP=BP.ShadowRoot&&(BP.ShadyCSS===void 0||BP.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,sj=Symbol(),Vbe=new WeakMap,sv=class{constructor(t,r,n){if(this._$cssResult$=!0,n!==sj)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=r}get styleSheet(){let t=this.o,r=this.t;if(kP&&t===void 0){let n=r!==void 0&&r.length===1;n&&(t=Vbe.get(r)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&Vbe.set(r,t))}return t}toString(){return this.cssText}},jbe=e=>new sv(typeof e=="string"?e:e+"",void 0,sj),be=(e,...t)=>{let r=e.length===1?e[0]:t.reduce((n,o,s)=>n+(i=>{if(i._$cssResult$===!0)return i.cssText;if(typeof i=="number")return i;throw Error("Value passed to 'css' function must be a 'css' function result: "+i+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[s+1],e[0]);return new sv(r,e,sj)},qbe=(e,t)=>{if(kP)e.adoptedStyleSheets=t.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(let r of t){let n=document.createElement("style"),o=BP.litNonce;o!==void 0&&n.setAttribute("nonce",o),n.textContent=r.cssText,e.appendChild(n)}},ij=kP?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let r="";for(let n of t.cssRules)r+=n.cssText;return jbe(r)})(e):e});var LJe,MJe,HJe,$Je,FJe,zJe,wx,Wbe,VJe,Kbe,iv,bx,av,Zbe,jJe,qJe,Lp,Gbe,Qe=b(()=>{l();et();et();({is:LJe,defineProperty:MJe,getOwnPropertyDescriptor:HJe,getOwnPropertyNames:$Je,getOwnPropertySymbols:FJe,getPrototypeOf:zJe}=Object),wx=globalThis,Wbe=wx.trustedTypes,VJe=Wbe?Wbe.emptyScript:"",Kbe=wx.reactiveElementPolyfillSupport,iv=(e,t)=>e,bx={toAttribute(e,t){switch(t){case Boolean:e=e?VJe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let r=e;switch(t){case Boolean:r=e!==null;break;case Number:r=e===null?null:Number(e);break;case Object:case Array:try{r=JSON.parse(e)}catch{r=null}}return r}},av=(e,t)=>!LJe(e,t),Zbe={attribute:!0,type:String,converter:bx,reflect:!1,hasChanged:av};(jJe=Symbol.metadata)!=null||(Symbol.metadata=Symbol("metadata")),(qJe=wx.litPropertyMetadata)!=null||(wx.litPropertyMetadata=new WeakMap);Lp=class extends HTMLElement{static addInitializer(t){var r;this._$Ei(),((r=this.l)!=null?r:this.l=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,r=Zbe){if(r.state&&(r.attribute=!1),this._$Ei(),this.elementProperties.set(t,r),!r.noAccessor){let n=Symbol(),o=this.getPropertyDescriptor(t,n,r);o!==void 0&&MJe(this.prototype,t,o)}}static getPropertyDescriptor(t,r,n){var o;let{get:s,set:i}=(o=HJe(this.prototype,t))!=null?o:{get(){return this[r]},set(a){this[r]=a}};return{get(){return s?.call(this)},set(a){let c=s?.call(this);i.call(this,a),this.requestUpdate(t,c,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){var r;return(r=this.elementProperties.get(t))!=null?r:Zbe}static _$Ei(){if(this.hasOwnProperty(iv("elementProperties")))return;let t=zJe(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(iv("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(iv("properties"))){let r=this.properties,n=[...$Je(r),...FJe(r)];for(let o of n)this.createProperty(o,r[o])}let t=this[Symbol.metadata];if(t!==null){let r=litPropertyMetadata.get(t);if(r!==void 0)for(let[n,o]of r)this.elementProperties.set(n,o)}this._$Eh=new Map;for(let[r,n]of this.elementProperties){let o=this._$Eu(r,n);o!==void 0&&this._$Eh.set(o,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let r=[];if(Array.isArray(t)){let n=new Set(t.flat(1/0).reverse());for(let o of n)r.unshift(ij(o))}else t!==void 0&&r.push(ij(t));return r}static _$Eu(t,r){let n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$ES=new Promise(r=>this.enableUpdating=r),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(r=>r(this))}addController(t){var r,n;((r=this._$EO)!=null?r:this._$EO=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&((n=t.hostConnected)==null||n.call(t))}removeController(t){var r;(r=this._$EO)==null||r.delete(t)}_$E_(){let t=new Map,r=this.constructor.elementProperties;for(let n of r.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){var t;let r=(t=this.shadowRoot)!=null?t:this.attachShadow(this.constructor.shadowRootOptions);return qbe(r,this.constructor.elementStyles),r}connectedCallback(){var t,r;(t=this.renderRoot)!=null||(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(r=this._$EO)==null||r.forEach(n=>{var o;return(o=n.hostConnected)==null?void 0:o.call(n)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$EO)==null||t.forEach(r=>{var n;return(n=r.hostDisconnected)==null?void 0:n.call(r)})}attributeChangedCallback(t,r,n){this._$AK(t,n)}_$EC(t,r){var n;let o=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,o);if(s!==void 0&&o.reflect===!0){let i=(((n=o.converter)==null?void 0:n.toAttribute)!==void 0?o.converter:bx).toAttribute(r,o.type);this._$Em=t,i==null?this.removeAttribute(s):this.setAttribute(s,i),this._$Em=null}}_$AK(t,r){var n;let o=this.constructor,s=o._$Eh.get(t);if(s!==void 0&&this._$Em!==s){let i=o.getPropertyOptions(s),a=typeof i.converter=="function"?{fromAttribute:i.converter}:((n=i.converter)==null?void 0:n.fromAttribute)!==void 0?i.converter:bx;this._$Em=s,this[s]=a.fromAttribute(r,i.type),this._$Em=null}}requestUpdate(t,r,n){var o;if(t!==void 0){if(n!=null||(n=this.constructor.getPropertyOptions(t)),!((o=n.hasChanged)!=null?o:av)(this[t],r))return;this.P(t,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,r,n){var o;this._$AL.has(t)||this._$AL.set(t,r),n.reflect===!0&&this._$Em!==t&&((o=this._$Ej)!=null?o:this._$Ej=new Set).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t,r;if(!this.isUpdatePending)return;if(!this.hasUpdated){if((t=this.renderRoot)!=null||(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[i,a]of this._$Ep)this[i]=a;this._$Ep=void 0}let s=this.constructor.elementProperties;if(s.size>0)for(let[i,a]of s)a.wrapped!==!0||this._$AL.has(i)||this[i]===void 0||this.P(i,this[i],a)}let n=!1,o=this._$AL;try{n=this.shouldUpdate(o),n?(this.willUpdate(o),(r=this._$EO)==null||r.forEach(s=>{var i;return(i=s.hostUpdate)==null?void 0:i.call(s)}),this.update(o)):this._$EU()}catch(s){throw n=!1,this._$EU(),s}n&&this._$AE(o)}willUpdate(t){}_$AE(t){var r;(r=this._$EO)==null||r.forEach(n=>{var o;return(o=n.hostUpdated)==null?void 0:o.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach(r=>this._$EC(r,this[r]))),this._$EU()}updated(t){}firstUpdated(t){}};Lp.elementStyles=[],Lp.shadowRootOptions={mode:"open"},Lp[iv("elementProperties")]=new Map,Lp[iv("finalized")]=new Map,Kbe?.({ReactiveElement:Lp}),((Gbe=wx.reactiveElementVersions)!=null?Gbe:wx.reactiveElementVersions=[]).push("2.0.4")});function l6e(e,t){if(!Array.isArray(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ybe!==void 0?Ybe.createHTML(t):t}function xx(e,t,r=e,n){var o,s,i;if(t===jy)return t;let a=n!==void 0?(o=r._$Co)==null?void 0:o[n]:r._$Cl,c=uv(t)?void 0:t._$litDirective$;return a?.constructor!==c&&((s=a?._$AO)==null||s.call(a,!1),c===void 0?a=void 0:(a=new c(e),a._$AT(e,r,n)),n!==void 0?((i=r._$Co)!=null?i:r._$Co=[])[n]=a:r._$Cl=a),a!==void 0&&(t=xx(e,a._$AS(e,t.values),a,n)),t}var UP,DP,Ybe,o6e,qm,s6e,WJe,Vy,lv,uv,i6e,KJe,aj,cv,Jbe,Qbe,Fy,Xbe,e6e,a6e,c6e,xe,z,jy,lo,t6e,zy,ZJe,dv,cj,fv,vx,lj,uj,dj,fj,r6e,n6e,u6e,tt=b(()=>{l();UP=globalThis,DP=UP.trustedTypes,Ybe=DP?DP.createPolicy("lit-html",{createHTML:e=>e}):void 0,o6e="$lit$",qm=`lit$${Math.random().toFixed(9).slice(2)}$`,s6e="?"+qm,WJe=`<${s6e}>`,Vy=document,lv=()=>Vy.createComment(""),uv=e=>e===null||typeof e!="object"&&typeof e!="function",i6e=Array.isArray,KJe=e=>i6e(e)||typeof e?.[Symbol.iterator]=="function",aj=`[ +\f\r]`,cv=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Jbe=/-->/g,Qbe=/>/g,Fy=RegExp(`>|${aj}(?:([^\\s"'>=/]+)(${aj}*=${aj}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Xbe=/'/g,e6e=/"/g,a6e=/^(?:script|style|textarea|title)$/i,c6e=e=>(t,...r)=>({_$litType$:e,strings:t,values:r}),xe=c6e(1),z=c6e(2),jy=Symbol.for("lit-noChange"),lo=Symbol.for("lit-nothing"),t6e=new WeakMap,zy=Vy.createTreeWalker(Vy,129);ZJe=(e,t)=>{let r=e.length-1,n=[],o,s=t===2?"":"",i=cv;for(let a=0;a"?(i=o??cv,f=-1):d[1]===void 0?f=-2:(f=i.lastIndex-d[2].length,u=d[1],i=d[3]===void 0?Fy:d[3]==='"'?e6e:Xbe):i===e6e||i===Xbe?i=Fy:i===Jbe||i===Qbe?i=cv:(i=Fy,o=void 0);let h=i===Fy&&e[a+1].startsWith("/>")?" ":"";s+=i===cv?c+WJe:f>=0?(n.push(u),c.slice(0,f)+o6e+c.slice(f)+qm+h):c+qm+(f===-2?a:h)}return[l6e(e,s+(e[r]||"")+(t===2?"":"")),n]},dv=class e{constructor({strings:t,_$litType$:r},n){let o;this.parts=[];let s=0,i=0,a=t.length-1,c=this.parts,[u,d]=ZJe(t,r);if(this.el=e.createElement(u,n),zy.currentNode=this.el.content,r===2){let f=this.el.content.firstChild;f.replaceWith(...f.childNodes)}for(;(o=zy.nextNode())!==null&&c.length0){o.textContent=DP?DP.emptyScript:"";for(let h=0;h2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=lo}_$AI(t,r=this,n,o){let s=this.strings,i=!1;if(s===void 0)t=xx(this,t,r,0),i=!uv(t)||t!==this._$AH&&t!==jy,i&&(this._$AH=t);else{let a=t,c,u;for(t=s[0],c=0;c{var n,o;let s=(n=r?.renderBefore)!=null?n:t,i=s._$litPart$;if(i===void 0){let a=(o=r?.renderBefore)!=null?o:null;s._$litPart$=i=new fv(t.insertBefore(lv(),a),a,void 0,r??{})}return i._$AI(e),i}});var we,d6e,f6e,p6e,st=b(()=>{l();Qe();Qe();tt();tt();we=class extends Lp{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,r;let n=super.createRenderRoot();return(r=(t=this.renderOptions).renderBefore)!=null||(t.renderBefore=n.firstChild),n}update(t){let r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=u6e(r,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)==null||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)==null||t.setConnected(!1)}render(){return jy}};we._$litElement$=!0,we.finalized=!0,(d6e=globalThis.litElementHydrateSupport)==null||d6e.call(globalThis,{LitElement:we});f6e=globalThis.litElementPolyfillSupport;f6e?.({LitElement:we});((p6e=globalThis.litElementVersions)!=null?p6e:globalThis.litElementVersions=[]).push("4.0.6")});var ve,it=b(()=>{l();ve=e=>(t,r)=>{r!==void 0?r.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)}});function K(e){return(t,r)=>typeof r=="object"?nQe(e,t,r):((n,o,s)=>{let i=o.hasOwnProperty(s);return o.constructor.createProperty(s,i?tQe(eQe({},n),{wrapped:!0}):n),i?Object.getOwnPropertyDescriptor(o,s):void 0})(e,t,r)}var GJe,YJe,JJe,h6e,QJe,XJe,m6e,eQe,tQe,rQe,nQe,at=b(()=>{l();Qe();GJe=Object.defineProperty,YJe=Object.defineProperties,JJe=Object.getOwnPropertyDescriptors,h6e=Object.getOwnPropertySymbols,QJe=Object.prototype.hasOwnProperty,XJe=Object.prototype.propertyIsEnumerable,m6e=(e,t,r)=>t in e?GJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,eQe=(e,t)=>{for(var r in t||(t={}))QJe.call(t,r)&&m6e(e,r,t[r]);if(h6e)for(var r of h6e(t))XJe.call(t,r)&&m6e(e,r,t[r]);return e},tQe=(e,t)=>YJe(e,JJe(t));rQe={attribute:!0,type:String,converter:bx,reflect:!1,hasChanged:av},nQe=(e=rQe,t,r)=>{let{kind:n,metadata:o}=r,s=globalThis.litPropertyMetadata.get(o);if(s===void 0&&globalThis.litPropertyMetadata.set(o,s=new Map),s.set(r.name,e),n==="accessor"){let{name:i}=r;return{set(a){let c=t.get.call(this);t.set.call(this,a),this.requestUpdate(i,c,e)},init(a){return a!==void 0&&this.P(i,void 0,e),a}}}if(n==="setter"){let{name:i}=r;return function(a){let c=this[i];t.call(this,a),this.requestUpdate(i,c,e)}}throw Error("Unsupported decorator location: "+n)}});var g6e={};Te(g6e,{PhArrowCircleDown:()=>Lu});var oQe,sQe,pv,Lu,y6e=b(()=>{l();Qe();tt();st();it();at();et();oQe=Object.defineProperty,sQe=Object.getOwnPropertyDescriptor,pv=(e,t,r,n)=>{for(var o=n>1?void 0:n?sQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&oQe(t,r,o),o},Lu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Lu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Lu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Lu.styles=be` + :host { + display: contents; + } + `;pv([K({type:String,reflect:!0})],Lu.prototype,"size",2);pv([K({type:String,reflect:!0})],Lu.prototype,"weight",2);pv([K({type:String,reflect:!0})],Lu.prototype,"color",2);pv([K({type:Boolean,reflect:!0})],Lu.prototype,"mirrored",2);Lu=pv([ve("ph-arrow-circle-down")],Lu)});var w6e={};Te(w6e,{PhArrowClockwise:()=>Mu});var iQe,aQe,hv,Mu,b6e=b(()=>{l();Qe();tt();st();it();at();et();iQe=Object.defineProperty,aQe=Object.getOwnPropertyDescriptor,hv=(e,t,r,n)=>{for(var o=n>1?void 0:n?aQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&iQe(t,r,o),o},Mu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Mu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Mu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Mu.styles=be` + :host { + display: contents; + } + `;hv([K({type:String,reflect:!0})],Mu.prototype,"size",2);hv([K({type:String,reflect:!0})],Mu.prototype,"weight",2);hv([K({type:String,reflect:!0})],Mu.prototype,"color",2);hv([K({type:Boolean,reflect:!0})],Mu.prototype,"mirrored",2);Mu=hv([ve("ph-arrow-clockwise")],Mu)});var x6e={};Te(x6e,{PhArrowDown:()=>Hu});var cQe,lQe,mv,Hu,v6e=b(()=>{l();Qe();tt();st();it();at();et();cQe=Object.defineProperty,lQe=Object.getOwnPropertyDescriptor,mv=(e,t,r,n)=>{for(var o=n>1?void 0:n?lQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&cQe(t,r,o),o},Hu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Hu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Hu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Hu.styles=be` + :host { + display: contents; + } + `;mv([K({type:String,reflect:!0})],Hu.prototype,"size",2);mv([K({type:String,reflect:!0})],Hu.prototype,"weight",2);mv([K({type:String,reflect:!0})],Hu.prototype,"color",2);mv([K({type:Boolean,reflect:!0})],Hu.prototype,"mirrored",2);Hu=mv([ve("ph-arrow-down")],Hu)});var E6e={};Te(E6e,{PhArrowLeft:()=>$u});var uQe,dQe,gv,$u,A6e=b(()=>{l();Qe();tt();st();it();at();et();uQe=Object.defineProperty,dQe=Object.getOwnPropertyDescriptor,gv=(e,t,r,n)=>{for(var o=n>1?void 0:n?dQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&uQe(t,r,o),o},$u=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${$u.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};$u.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);$u.styles=be` + :host { + display: contents; + } + `;gv([K({type:String,reflect:!0})],$u.prototype,"size",2);gv([K({type:String,reflect:!0})],$u.prototype,"weight",2);gv([K({type:String,reflect:!0})],$u.prototype,"color",2);gv([K({type:Boolean,reflect:!0})],$u.prototype,"mirrored",2);$u=gv([ve("ph-arrow-left")],$u)});var C6e={};Te(C6e,{PhArrowRight:()=>Fu});var fQe,pQe,yv,Fu,S6e=b(()=>{l();Qe();tt();st();it();at();et();fQe=Object.defineProperty,pQe=Object.getOwnPropertyDescriptor,yv=(e,t,r,n)=>{for(var o=n>1?void 0:n?pQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&fQe(t,r,o),o},Fu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Fu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Fu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Fu.styles=be` + :host { + display: contents; + } + `;yv([K({type:String,reflect:!0})],Fu.prototype,"size",2);yv([K({type:String,reflect:!0})],Fu.prototype,"weight",2);yv([K({type:String,reflect:!0})],Fu.prototype,"color",2);yv([K({type:Boolean,reflect:!0})],Fu.prototype,"mirrored",2);Fu=yv([ve("ph-arrow-right")],Fu)});var I6e={};Te(I6e,{PhArrowSquareOut:()=>zu});var hQe,mQe,wv,zu,T6e=b(()=>{l();Qe();tt();st();it();at();et();hQe=Object.defineProperty,mQe=Object.getOwnPropertyDescriptor,wv=(e,t,r,n)=>{for(var o=n>1?void 0:n?mQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&hQe(t,r,o),o},zu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${zu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};zu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);zu.styles=be` + :host { + display: contents; + } + `;wv([K({type:String,reflect:!0})],zu.prototype,"size",2);wv([K({type:String,reflect:!0})],zu.prototype,"weight",2);wv([K({type:String,reflect:!0})],zu.prototype,"color",2);wv([K({type:Boolean,reflect:!0})],zu.prototype,"mirrored",2);zu=wv([ve("ph-arrow-square-out")],zu)});var _6e={};Te(_6e,{PhArrowsDownUp:()=>Vu});var gQe,yQe,bv,Vu,P6e=b(()=>{l();Qe();tt();st();it();at();et();gQe=Object.defineProperty,yQe=Object.getOwnPropertyDescriptor,bv=(e,t,r,n)=>{for(var o=n>1?void 0:n?yQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&gQe(t,r,o),o},Vu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Vu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Vu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Vu.styles=be` + :host { + display: contents; + } + `;bv([K({type:String,reflect:!0})],Vu.prototype,"size",2);bv([K({type:String,reflect:!0})],Vu.prototype,"weight",2);bv([K({type:String,reflect:!0})],Vu.prototype,"color",2);bv([K({type:Boolean,reflect:!0})],Vu.prototype,"mirrored",2);Vu=bv([ve("ph-arrows-down-up")],Vu)});var N6e={};Te(N6e,{PhArrowsLeftRight:()=>ju});var wQe,bQe,xv,ju,R6e=b(()=>{l();Qe();tt();st();it();at();et();wQe=Object.defineProperty,bQe=Object.getOwnPropertyDescriptor,xv=(e,t,r,n)=>{for(var o=n>1?void 0:n?bQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&wQe(t,r,o),o},ju=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${ju.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};ju.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);ju.styles=be` + :host { + display: contents; + } + `;xv([K({type:String,reflect:!0})],ju.prototype,"size",2);xv([K({type:String,reflect:!0})],ju.prototype,"weight",2);xv([K({type:String,reflect:!0})],ju.prototype,"color",2);xv([K({type:Boolean,reflect:!0})],ju.prototype,"mirrored",2);ju=xv([ve("ph-arrows-left-right")],ju)});var O6e={};Te(O6e,{PhArrowUp:()=>qu});var xQe,vQe,vv,qu,B6e=b(()=>{l();Qe();tt();st();it();at();et();xQe=Object.defineProperty,vQe=Object.getOwnPropertyDescriptor,vv=(e,t,r,n)=>{for(var o=n>1?void 0:n?vQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&xQe(t,r,o),o},qu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${qu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};qu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);qu.styles=be` + :host { + display: contents; + } + `;vv([K({type:String,reflect:!0})],qu.prototype,"size",2);vv([K({type:String,reflect:!0})],qu.prototype,"weight",2);vv([K({type:String,reflect:!0})],qu.prototype,"color",2);vv([K({type:Boolean,reflect:!0})],qu.prototype,"mirrored",2);qu=vv([ve("ph-arrow-up")],qu)});var k6e={};Te(k6e,{PhArrowUpRight:()=>Wu});var EQe,AQe,Ev,Wu,U6e=b(()=>{l();Qe();tt();st();it();at();et();EQe=Object.defineProperty,AQe=Object.getOwnPropertyDescriptor,Ev=(e,t,r,n)=>{for(var o=n>1?void 0:n?AQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&EQe(t,r,o),o},Wu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Wu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Wu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Wu.styles=be` + :host { + display: contents; + } + `;Ev([K({type:String,reflect:!0})],Wu.prototype,"size",2);Ev([K({type:String,reflect:!0})],Wu.prototype,"weight",2);Ev([K({type:String,reflect:!0})],Wu.prototype,"color",2);Ev([K({type:Boolean,reflect:!0})],Wu.prototype,"mirrored",2);Wu=Ev([ve("ph-arrow-up-right")],Wu)});var D6e={};Te(D6e,{PhArrowsClockwise:()=>Ku});var CQe,SQe,Av,Ku,L6e=b(()=>{l();Qe();tt();st();it();at();et();CQe=Object.defineProperty,SQe=Object.getOwnPropertyDescriptor,Av=(e,t,r,n)=>{for(var o=n>1?void 0:n?SQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&CQe(t,r,o),o},Ku=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Ku.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Ku.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Ku.styles=be` + :host { + display: contents; + } + `;Av([K({type:String,reflect:!0})],Ku.prototype,"size",2);Av([K({type:String,reflect:!0})],Ku.prototype,"weight",2);Av([K({type:String,reflect:!0})],Ku.prototype,"color",2);Av([K({type:Boolean,reflect:!0})],Ku.prototype,"mirrored",2);Ku=Av([ve("ph-arrows-clockwise")],Ku)});var M6e={};Te(M6e,{PhBank:()=>Zu});var IQe,TQe,Cv,Zu,H6e=b(()=>{l();Qe();tt();st();it();at();et();IQe=Object.defineProperty,TQe=Object.getOwnPropertyDescriptor,Cv=(e,t,r,n)=>{for(var o=n>1?void 0:n?TQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&IQe(t,r,o),o},Zu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Zu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Zu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Zu.styles=be` + :host { + display: contents; + } + `;Cv([K({type:String,reflect:!0})],Zu.prototype,"size",2);Cv([K({type:String,reflect:!0})],Zu.prototype,"weight",2);Cv([K({type:String,reflect:!0})],Zu.prototype,"color",2);Cv([K({type:Boolean,reflect:!0})],Zu.prototype,"mirrored",2);Zu=Cv([ve("ph-bank")],Zu)});var $6e={};Te($6e,{PhBrowser:()=>Gu});var _Qe,PQe,Sv,Gu,F6e=b(()=>{l();Qe();tt();st();it();at();et();_Qe=Object.defineProperty,PQe=Object.getOwnPropertyDescriptor,Sv=(e,t,r,n)=>{for(var o=n>1?void 0:n?PQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&_Qe(t,r,o),o},Gu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Gu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Gu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Gu.styles=be` + :host { + display: contents; + } + `;Sv([K({type:String,reflect:!0})],Gu.prototype,"size",2);Sv([K({type:String,reflect:!0})],Gu.prototype,"weight",2);Sv([K({type:String,reflect:!0})],Gu.prototype,"color",2);Sv([K({type:Boolean,reflect:!0})],Gu.prototype,"mirrored",2);Gu=Sv([ve("ph-browser")],Gu)});var z6e={};Te(z6e,{PhCaretDown:()=>Yu});var NQe,RQe,Iv,Yu,V6e=b(()=>{l();Qe();tt();st();it();at();et();NQe=Object.defineProperty,RQe=Object.getOwnPropertyDescriptor,Iv=(e,t,r,n)=>{for(var o=n>1?void 0:n?RQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&NQe(t,r,o),o},Yu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Yu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Yu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Yu.styles=be` + :host { + display: contents; + } + `;Iv([K({type:String,reflect:!0})],Yu.prototype,"size",2);Iv([K({type:String,reflect:!0})],Yu.prototype,"weight",2);Iv([K({type:String,reflect:!0})],Yu.prototype,"color",2);Iv([K({type:Boolean,reflect:!0})],Yu.prototype,"mirrored",2);Yu=Iv([ve("ph-caret-down")],Yu)});var j6e={};Te(j6e,{PhCaretLeft:()=>Ju});var OQe,BQe,Tv,Ju,q6e=b(()=>{l();Qe();tt();st();it();at();et();OQe=Object.defineProperty,BQe=Object.getOwnPropertyDescriptor,Tv=(e,t,r,n)=>{for(var o=n>1?void 0:n?BQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&OQe(t,r,o),o},Ju=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Ju.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Ju.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Ju.styles=be` + :host { + display: contents; + } + `;Tv([K({type:String,reflect:!0})],Ju.prototype,"size",2);Tv([K({type:String,reflect:!0})],Ju.prototype,"weight",2);Tv([K({type:String,reflect:!0})],Ju.prototype,"color",2);Tv([K({type:Boolean,reflect:!0})],Ju.prototype,"mirrored",2);Ju=Tv([ve("ph-caret-left")],Ju)});var W6e={};Te(W6e,{PhCaretRight:()=>Qu});var kQe,UQe,_v,Qu,K6e=b(()=>{l();Qe();tt();st();it();at();et();kQe=Object.defineProperty,UQe=Object.getOwnPropertyDescriptor,_v=(e,t,r,n)=>{for(var o=n>1?void 0:n?UQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&kQe(t,r,o),o},Qu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Qu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Qu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Qu.styles=be` + :host { + display: contents; + } + `;_v([K({type:String,reflect:!0})],Qu.prototype,"size",2);_v([K({type:String,reflect:!0})],Qu.prototype,"weight",2);_v([K({type:String,reflect:!0})],Qu.prototype,"color",2);_v([K({type:Boolean,reflect:!0})],Qu.prototype,"mirrored",2);Qu=_v([ve("ph-caret-right")],Qu)});var Z6e={};Te(Z6e,{PhCaretUp:()=>Xu});var DQe,LQe,Pv,Xu,G6e=b(()=>{l();Qe();tt();st();it();at();et();DQe=Object.defineProperty,LQe=Object.getOwnPropertyDescriptor,Pv=(e,t,r,n)=>{for(var o=n>1?void 0:n?LQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&DQe(t,r,o),o},Xu=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Xu.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Xu.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Xu.styles=be` + :host { + display: contents; + } + `;Pv([K({type:String,reflect:!0})],Xu.prototype,"size",2);Pv([K({type:String,reflect:!0})],Xu.prototype,"weight",2);Pv([K({type:String,reflect:!0})],Xu.prototype,"color",2);Pv([K({type:Boolean,reflect:!0})],Xu.prototype,"mirrored",2);Xu=Pv([ve("ph-caret-up")],Xu)});var Y6e={};Te(Y6e,{PhCheck:()=>ed});var MQe,HQe,Nv,ed,J6e=b(()=>{l();Qe();tt();st();it();at();et();MQe=Object.defineProperty,HQe=Object.getOwnPropertyDescriptor,Nv=(e,t,r,n)=>{for(var o=n>1?void 0:n?HQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&MQe(t,r,o),o},ed=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${ed.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};ed.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);ed.styles=be` + :host { + display: contents; + } + `;Nv([K({type:String,reflect:!0})],ed.prototype,"size",2);Nv([K({type:String,reflect:!0})],ed.prototype,"weight",2);Nv([K({type:String,reflect:!0})],ed.prototype,"color",2);Nv([K({type:Boolean,reflect:!0})],ed.prototype,"mirrored",2);ed=Nv([ve("ph-check")],ed)});var Q6e={};Te(Q6e,{PhCircleHalf:()=>td});var $Qe,FQe,Rv,td,X6e=b(()=>{l();Qe();tt();st();it();at();et();$Qe=Object.defineProperty,FQe=Object.getOwnPropertyDescriptor,Rv=(e,t,r,n)=>{for(var o=n>1?void 0:n?FQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&$Qe(t,r,o),o},td=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${td.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};td.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);td.styles=be` + :host { + display: contents; + } + `;Rv([K({type:String,reflect:!0})],td.prototype,"size",2);Rv([K({type:String,reflect:!0})],td.prototype,"weight",2);Rv([K({type:String,reflect:!0})],td.prototype,"color",2);Rv([K({type:Boolean,reflect:!0})],td.prototype,"mirrored",2);td=Rv([ve("ph-circle-half")],td)});var exe={};Te(exe,{PhClock:()=>rd});var zQe,VQe,Ov,rd,txe=b(()=>{l();Qe();tt();st();it();at();et();zQe=Object.defineProperty,VQe=Object.getOwnPropertyDescriptor,Ov=(e,t,r,n)=>{for(var o=n>1?void 0:n?VQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&zQe(t,r,o),o},rd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${rd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};rd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);rd.styles=be` + :host { + display: contents; + } + `;Ov([K({type:String,reflect:!0})],rd.prototype,"size",2);Ov([K({type:String,reflect:!0})],rd.prototype,"weight",2);Ov([K({type:String,reflect:!0})],rd.prototype,"color",2);Ov([K({type:Boolean,reflect:!0})],rd.prototype,"mirrored",2);rd=Ov([ve("ph-clock")],rd)});var rxe={};Te(rxe,{PhCompass:()=>nd});var jQe,qQe,Bv,nd,nxe=b(()=>{l();Qe();tt();st();it();at();et();jQe=Object.defineProperty,qQe=Object.getOwnPropertyDescriptor,Bv=(e,t,r,n)=>{for(var o=n>1?void 0:n?qQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&jQe(t,r,o),o},nd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${nd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};nd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);nd.styles=be` + :host { + display: contents; + } + `;Bv([K({type:String,reflect:!0})],nd.prototype,"size",2);Bv([K({type:String,reflect:!0})],nd.prototype,"weight",2);Bv([K({type:String,reflect:!0})],nd.prototype,"color",2);Bv([K({type:Boolean,reflect:!0})],nd.prototype,"mirrored",2);nd=Bv([ve("ph-compass")],nd)});var oxe={};Te(oxe,{PhCopy:()=>od});var WQe,KQe,kv,od,sxe=b(()=>{l();Qe();tt();st();it();at();et();WQe=Object.defineProperty,KQe=Object.getOwnPropertyDescriptor,kv=(e,t,r,n)=>{for(var o=n>1?void 0:n?KQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&WQe(t,r,o),o},od=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${od.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};od.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);od.styles=be` + :host { + display: contents; + } + `;kv([K({type:String,reflect:!0})],od.prototype,"size",2);kv([K({type:String,reflect:!0})],od.prototype,"weight",2);kv([K({type:String,reflect:!0})],od.prototype,"color",2);kv([K({type:Boolean,reflect:!0})],od.prototype,"mirrored",2);od=kv([ve("ph-copy")],od)});var ixe={};Te(ixe,{PhCreditCard:()=>sd});var ZQe,GQe,Uv,sd,axe=b(()=>{l();Qe();tt();st();it();at();et();ZQe=Object.defineProperty,GQe=Object.getOwnPropertyDescriptor,Uv=(e,t,r,n)=>{for(var o=n>1?void 0:n?GQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&ZQe(t,r,o),o},sd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${sd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};sd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);sd.styles=be` + :host { + display: contents; + } + `;Uv([K({type:String,reflect:!0})],sd.prototype,"size",2);Uv([K({type:String,reflect:!0})],sd.prototype,"weight",2);Uv([K({type:String,reflect:!0})],sd.prototype,"color",2);Uv([K({type:Boolean,reflect:!0})],sd.prototype,"mirrored",2);sd=Uv([ve("ph-credit-card")],sd)});var cxe={};Te(cxe,{PhCurrencyDollar:()=>id});var YQe,JQe,Dv,id,lxe=b(()=>{l();Qe();tt();st();it();at();et();YQe=Object.defineProperty,JQe=Object.getOwnPropertyDescriptor,Dv=(e,t,r,n)=>{for(var o=n>1?void 0:n?JQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&YQe(t,r,o),o},id=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${id.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};id.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);id.styles=be` + :host { + display: contents; + } + `;Dv([K({type:String,reflect:!0})],id.prototype,"size",2);Dv([K({type:String,reflect:!0})],id.prototype,"weight",2);Dv([K({type:String,reflect:!0})],id.prototype,"color",2);Dv([K({type:Boolean,reflect:!0})],id.prototype,"mirrored",2);id=Dv([ve("ph-currency-dollar")],id)});var uxe={};Te(uxe,{PhDesktop:()=>ad});var QQe,XQe,Lv,ad,dxe=b(()=>{l();Qe();tt();st();it();at();et();QQe=Object.defineProperty,XQe=Object.getOwnPropertyDescriptor,Lv=(e,t,r,n)=>{for(var o=n>1?void 0:n?XQe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&QQe(t,r,o),o},ad=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${ad.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};ad.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);ad.styles=be` + :host { + display: contents; + } + `;Lv([K({type:String,reflect:!0})],ad.prototype,"size",2);Lv([K({type:String,reflect:!0})],ad.prototype,"weight",2);Lv([K({type:String,reflect:!0})],ad.prototype,"color",2);Lv([K({type:Boolean,reflect:!0})],ad.prototype,"mirrored",2);ad=Lv([ve("ph-desktop")],ad)});var fxe={};Te(fxe,{PhDeviceMobile:()=>cd});var eXe,tXe,Mv,cd,pxe=b(()=>{l();Qe();tt();st();it();at();et();eXe=Object.defineProperty,tXe=Object.getOwnPropertyDescriptor,Mv=(e,t,r,n)=>{for(var o=n>1?void 0:n?tXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&eXe(t,r,o),o},cd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${cd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};cd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);cd.styles=be` + :host { + display: contents; + } + `;Mv([K({type:String,reflect:!0})],cd.prototype,"size",2);Mv([K({type:String,reflect:!0})],cd.prototype,"weight",2);Mv([K({type:String,reflect:!0})],cd.prototype,"color",2);Mv([K({type:Boolean,reflect:!0})],cd.prototype,"mirrored",2);cd=Mv([ve("ph-device-mobile")],cd)});var hxe={};Te(hxe,{PhDotsThree:()=>ld});var rXe,nXe,Hv,ld,mxe=b(()=>{l();Qe();tt();st();it();at();et();rXe=Object.defineProperty,nXe=Object.getOwnPropertyDescriptor,Hv=(e,t,r,n)=>{for(var o=n>1?void 0:n?nXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&rXe(t,r,o),o},ld=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${ld.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};ld.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);ld.styles=be` + :host { + display: contents; + } + `;Hv([K({type:String,reflect:!0})],ld.prototype,"size",2);Hv([K({type:String,reflect:!0})],ld.prototype,"weight",2);Hv([K({type:String,reflect:!0})],ld.prototype,"color",2);Hv([K({type:Boolean,reflect:!0})],ld.prototype,"mirrored",2);ld=Hv([ve("ph-dots-three")],ld)});var gxe={};Te(gxe,{PhVault:()=>ud});var oXe,sXe,$v,ud,yxe=b(()=>{l();Qe();tt();st();it();at();et();oXe=Object.defineProperty,sXe=Object.getOwnPropertyDescriptor,$v=(e,t,r,n)=>{for(var o=n>1?void 0:n?sXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&oXe(t,r,o),o},ud=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${ud.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};ud.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);ud.styles=be` + :host { + display: contents; + } + `;$v([K({type:String,reflect:!0})],ud.prototype,"size",2);$v([K({type:String,reflect:!0})],ud.prototype,"weight",2);$v([K({type:String,reflect:!0})],ud.prototype,"color",2);$v([K({type:Boolean,reflect:!0})],ud.prototype,"mirrored",2);ud=$v([ve("ph-vault")],ud)});var wxe={};Te(wxe,{PhEnvelope:()=>dd});var iXe,aXe,Fv,dd,bxe=b(()=>{l();Qe();tt();st();it();at();et();iXe=Object.defineProperty,aXe=Object.getOwnPropertyDescriptor,Fv=(e,t,r,n)=>{for(var o=n>1?void 0:n?aXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&iXe(t,r,o),o},dd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${dd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};dd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);dd.styles=be` + :host { + display: contents; + } + `;Fv([K({type:String,reflect:!0})],dd.prototype,"size",2);Fv([K({type:String,reflect:!0})],dd.prototype,"weight",2);Fv([K({type:String,reflect:!0})],dd.prototype,"color",2);Fv([K({type:Boolean,reflect:!0})],dd.prototype,"mirrored",2);dd=Fv([ve("ph-envelope")],dd)});var xxe={};Te(xxe,{PhFunnelSimple:()=>fd});var cXe,lXe,zv,fd,vxe=b(()=>{l();Qe();tt();st();it();at();et();cXe=Object.defineProperty,lXe=Object.getOwnPropertyDescriptor,zv=(e,t,r,n)=>{for(var o=n>1?void 0:n?lXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&cXe(t,r,o),o},fd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${fd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};fd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);fd.styles=be` + :host { + display: contents; + } + `;zv([K({type:String,reflect:!0})],fd.prototype,"size",2);zv([K({type:String,reflect:!0})],fd.prototype,"weight",2);zv([K({type:String,reflect:!0})],fd.prototype,"color",2);zv([K({type:Boolean,reflect:!0})],fd.prototype,"mirrored",2);fd=zv([ve("ph-funnel-simple")],fd)});var Exe={};Te(Exe,{PhGlobe:()=>pd});var uXe,dXe,Vv,pd,Axe=b(()=>{l();Qe();tt();st();it();at();et();uXe=Object.defineProperty,dXe=Object.getOwnPropertyDescriptor,Vv=(e,t,r,n)=>{for(var o=n>1?void 0:n?dXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&uXe(t,r,o),o},pd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${pd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};pd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);pd.styles=be` + :host { + display: contents; + } + `;Vv([K({type:String,reflect:!0})],pd.prototype,"size",2);Vv([K({type:String,reflect:!0})],pd.prototype,"weight",2);Vv([K({type:String,reflect:!0})],pd.prototype,"color",2);Vv([K({type:Boolean,reflect:!0})],pd.prototype,"mirrored",2);pd=Vv([ve("ph-globe")],pd)});var Cxe={};Te(Cxe,{PhIdentificationCard:()=>hd});var fXe,pXe,jv,hd,Sxe=b(()=>{l();Qe();tt();st();it();at();et();fXe=Object.defineProperty,pXe=Object.getOwnPropertyDescriptor,jv=(e,t,r,n)=>{for(var o=n>1?void 0:n?pXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&fXe(t,r,o),o},hd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${hd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};hd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);hd.styles=be` + :host { + display: contents; + } + `;jv([K({type:String,reflect:!0})],hd.prototype,"size",2);jv([K({type:String,reflect:!0})],hd.prototype,"weight",2);jv([K({type:String,reflect:!0})],hd.prototype,"color",2);jv([K({type:Boolean,reflect:!0})],hd.prototype,"mirrored",2);hd=jv([ve("ph-identification-card")],hd)});var Ixe={};Te(Ixe,{PhImage:()=>md});var hXe,mXe,qv,md,Txe=b(()=>{l();Qe();tt();st();it();at();et();hXe=Object.defineProperty,mXe=Object.getOwnPropertyDescriptor,qv=(e,t,r,n)=>{for(var o=n>1?void 0:n?mXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&hXe(t,r,o),o},md=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${md.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};md.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);md.styles=be` + :host { + display: contents; + } + `;qv([K({type:String,reflect:!0})],md.prototype,"size",2);qv([K({type:String,reflect:!0})],md.prototype,"weight",2);qv([K({type:String,reflect:!0})],md.prototype,"color",2);qv([K({type:Boolean,reflect:!0})],md.prototype,"mirrored",2);md=qv([ve("ph-image")],md)});var _xe={};Te(_xe,{PhInfo:()=>gd});var gXe,yXe,Wv,gd,Pxe=b(()=>{l();Qe();tt();st();it();at();et();gXe=Object.defineProperty,yXe=Object.getOwnPropertyDescriptor,Wv=(e,t,r,n)=>{for(var o=n>1?void 0:n?yXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&gXe(t,r,o),o},gd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${gd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};gd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);gd.styles=be` + :host { + display: contents; + } + `;Wv([K({type:String,reflect:!0})],gd.prototype,"size",2);Wv([K({type:String,reflect:!0})],gd.prototype,"weight",2);Wv([K({type:String,reflect:!0})],gd.prototype,"color",2);Wv([K({type:Boolean,reflect:!0})],gd.prototype,"mirrored",2);gd=Wv([ve("ph-info")],gd)});var Nxe={};Te(Nxe,{PhLightbulb:()=>yd});var wXe,bXe,Kv,yd,Rxe=b(()=>{l();Qe();tt();st();it();at();et();wXe=Object.defineProperty,bXe=Object.getOwnPropertyDescriptor,Kv=(e,t,r,n)=>{for(var o=n>1?void 0:n?bXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&wXe(t,r,o),o},yd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${yd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};yd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);yd.styles=be` + :host { + display: contents; + } + `;Kv([K({type:String,reflect:!0})],yd.prototype,"size",2);Kv([K({type:String,reflect:!0})],yd.prototype,"weight",2);Kv([K({type:String,reflect:!0})],yd.prototype,"color",2);Kv([K({type:Boolean,reflect:!0})],yd.prototype,"mirrored",2);yd=Kv([ve("ph-lightbulb")],yd)});var Oxe={};Te(Oxe,{PhMagnifyingGlass:()=>wd});var xXe,vXe,Zv,wd,Bxe=b(()=>{l();Qe();tt();st();it();at();et();xXe=Object.defineProperty,vXe=Object.getOwnPropertyDescriptor,Zv=(e,t,r,n)=>{for(var o=n>1?void 0:n?vXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&xXe(t,r,o),o},wd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${wd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};wd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);wd.styles=be` + :host { + display: contents; + } + `;Zv([K({type:String,reflect:!0})],wd.prototype,"size",2);Zv([K({type:String,reflect:!0})],wd.prototype,"weight",2);Zv([K({type:String,reflect:!0})],wd.prototype,"color",2);Zv([K({type:Boolean,reflect:!0})],wd.prototype,"mirrored",2);wd=Zv([ve("ph-magnifying-glass")],wd)});var kxe={};Te(kxe,{PhPaperPlaneRight:()=>bd});var EXe,AXe,Gv,bd,Uxe=b(()=>{l();Qe();tt();st();it();at();et();EXe=Object.defineProperty,AXe=Object.getOwnPropertyDescriptor,Gv=(e,t,r,n)=>{for(var o=n>1?void 0:n?AXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&EXe(t,r,o),o},bd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${bd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};bd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);bd.styles=be` + :host { + display: contents; + } + `;Gv([K({type:String,reflect:!0})],bd.prototype,"size",2);Gv([K({type:String,reflect:!0})],bd.prototype,"weight",2);Gv([K({type:String,reflect:!0})],bd.prototype,"color",2);Gv([K({type:Boolean,reflect:!0})],bd.prototype,"mirrored",2);bd=Gv([ve("ph-paper-plane-right")],bd)});var Dxe={};Te(Dxe,{PhPlus:()=>xd});var CXe,SXe,Yv,xd,Lxe=b(()=>{l();Qe();tt();st();it();at();et();CXe=Object.defineProperty,SXe=Object.getOwnPropertyDescriptor,Yv=(e,t,r,n)=>{for(var o=n>1?void 0:n?SXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&CXe(t,r,o),o},xd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${xd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};xd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);xd.styles=be` + :host { + display: contents; + } + `;Yv([K({type:String,reflect:!0})],xd.prototype,"size",2);Yv([K({type:String,reflect:!0})],xd.prototype,"weight",2);Yv([K({type:String,reflect:!0})],xd.prototype,"color",2);Yv([K({type:Boolean,reflect:!0})],xd.prototype,"mirrored",2);xd=Yv([ve("ph-plus")],xd)});var Mxe={};Te(Mxe,{PhPower:()=>vd});var IXe,TXe,Jv,vd,Hxe=b(()=>{l();Qe();tt();st();it();at();et();IXe=Object.defineProperty,TXe=Object.getOwnPropertyDescriptor,Jv=(e,t,r,n)=>{for(var o=n>1?void 0:n?TXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&IXe(t,r,o),o},vd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${vd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};vd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);vd.styles=be` + :host { + display: contents; + } + `;Jv([K({type:String,reflect:!0})],vd.prototype,"size",2);Jv([K({type:String,reflect:!0})],vd.prototype,"weight",2);Jv([K({type:String,reflect:!0})],vd.prototype,"color",2);Jv([K({type:Boolean,reflect:!0})],vd.prototype,"mirrored",2);vd=Jv([ve("ph-power")],vd)});var $xe={};Te($xe,{PhPuzzlePiece:()=>Ed});var _Xe,PXe,Qv,Ed,Fxe=b(()=>{l();Qe();tt();st();it();at();et();_Xe=Object.defineProperty,PXe=Object.getOwnPropertyDescriptor,Qv=(e,t,r,n)=>{for(var o=n>1?void 0:n?PXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&_Xe(t,r,o),o},Ed=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Ed.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Ed.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Ed.styles=be` + :host { + display: contents; + } + `;Qv([K({type:String,reflect:!0})],Ed.prototype,"size",2);Qv([K({type:String,reflect:!0})],Ed.prototype,"weight",2);Qv([K({type:String,reflect:!0})],Ed.prototype,"color",2);Qv([K({type:Boolean,reflect:!0})],Ed.prototype,"mirrored",2);Ed=Qv([ve("ph-puzzle-piece")],Ed)});var zxe={};Te(zxe,{PhQrCode:()=>Ad});var NXe,RXe,Xv,Ad,Vxe=b(()=>{l();Qe();tt();st();it();at();et();NXe=Object.defineProperty,RXe=Object.getOwnPropertyDescriptor,Xv=(e,t,r,n)=>{for(var o=n>1?void 0:n?RXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&NXe(t,r,o),o},Ad=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Ad.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Ad.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Ad.styles=be` + :host { + display: contents; + } + `;Xv([K({type:String,reflect:!0})],Ad.prototype,"size",2);Xv([K({type:String,reflect:!0})],Ad.prototype,"weight",2);Xv([K({type:String,reflect:!0})],Ad.prototype,"color",2);Xv([K({type:Boolean,reflect:!0})],Ad.prototype,"mirrored",2);Ad=Xv([ve("ph-qr-code")],Ad)});var jxe={};Te(jxe,{PhQuestion:()=>Cd});var OXe,BXe,eE,Cd,qxe=b(()=>{l();Qe();tt();st();it();at();et();OXe=Object.defineProperty,BXe=Object.getOwnPropertyDescriptor,eE=(e,t,r,n)=>{for(var o=n>1?void 0:n?BXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&OXe(t,r,o),o},Cd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Cd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Cd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Cd.styles=be` + :host { + display: contents; + } + `;eE([K({type:String,reflect:!0})],Cd.prototype,"size",2);eE([K({type:String,reflect:!0})],Cd.prototype,"weight",2);eE([K({type:String,reflect:!0})],Cd.prototype,"color",2);eE([K({type:Boolean,reflect:!0})],Cd.prototype,"mirrored",2);Cd=eE([ve("ph-question")],Cd)});var Wxe={};Te(Wxe,{PhQuestionMark:()=>Sd});var kXe,UXe,tE,Sd,Kxe=b(()=>{l();Qe();tt();st();it();at();et();kXe=Object.defineProperty,UXe=Object.getOwnPropertyDescriptor,tE=(e,t,r,n)=>{for(var o=n>1?void 0:n?UXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&kXe(t,r,o),o},Sd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Sd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Sd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Sd.styles=be` + :host { + display: contents; + } + `;tE([K({type:String,reflect:!0})],Sd.prototype,"size",2);tE([K({type:String,reflect:!0})],Sd.prototype,"weight",2);tE([K({type:String,reflect:!0})],Sd.prototype,"color",2);tE([K({type:Boolean,reflect:!0})],Sd.prototype,"mirrored",2);Sd=tE([ve("ph-question-mark")],Sd)});var Zxe={};Te(Zxe,{PhSealCheck:()=>Id});var DXe,LXe,rE,Id,Gxe=b(()=>{l();Qe();tt();st();it();at();et();DXe=Object.defineProperty,LXe=Object.getOwnPropertyDescriptor,rE=(e,t,r,n)=>{for(var o=n>1?void 0:n?LXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&DXe(t,r,o),o},Id=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Id.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Id.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Id.styles=be` + :host { + display: contents; + } + `;rE([K({type:String,reflect:!0})],Id.prototype,"size",2);rE([K({type:String,reflect:!0})],Id.prototype,"weight",2);rE([K({type:String,reflect:!0})],Id.prototype,"color",2);rE([K({type:Boolean,reflect:!0})],Id.prototype,"mirrored",2);Id=rE([ve("ph-seal-check")],Id)});var Yxe={};Te(Yxe,{PhSignOut:()=>Td});var MXe,HXe,nE,Td,Jxe=b(()=>{l();Qe();tt();st();it();at();et();MXe=Object.defineProperty,HXe=Object.getOwnPropertyDescriptor,nE=(e,t,r,n)=>{for(var o=n>1?void 0:n?HXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&MXe(t,r,o),o},Td=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Td.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Td.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Td.styles=be` + :host { + display: contents; + } + `;nE([K({type:String,reflect:!0})],Td.prototype,"size",2);nE([K({type:String,reflect:!0})],Td.prototype,"weight",2);nE([K({type:String,reflect:!0})],Td.prototype,"color",2);nE([K({type:Boolean,reflect:!0})],Td.prototype,"mirrored",2);Td=nE([ve("ph-sign-out")],Td)});var Qxe={};Te(Qxe,{PhSpinner:()=>_d});var $Xe,FXe,oE,_d,Xxe=b(()=>{l();Qe();tt();st();it();at();et();$Xe=Object.defineProperty,FXe=Object.getOwnPropertyDescriptor,oE=(e,t,r,n)=>{for(var o=n>1?void 0:n?FXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&$Xe(t,r,o),o},_d=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${_d.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};_d.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);_d.styles=be` + :host { + display: contents; + } + `;oE([K({type:String,reflect:!0})],_d.prototype,"size",2);oE([K({type:String,reflect:!0})],_d.prototype,"weight",2);oE([K({type:String,reflect:!0})],_d.prototype,"color",2);oE([K({type:Boolean,reflect:!0})],_d.prototype,"mirrored",2);_d=oE([ve("ph-spinner")],_d)});var e8e={};Te(e8e,{PhTrash:()=>Pd});var zXe,VXe,sE,Pd,t8e=b(()=>{l();Qe();tt();st();it();at();et();zXe=Object.defineProperty,VXe=Object.getOwnPropertyDescriptor,sE=(e,t,r,n)=>{for(var o=n>1?void 0:n?VXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&zXe(t,r,o),o},Pd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Pd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Pd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Pd.styles=be` + :host { + display: contents; + } + `;sE([K({type:String,reflect:!0})],Pd.prototype,"size",2);sE([K({type:String,reflect:!0})],Pd.prototype,"weight",2);sE([K({type:String,reflect:!0})],Pd.prototype,"color",2);sE([K({type:Boolean,reflect:!0})],Pd.prototype,"mirrored",2);Pd=sE([ve("ph-trash")],Pd)});var r8e={};Te(r8e,{PhUser:()=>Nd});var jXe,qXe,iE,Nd,n8e=b(()=>{l();Qe();tt();st();it();at();et();jXe=Object.defineProperty,qXe=Object.getOwnPropertyDescriptor,iE=(e,t,r,n)=>{for(var o=n>1?void 0:n?qXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&jXe(t,r,o),o},Nd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Nd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Nd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Nd.styles=be` + :host { + display: contents; + } + `;iE([K({type:String,reflect:!0})],Nd.prototype,"size",2);iE([K({type:String,reflect:!0})],Nd.prototype,"weight",2);iE([K({type:String,reflect:!0})],Nd.prototype,"color",2);iE([K({type:Boolean,reflect:!0})],Nd.prototype,"mirrored",2);Nd=iE([ve("ph-user")],Nd)});var o8e={};Te(o8e,{PhWallet:()=>Rd});var WXe,KXe,aE,Rd,s8e=b(()=>{l();Qe();tt();st();it();at();et();WXe=Object.defineProperty,KXe=Object.getOwnPropertyDescriptor,aE=(e,t,r,n)=>{for(var o=n>1?void 0:n?KXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&WXe(t,r,o),o},Rd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Rd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Rd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Rd.styles=be` + :host { + display: contents; + } + `;aE([K({type:String,reflect:!0})],Rd.prototype,"size",2);aE([K({type:String,reflect:!0})],Rd.prototype,"weight",2);aE([K({type:String,reflect:!0})],Rd.prototype,"color",2);aE([K({type:Boolean,reflect:!0})],Rd.prototype,"mirrored",2);Rd=aE([ve("ph-wallet")],Rd)});var i8e={};Te(i8e,{PhWarning:()=>Od});var ZXe,GXe,cE,Od,a8e=b(()=>{l();Qe();tt();st();it();at();et();ZXe=Object.defineProperty,GXe=Object.getOwnPropertyDescriptor,cE=(e,t,r,n)=>{for(var o=n>1?void 0:n?GXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&ZXe(t,r,o),o},Od=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Od.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Od.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Od.styles=be` + :host { + display: contents; + } + `;cE([K({type:String,reflect:!0})],Od.prototype,"size",2);cE([K({type:String,reflect:!0})],Od.prototype,"weight",2);cE([K({type:String,reflect:!0})],Od.prototype,"color",2);cE([K({type:Boolean,reflect:!0})],Od.prototype,"mirrored",2);Od=cE([ve("ph-warning")],Od)});var c8e={};Te(c8e,{PhWarningCircle:()=>Bd});var YXe,JXe,lE,Bd,l8e=b(()=>{l();Qe();tt();st();it();at();et();YXe=Object.defineProperty,JXe=Object.getOwnPropertyDescriptor,lE=(e,t,r,n)=>{for(var o=n>1?void 0:n?JXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&YXe(t,r,o),o},Bd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${Bd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};Bd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);Bd.styles=be` + :host { + display: contents; + } + `;lE([K({type:String,reflect:!0})],Bd.prototype,"size",2);lE([K({type:String,reflect:!0})],Bd.prototype,"weight",2);lE([K({type:String,reflect:!0})],Bd.prototype,"color",2);lE([K({type:Boolean,reflect:!0})],Bd.prototype,"mirrored",2);Bd=lE([ve("ph-warning-circle")],Bd)});var u8e={};Te(u8e,{PhX:()=>kd});var QXe,XXe,uE,kd,d8e=b(()=>{l();Qe();tt();st();it();at();et();QXe=Object.defineProperty,XXe=Object.getOwnPropertyDescriptor,uE=(e,t,r,n)=>{for(var o=n>1?void 0:n?XXe(t,r):t,s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=(n?i(t,r,o):i(o))||o);return n&&o&&QXe(t,r,o),o},kd=class extends we{constructor(){super(...arguments),this.size="1em",this.weight="regular",this.color="currentColor",this.mirrored=!1}render(){var e;return xe` + ${kd.weightsMap.get((e=this.weight)!=null?e:"regular")} + `}};kd.weightsMap=new Map([["thin",z``],["light",z``],["regular",z``],["bold",z``],["fill",z``],["duotone",z``]]);kd.styles=be` + :host { + display: contents; + } + `;uE([K({type:String,reflect:!0})],kd.prototype,"size",2);uE([K({type:String,reflect:!0})],kd.prototype,"weight",2);uE([K({type:String,reflect:!0})],kd.prototype,"color",2);uE([K({type:Boolean,reflect:!0})],kd.prototype,"mirrored",2);kd=uE([ve("ph-x")],kd)});var dE,eet,tet,ret,net,qy,uo=b(()=>{l();he();$e();zwe();jwe();Wwe();Zwe();Ywe();Qwe();ebe();rbe();obe();ibe();cbe();ube();fbe();hbe();gbe();wbe();xbe();Ebe();Cbe();Ibe();_be();Nbe();Obe();kbe();Hbe();$be();Rt();Mt();Bt();zbe();dE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},eet={add:"ph-plus",allWallets:"ph-dots-three",arrowBottom:"ph-arrow-down",arrowBottomCircle:"ph-arrow-circle-down",arrowClockWise:"ph-arrow-clockwise",arrowLeft:"ph-arrow-left",arrowRight:"ph-arrow-right",arrowTop:"ph-arrow-up",arrowTopRight:"ph-arrow-up-right",bank:"ph-bank",bin:"ph-trash",browser:"ph-browser",card:"ph-credit-card",checkmarkBold:"ph-check",chevronBottom:"ph-caret-down",chevronLeft:"ph-caret-left",chevronRight:"ph-caret-right",chevronTop:"ph-caret-up",clock:"ph-clock",close:"ph-x",coinPlaceholder:"ph-circle-half",compass:"ph-compass",copy:"ph-copy",desktop:"ph-desktop",dollar:"ph-currency-dollar",download:"ph-vault",exclamationCircle:"ph-warning-circle",extension:"ph-puzzle-piece",externalLink:"ph-arrow-square-out",filters:"ph-funnel-simple",helpCircle:"ph-question",id:"ph-identification-card",image:"ph-image",info:"ph-info",lightbulb:"ph-lightbulb",mail:"ph-envelope",mobile:"ph-device-mobile",more:"ph-dots-three",networkPlaceholder:"ph-globe",nftPlaceholder:"ph-image",plus:"ph-plus",power:"ph-power",qrCode:"ph-qr-code",questionMark:"ph-question",refresh:"ph-arrow-clockwise",recycleHorizontal:"ph-arrows-clockwise",search:"ph-magnifying-glass",sealCheck:"ph-seal-check",send:"ph-paper-plane-right",signOut:"ph-sign-out",spinner:"ph-spinner",swapHorizontal:"ph-arrows-left-right",swapVertical:"ph-arrows-down-up",threeDots:"ph-dots-three",user:"ph-user",verify:"ph-seal-check",verifyFilled:"ph-seal-check",wallet:"ph-wallet",warning:"ph-warning",warningCircle:"ph-warning-circle",appStore:"",apple:"",bitcoin:"",coins:"",chromeStore:"",cursor:"",discord:"",ethereum:"",etherscan:"",facebook:"",farcaster:"",github:"",google:"",playStore:"",paperPlaneTitle:"",reown:"",solana:"",ton:"",telegram:"",twitch:"",twitterIcon:"",twitter:"",walletConnect:"",walletConnectBrown:"",walletConnectLightBrown:"",x:"",infoSeal:"",checkmark:""},tet={"ph-arrow-circle-down":()=>Promise.resolve().then(()=>(y6e(),g6e)),"ph-arrow-clockwise":()=>Promise.resolve().then(()=>(b6e(),w6e)),"ph-arrow-down":()=>Promise.resolve().then(()=>(v6e(),x6e)),"ph-arrow-left":()=>Promise.resolve().then(()=>(A6e(),E6e)),"ph-arrow-right":()=>Promise.resolve().then(()=>(S6e(),C6e)),"ph-arrow-square-out":()=>Promise.resolve().then(()=>(T6e(),I6e)),"ph-arrows-down-up":()=>Promise.resolve().then(()=>(P6e(),_6e)),"ph-arrows-left-right":()=>Promise.resolve().then(()=>(R6e(),N6e)),"ph-arrow-up":()=>Promise.resolve().then(()=>(B6e(),O6e)),"ph-arrow-up-right":()=>Promise.resolve().then(()=>(U6e(),k6e)),"ph-arrows-clockwise":()=>Promise.resolve().then(()=>(L6e(),D6e)),"ph-bank":()=>Promise.resolve().then(()=>(H6e(),M6e)),"ph-browser":()=>Promise.resolve().then(()=>(F6e(),$6e)),"ph-caret-down":()=>Promise.resolve().then(()=>(V6e(),z6e)),"ph-caret-left":()=>Promise.resolve().then(()=>(q6e(),j6e)),"ph-caret-right":()=>Promise.resolve().then(()=>(K6e(),W6e)),"ph-caret-up":()=>Promise.resolve().then(()=>(G6e(),Z6e)),"ph-check":()=>Promise.resolve().then(()=>(J6e(),Y6e)),"ph-circle-half":()=>Promise.resolve().then(()=>(X6e(),Q6e)),"ph-clock":()=>Promise.resolve().then(()=>(txe(),exe)),"ph-compass":()=>Promise.resolve().then(()=>(nxe(),rxe)),"ph-copy":()=>Promise.resolve().then(()=>(sxe(),oxe)),"ph-credit-card":()=>Promise.resolve().then(()=>(axe(),ixe)),"ph-currency-dollar":()=>Promise.resolve().then(()=>(lxe(),cxe)),"ph-desktop":()=>Promise.resolve().then(()=>(dxe(),uxe)),"ph-device-mobile":()=>Promise.resolve().then(()=>(pxe(),fxe)),"ph-dots-three":()=>Promise.resolve().then(()=>(mxe(),hxe)),"ph-vault":()=>Promise.resolve().then(()=>(yxe(),gxe)),"ph-envelope":()=>Promise.resolve().then(()=>(bxe(),wxe)),"ph-funnel-simple":()=>Promise.resolve().then(()=>(vxe(),xxe)),"ph-globe":()=>Promise.resolve().then(()=>(Axe(),Exe)),"ph-identification-card":()=>Promise.resolve().then(()=>(Sxe(),Cxe)),"ph-image":()=>Promise.resolve().then(()=>(Txe(),Ixe)),"ph-info":()=>Promise.resolve().then(()=>(Pxe(),_xe)),"ph-lightbulb":()=>Promise.resolve().then(()=>(Rxe(),Nxe)),"ph-magnifying-glass":()=>Promise.resolve().then(()=>(Bxe(),Oxe)),"ph-paper-plane-right":()=>Promise.resolve().then(()=>(Uxe(),kxe)),"ph-plus":()=>Promise.resolve().then(()=>(Lxe(),Dxe)),"ph-power":()=>Promise.resolve().then(()=>(Hxe(),Mxe)),"ph-puzzle-piece":()=>Promise.resolve().then(()=>(Fxe(),$xe)),"ph-qr-code":()=>Promise.resolve().then(()=>(Vxe(),zxe)),"ph-question":()=>Promise.resolve().then(()=>(qxe(),jxe)),"ph-question-circle":()=>Promise.resolve().then(()=>(Kxe(),Wxe)),"ph-seal-check":()=>Promise.resolve().then(()=>(Gxe(),Zxe)),"ph-sign-out":()=>Promise.resolve().then(()=>(Jxe(),Yxe)),"ph-spinner":()=>Promise.resolve().then(()=>(Xxe(),Qxe)),"ph-trash":()=>Promise.resolve().then(()=>(t8e(),e8e)),"ph-user":()=>Promise.resolve().then(()=>(n8e(),r8e)),"ph-wallet":()=>Promise.resolve().then(()=>(s8e(),o8e)),"ph-warning":()=>Promise.resolve().then(()=>(a8e(),i8e)),"ph-warning-circle":()=>Promise.resolve().then(()=>(l8e(),c8e)),"ph-x":()=>Promise.resolve().then(()=>(d8e(),u8e))},ret={appStore:Vwe,apple:qwe,bitcoin:Kwe,coins:Xwe,chromeStore:Jwe,cursor:tbe,discord:nbe,ethereum:sbe,etherscan:abe,facebook:lbe,farcaster:dbe,github:pbe,google:mbe,playStore:vbe,paperPlaneTitle:bbe,reown:Abe,solana:Sbe,ton:Pbe,telegram:Tbe,twitch:Rbe,twitter:oj,twitterIcon:Bbe,walletConnect:Ube,walletConnectInvert:Dbe,walletConnectBrown:Mbe,walletConnectLightBrown:Lbe,x:oj,infoSeal:ybe,checkmark:Gwe},net={"accent-primary":$t.tokens.core.iconAccentPrimary,"accent-certified":$t.tokens.core.iconAccentCertified,"foreground-secondary":$t.tokens.theme.foregroundSecondary,default:$t.tokens.theme.iconDefault,success:$t.tokens.core.iconSuccess,error:$t.tokens.core.iconError,warning:$t.tokens.core.iconWarning,inverse:$t.tokens.theme.iconInverse},qy=class extends ie{constructor(){super(...arguments),this.size="md",this.name="copy",this.weight="bold",this.color="inherit"}render(){let t={xxs:"2",xs:"3",sm:"3",md:"4",mdl:"5",lg:"5",xl:"6",xxl:"7",inherit:"inherit"};this.style.cssText=` + --local-width: ${this.size==="inherit"?"inherit":`var(--apkt-spacing-${t[this.size]})`}; + --local-color: ${this.color==="inherit"?"inherit":net[this.color]} + `;let r=eet[this.name];if(r&&r!==""){let n=tet[r];n&&n();let o=$we(r);return nj`<${o} size=${{xxs:"0.5em",xs:"0.75em",sm:"0.75em",md:"1em",mdl:"1.25em",lg:"1.25em",xl:"1.5em",xxl:"1.75em"}[this.size]} weight="${this.weight}">`}return ret[this.name]||nj``}};qy.styles=[Me,Fbe];dE([q()],qy.prototype,"size",void 0);dE([q()],qy.prototype,"name",void 0);dE([q()],qy.prototype,"weight",void 0);dE([q()],qy.prototype,"color",void 0);qy=dE([ne("wui-icon")],qy)});var LP,fE,Ex,pE=b(()=>{l();LP={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},fE=e=>(...t)=>({_$litDirective$:e,values:t}),Ex=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,r,n){this._$Ct=t,this._$AM=r,this._$Ci=n}_$AS(t,r){return this.update(t,r)}update(t,r){return this.render(...r)}}});var Ax,f8e=b(()=>{l();Up();pE();Ax=fE(class extends Ex{constructor(e){if(super(e),e.type!==LP.ATTRIBUTE||e.name!=="class"||e.strings?.length>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(e){return" "+Object.keys(e).filter(t=>e[t]).join(" ")+" "}update(e,[t]){if(this.st===void 0){this.st=new Set,e.strings!==void 0&&(this.nt=new Set(e.strings.join(" ").split(/\s/).filter(n=>n!=="")));for(let n in t)t[n]&&!this.nt?.has(n)&&this.st.add(n);return this.render(t)}let r=e.element.classList;for(let n of this.st)n in t||(r.remove(n),this.st.delete(n));for(let n in t){let o=!!t[n];o===this.st.has(n)||this.nt?.has(n)||(o?(r.add(n),this.st.add(n)):(r.remove(n),this.st.delete(n)))}return kp}})});var MP=b(()=>{l();f8e()});var p8e,h8e=b(()=>{l();Rt();p8e=fe` + slot { + width: 100%; + display: inline-block; + font-style: normal; + overflow: inherit; + text-overflow: inherit; + text-align: var(--local-align); + color: var(--local-color); + } + + .wui-line-clamp-1 { + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 1; + } + + .wui-line-clamp-2 { + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + } + + /* -- Headings --------------------------------------------------- */ + .wui-font-h1-regular-mono { + font-size: ${({textSize:e})=>e.h1}; + line-height: ${({typography:e})=>e["h1-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h1-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-h1-regular { + font-size: ${({textSize:e})=>e.h1}; + line-height: ${({typography:e})=>e["h1-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h1-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h1-medium { + font-size: ${({textSize:e})=>e.h1}; + line-height: ${({typography:e})=>e["h1-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h1-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h2-regular-mono { + font-size: ${({textSize:e})=>e.h2}; + line-height: ${({typography:e})=>e["h2-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h2-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-h2-regular { + font-size: ${({textSize:e})=>e.h2}; + line-height: ${({typography:e})=>e["h2-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h2-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h2-medium { + font-size: ${({textSize:e})=>e.h2}; + line-height: ${({typography:e})=>e["h2-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h2-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h3-regular-mono { + font-size: ${({textSize:e})=>e.h3}; + line-height: ${({typography:e})=>e["h3-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h3-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-h3-regular { + font-size: ${({textSize:e})=>e.h3}; + line-height: ${({typography:e})=>e["h3-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h3-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h3-medium { + font-size: ${({textSize:e})=>e.h3}; + line-height: ${({typography:e})=>e["h3-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h3-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h4-regular-mono { + font-size: ${({textSize:e})=>e.h4}; + line-height: ${({typography:e})=>e["h4-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h4-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-h4-regular { + font-size: ${({textSize:e})=>e.h4}; + line-height: ${({typography:e})=>e["h4-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h4-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h4-medium { + font-size: ${({textSize:e})=>e.h4}; + line-height: ${({typography:e})=>e["h4-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h4-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h5-regular-mono { + font-size: ${({textSize:e})=>e.h5}; + line-height: ${({typography:e})=>e["h5-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h5-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-h5-regular { + font-size: ${({textSize:e})=>e.h5}; + line-height: ${({typography:e})=>e["h5-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h5-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h5-medium { + font-size: ${({textSize:e})=>e.h5}; + line-height: ${({typography:e})=>e["h5-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h5-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h6-regular-mono { + font-size: ${({textSize:e})=>e.h6}; + line-height: ${({typography:e})=>e["h6-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h6-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-h6-regular { + font-size: ${({textSize:e})=>e.h6}; + line-height: ${({typography:e})=>e["h6-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h6-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-h6-medium { + font-size: ${({textSize:e})=>e.h6}; + line-height: ${({typography:e})=>e["h6-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["h6-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-lg-regular-mono { + font-size: ${({textSize:e})=>e.large}; + line-height: ${({typography:e})=>e["lg-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["lg-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-lg-regular { + font-size: ${({textSize:e})=>e.large}; + line-height: ${({typography:e})=>e["lg-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["lg-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-lg-medium { + font-size: ${({textSize:e})=>e.large}; + line-height: ${({typography:e})=>e["lg-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["lg-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-md-regular-mono { + font-size: ${({textSize:e})=>e.medium}; + line-height: ${({typography:e})=>e["md-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["md-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-md-regular { + font-size: ${({textSize:e})=>e.medium}; + line-height: ${({typography:e})=>e["md-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["md-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-md-medium { + font-size: ${({textSize:e})=>e.medium}; + line-height: ${({typography:e})=>e["md-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["md-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-sm-regular-mono { + font-size: ${({textSize:e})=>e.small}; + line-height: ${({typography:e})=>e["sm-regular-mono"].lineHeight}; + letter-spacing: ${({typography:e})=>e["sm-regular-mono"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.mono}; + } + + .wui-font-sm-regular { + font-size: ${({textSize:e})=>e.small}; + line-height: ${({typography:e})=>e["sm-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["sm-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } + + .wui-font-sm-medium { + font-size: ${({textSize:e})=>e.small}; + line-height: ${({typography:e})=>e["sm-medium"].lineHeight}; + letter-spacing: ${({typography:e})=>e["sm-medium"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.medium}; + font-family: ${({fontFamily:e})=>e.regular}; + font-feature-settings: + 'liga' off, + 'clig' off; + } +`});var Cx,oet,Wm,Rs=b(()=>{l();he();$e();MP();Rt();Mt();Bt();h8e();Cx=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},oet={primary:$t.tokens.theme.textPrimary,secondary:$t.tokens.theme.textSecondary,tertiary:$t.tokens.theme.textTertiary,invert:$t.tokens.theme.textInvert,error:$t.tokens.core.textError,success:$t.tokens.core.textSuccess,warning:$t.tokens.core.textWarning,"accent-primary":$t.tokens.core.textAccentPrimary},Wm=class extends ie{constructor(){super(...arguments),this.variant="md-regular",this.color="inherit",this.align="left",this.lineClamp=void 0,this.display="inline-flex"}render(){let t={[`wui-font-${this.variant}`]:!0,[`wui-line-clamp-${this.lineClamp}`]:!!this.lineClamp};return this.style.cssText=` + display: ${this.display}; + --local-align: ${this.align}; + --local-color: ${this.color==="inherit"?"inherit":oet[this.color??"primary"]}; + `,V``}};Wm.styles=[Me,p8e];Cx([q()],Wm.prototype,"variant",void 0);Cx([q()],Wm.prototype,"color",void 0);Cx([q()],Wm.prototype,"align",void 0);Cx([q()],Wm.prototype,"lineClamp",void 0);Cx([q()],Wm.prototype,"display",void 0);Wm=Cx([ne("wui-text")],Wm)});var m8e,g8e=b(()=>{l();Rt();m8e=fe` + :host { + display: inline-flex; + justify-content: center; + align-items: center; + border-radius: ${({borderRadius:e})=>e[2]}; + padding: ${({spacing:e})=>e[1]} !important; + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + position: relative; + } + + :host([data-padding='2']) { + padding: ${({spacing:e})=>e[2]} !important; + } + + :host:after { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + border-radius: ${({borderRadius:e})=>e[2]}; + } + + :host > wui-icon { + z-index: 10; + } + + /* -- Colors --------------------------------------------------- */ + :host([data-color='accent-primary']) { + color: ${({tokens:e})=>e.core.iconAccentPrimary}; + } + + :host([data-color='accent-primary']):after { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + :host([data-color='default']), + :host([data-color='secondary']) { + color: ${({tokens:e})=>e.theme.iconDefault}; + } + + :host([data-color='default']):after { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + :host([data-color='secondary']):after { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + :host([data-color='success']) { + color: ${({tokens:e})=>e.core.iconSuccess}; + } + + :host([data-color='success']):after { + background-color: ${({tokens:e})=>e.core.backgroundSuccess}; + } + + :host([data-color='error']) { + color: ${({tokens:e})=>e.core.iconError}; + } + + :host([data-color='error']):after { + background-color: ${({tokens:e})=>e.core.backgroundError}; + } + + :host([data-color='warning']) { + color: ${({tokens:e})=>e.core.iconWarning}; + } + + :host([data-color='warning']):after { + background-color: ${({tokens:e})=>e.core.backgroundWarning}; + } + + :host([data-color='inverse']) { + color: ${({tokens:e})=>e.theme.iconInverse}; + } + + :host([data-color='inverse']):after { + background-color: transparent; + } +`});var hE,Wy,Sx=b(()=>{l();he();$e();kr();uo();Mt();Bt();g8e();hE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Wy=class extends ie{constructor(){super(...arguments),this.icon="copy",this.size="md",this.padding="1",this.color="default"}render(){return this.dataset.padding=this.padding,this.dataset.color=this.color,V` + + `}};Wy.styles=[Me,Gt,m8e];hE([q()],Wy.prototype,"icon",void 0);hE([q()],Wy.prototype,"size",void 0);hE([q()],Wy.prototype,"padding",void 0);hE([q()],Wy.prototype,"color",void 0);Wy=hE([ne("wui-icon-box")],Wy)});var y8e,w8e=b(()=>{l();Rt();y8e=fe` + :host { + display: block; + width: var(--local-width); + height: var(--local-height); + } + + img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + object-position: center center; + border-radius: inherit; + user-select: none; + user-drag: none; + -webkit-user-drag: none; + -khtml-user-drag: none; + -moz-user-drag: none; + -o-user-drag: none; + } + + :host([data-boxed='true']) { + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: ${({borderRadius:e})=>e[2]}; + } + + :host([data-boxed='true']) img { + width: 20px; + height: 20px; + border-radius: ${({borderRadius:e})=>e[16]}; + } + + :host([data-full='true']) img { + width: 100%; + height: 100%; + } + + :host([data-boxed='true']) wui-icon { + width: 20px; + height: 20px; + } + + :host([data-icon='error']) { + background-color: ${({tokens:e})=>e.core.backgroundError}; + } + + :host([data-rounded='true']) { + border-radius: ${({borderRadius:e})=>e[16]}; + } +`});var Ud,Cc,Ky=b(()=>{l();he();$e();kr();Mt();Bt();w8e();Ud=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Cc=class extends ie{constructor(){super(...arguments),this.src="./path/to/image.jpg",this.alt="Image",this.size=void 0,this.boxed=!1,this.rounded=!1,this.fullSize=!1}render(){let t={inherit:"inherit",xxs:"2",xs:"3",sm:"4",md:"4",mdl:"5",lg:"5",xl:"6",xxl:"7","3xl":"8","4xl":"9","5xl":"10"};return this.style.cssText=` + --local-width: ${this.size?`var(--apkt-spacing-${t[this.size]});`:"100%"}; + --local-height: ${this.size?`var(--apkt-spacing-${t[this.size]});`:"100%"}; + `,this.dataset.boxed=this.boxed?"true":"false",this.dataset.rounded=this.rounded?"true":"false",this.dataset.full=this.fullSize?"true":"false",this.dataset.icon=this.iconColor||"inherit",this.icon?V` `:this.logo?V` `:V`${this.alt}`}handleImageError(){this.dispatchEvent(new CustomEvent("onLoadError",{bubbles:!0,composed:!0}))}};Cc.styles=[Me,y8e];Ud([q()],Cc.prototype,"src",void 0);Ud([q()],Cc.prototype,"logo",void 0);Ud([q()],Cc.prototype,"icon",void 0);Ud([q()],Cc.prototype,"iconColor",void 0);Ud([q()],Cc.prototype,"alt",void 0);Ud([q()],Cc.prototype,"size",void 0);Ud([q({type:Boolean})],Cc.prototype,"boxed",void 0);Ud([q({type:Boolean})],Cc.prototype,"rounded",void 0);Ud([q({type:Boolean})],Cc.prototype,"fullSize",void 0);Cc=Ud([ne("wui-image")],Cc)});var b8e,x8e=b(()=>{l();Rt();b8e=fe` + :host { + position: relative; + background-color: ${({tokens:e})=>e.theme.foregroundTertiary}; + display: flex; + justify-content: center; + align-items: center; + border-radius: inherit; + border-radius: var(--local-border-radius); + } + + :host([data-image='true']) { + background-color: transparent; + } + + :host > wui-flex { + overflow: hidden; + border-radius: inherit; + border-radius: var(--local-border-radius); + } + + :host([data-size='sm']) { + width: 32px; + height: 32px; + } + + :host([data-size='md']) { + width: 40px; + height: 40px; + } + + :host([data-size='lg']) { + width: 56px; + height: 56px; + } + + :host([name='Extension'])::after { + border: 1px solid ${({colors:e})=>e.accent010}; + } + + :host([data-wallet-icon='allWallets'])::after { + border: 1px solid ${({colors:e})=>e.accent010}; + } + + wui-icon[data-parent-size='inherit'] { + width: 75%; + height: 75%; + align-items: center; + } + + wui-icon { + color: ${({tokens:e})=>e.theme.iconDefault}; + } + + wui-icon[data-parent-size='sm'] { + width: 24px; + height: 24px; + } + + wui-icon[data-parent-size='md'] { + width: 32px; + height: 32px; + } + + :host > wui-icon-box { + position: absolute; + overflow: hidden; + right: -1px; + bottom: -2px; + z-index: 1; + border: 2px solid ${({tokens:e})=>e.theme.backgroundPrimary}; + padding: 1px; + } +`});var Zy,Mp,HP=b(()=>{l();he();$e();uo();Ky();Mt();Bt();Sx();x8e();Zy=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Mp=class extends ie{constructor(){super(...arguments),this.size="md",this.name="",this.installed=!1,this.badgeSize="xs"}render(){let t="1";return this.size==="lg"?t="4":this.size==="md"?t="2":this.size==="sm"&&(t="1"),this.style.cssText=` + --local-border-radius: var(--apkt-borderRadius-${t}); + `,this.dataset.size=this.size,this.imageSrc&&(this.dataset.image="true"),this.walletIcon&&(this.dataset.walletIcon=this.walletIcon),V` + ${this.templateVisual()} + `}templateVisual(){return this.imageSrc?V``:this.walletIcon?V``:V``}};Mp.styles=[Me,b8e];Zy([q()],Mp.prototype,"size",void 0);Zy([q()],Mp.prototype,"name",void 0);Zy([q()],Mp.prototype,"imageSrc",void 0);Zy([q()],Mp.prototype,"walletIcon",void 0);Zy([q({type:Boolean})],Mp.prototype,"installed",void 0);Zy([q()],Mp.prototype,"badgeSize",void 0);Mp=Zy([ne("wui-wallet-image")],Mp)});var v8e,E8e=b(()=>{l();Rt();v8e=fe` + :host { + position: relative; + border-radius: ${({borderRadius:e})=>e[2]}; + width: 40px; + height: 40px; + overflow: hidden; + background: ${({tokens:e})=>e.theme.foregroundPrimary}; + display: flex; + justify-content: center; + align-items: center; + flex-wrap: wrap; + column-gap: ${({spacing:e})=>e[1]}; + padding: ${({spacing:e})=>e[1]}; + } + + :host > wui-wallet-image { + width: 14px; + height: 14px; + border-radius: 2px; + } +`});var A8e,pj,$P,C8e=b(()=>{l();he();$e();kr();Mt();Bt();Sx();HP();E8e();A8e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},pj=4,$P=class extends ie{constructor(){super(...arguments),this.walletImages=[]}render(){let t=this.walletImages.lengthV` + + `)} + ${t?[...Array(pj-this.walletImages.length)].map(()=>V` `):null} `}};$P.styles=[Me,v8e];A8e([q({type:Array})],$P.prototype,"walletImages",void 0);$P=A8e([ne("wui-all-wallets-image")],$P)});var S8e,I8e=b(()=>{l();Rt();S8e=fe` + :host { + display: flex; + justify-content: center; + align-items: center; + gap: ${({spacing:e})=>e[1]}; + text-transform: uppercase; + white-space: nowrap; + } + + :host([data-variant='accent']) { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + color: ${({tokens:e})=>e.core.textAccentPrimary}; + } + + :host([data-variant='info']) { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + :host([data-variant='success']) { + background-color: ${({tokens:e})=>e.core.backgroundSuccess}; + color: ${({tokens:e})=>e.core.textSuccess}; + } + + :host([data-variant='warning']) { + background-color: ${({tokens:e})=>e.core.backgroundWarning}; + color: ${({tokens:e})=>e.core.textWarning}; + } + + :host([data-variant='error']) { + background-color: ${({tokens:e})=>e.core.backgroundError}; + color: ${({tokens:e})=>e.core.textError}; + } + + :host([data-variant='certified']) { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + :host([data-size='md']) { + height: 30px; + padding: 0 ${({spacing:e})=>e[2]}; + border-radius: ${({borderRadius:e})=>e[2]}; + } + + :host([data-size='sm']) { + height: 20px; + padding: 0 ${({spacing:e})=>e[1]}; + border-radius: ${({borderRadius:e})=>e[1]}; + } +`});var FP,Ix,hj=b(()=>{l();he();$e();uo();Rs();Mt();Bt();I8e();FP=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ix=class extends ie{constructor(){super(...arguments),this.variant="accent",this.size="md",this.icon=void 0}render(){this.dataset.variant=this.variant,this.dataset.size=this.size;let t=this.size==="md"?"md-medium":"sm-medium",r=this.size==="md"?"md":"sm";return V` + ${this.icon?V``:null} + + + + `}};Ix.styles=[Me,S8e];FP([q()],Ix.prototype,"variant",void 0);FP([q()],Ix.prototype,"size",void 0);FP([q()],Ix.prototype,"icon",void 0);Ix=FP([ne("wui-tag")],Ix)});var T8e,_8e=b(()=>{l();Rt();T8e=fe` + :host { + width: 100%; + } + + button { + column-gap: ${({spacing:e})=>e[2]}; + padding: ${({spacing:e})=>e[3]}; + width: 100%; + background-color: transparent; + border-radius: ${({borderRadius:e})=>e[4]}; + color: ${({tokens:e})=>e.theme.textPrimary}; + } + + button > wui-wallet-image { + background: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + button > wui-text:nth-child(2) { + display: flex; + flex: 1; + } + + button:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + button[data-all-wallets='true'] { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + button[data-all-wallets='true']:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + button:focus-visible:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + box-shadow: 0 0 0 4px ${({tokens:e})=>e.core.foregroundAccent020}; + } + + button:disabled { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + opacity: 0.5; + cursor: not-allowed; + } + + button:disabled > wui-tag { + background-color: ${({tokens:e})=>e.core.glass010}; + color: ${({tokens:e})=>e.theme.foregroundTertiary}; + } + + wui-flex.namespace-icon { + width: 16px; + height: 16px; + border-radius: ${({borderRadius:e})=>e.round}; + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + box-shadow: 0 0 0 2px ${({tokens:e})=>e.theme.backgroundPrimary}; + transition: box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2); + } + + button:hover:enabled wui-flex.namespace-icon { + box-shadow: 0 0 0 2px ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + wui-flex.namespace-icon > wui-icon { + width: 10px; + height: 10px; + } + + wui-flex.namespace-icon:not(:first-child) { + margin-left: -4px; + } +`});var Yi,set,Os,P8e=b(()=>{l();he();$e();kr();uo();Rs();Sx();Mt();Bt();C8e();hj();HP();_8e();Yi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},set={eip155:"ethereum",solana:"solana",bip122:"bitcoin",polkadot:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:"ton"},Os=class extends ie{constructor(){super(...arguments),this.walletImages=[],this.imageSrc="",this.name="",this.size="md",this.tabIdx=void 0,this.namespaces=[],this.disabled=!1,this.showAllWallets=!1,this.loading=!1,this.loadingSpinnerColor="accent-100"}render(){return this.dataset.size=this.size,V` + + `}templateNamespaces(){return this.namespaces?.length?V` + ${this.namespaces.map((t,r)=>V` + + `)} + `:null}templateAllWallets(){return this.showAllWallets&&this.imageSrc?V` `:this.showAllWallets&&this.walletIcon?V` `:null}templateWalletImage(){return!this.showAllWallets&&this.imageSrc?V``:!this.showAllWallets&&!this.imageSrc?V``:null}templateStatus(){return this.loading?V``:this.tagLabel&&this.tagVariant?V`${this.tagLabel}`:null}};Os.styles=[Me,Gt,T8e];Yi([q({type:Array})],Os.prototype,"walletImages",void 0);Yi([q()],Os.prototype,"imageSrc",void 0);Yi([q()],Os.prototype,"name",void 0);Yi([q()],Os.prototype,"size",void 0);Yi([q()],Os.prototype,"tagLabel",void 0);Yi([q()],Os.prototype,"tagVariant",void 0);Yi([q()],Os.prototype,"walletIcon",void 0);Yi([q()],Os.prototype,"tabIdx",void 0);Yi([q({type:Array})],Os.prototype,"namespaces",void 0);Yi([q({type:Boolean})],Os.prototype,"disabled",void 0);Yi([q({type:Boolean})],Os.prototype,"showAllWallets",void 0);Yi([q({type:Boolean})],Os.prototype,"loading",void 0);Yi([q({type:String})],Os.prototype,"loadingSpinnerColor",void 0);Os=Yi([ne("wui-list-wallet")],Os)});var mj=b(()=>{l();P8e()});var Tx,Gy,N8e=b(()=>{l();he();$e();kr();ut();ct();Ve();mj();Tx=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Gy=class extends ie{constructor(){super(),this.unsubscribe=[],this.tabIdx=void 0,this.connectors=re.state.connectors,this.count=ge.state.count,this.filteredCount=ge.state.filteredWallets.length,this.isFetchingRecommendedWallets=ge.state.isFetchingRecommendedWallets,this.unsubscribe.push(re.subscribeKey("connectors",t=>this.connectors=t),ge.subscribeKey("count",t=>this.count=t),ge.subscribeKey("filteredWallets",t=>this.filteredCount=t.length),ge.subscribeKey("isFetchingRecommendedWallets",t=>this.isFetchingRecommendedWallets=t))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){let t=this.connectors.find(u=>u.id==="walletConnect"),{allWallets:r}=Y.state;if(!t||r==="HIDE"||r==="ONLY_MOBILE"&&!se.isMobile())return null;let n=ge.state.featured.length,o=this.count+n,s=o<10?o:Math.floor(o/10)*10,i=this.filteredCount>0?this.filteredCount:s,a=`${i}`;this.filteredCount>0?a=`${this.filteredCount}`:i + `}onAllWallets(){Ae.sendEvent({type:"track",event:"CLICK_ALL_WALLETS"}),J.push("AllWallets",{redirectView:J.state.data?.redirectView})}};Tx([q()],Gy.prototype,"tabIdx",void 0);Tx([le()],Gy.prototype,"connectors",void 0);Tx([le()],Gy.prototype,"count",void 0);Tx([le()],Gy.prototype,"filteredCount",void 0);Tx([le()],Gy.prototype,"isFetchingRecommendedWallets",void 0);Gy=Tx([ne("w3m-all-wallets-widget")],Gy)});var R8e,O8e=b(()=>{l();Ve();R8e=fe` + :host { + margin-top: ${({spacing:e})=>e[1]}; + } + wui-separator { + margin: ${({spacing:e})=>e[3]} calc(${({spacing:e})=>e[3]} * -1) + ${({spacing:e})=>e[2]} calc(${({spacing:e})=>e[3]} * -1); + width: calc(100% + ${({spacing:e})=>e[3]} * 2); + } +`});var _x,Km,B8e=b(()=>{l();he();$e();kr();ut();ct();Ve();jr();Il();O8e();_x=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Km=class extends ie{constructor(){super(),this.unsubscribe=[],this.explorerWallets=ge.state.explorerWallets,this.connections=ee.state.connections,this.connectorImages=Wn.state.connectorImages,this.loadingTelegram=!1,this.unsubscribe.push(ee.subscribeKey("connections",t=>this.connections=t),Wn.subscribeKey("connectorImages",t=>this.connectorImages=t),ge.subscribeKey("explorerFilteredWallets",t=>{this.explorerWallets=t?.length?t:ge.state.explorerWallets}),ge.subscribeKey("explorerWallets",t=>{this.explorerWallets?.length||(this.explorerWallets=t)})),se.isTelegram()&&se.isIos()&&(this.loadingTelegram=!ee.state.wcUri,this.unsubscribe.push(ee.subscribeKey("wcUri",t=>this.loadingTelegram=!t)))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){return V` + ${this.connectorListTemplate()} + `}connectorListTemplate(){return Dn.connectorList().map((t,r)=>t.kind==="connector"?this.renderConnector(t,r):this.renderWallet(t,r))}getConnectorNamespaces(t){return t.subtype==="walletConnect"?[]:t.subtype==="multiChain"?t.connector.connectors?.map(r=>r.chain)||[]:[t.connector.chain]}renderConnector(t,r){let n=t.connector,o=St.getConnectorImage(n)||this.connectorImages[n?.imageId??""],i=(this.connections.get(n.chain)??[]).some(f=>an.isLowerCaseMatch(f.connectorId,n.id)),a,c;t.subtype==="walletConnect"?(a="qr code",c="accent"):t.subtype==="injected"||t.subtype==="announced"?(a=i?"connected":"installed",c=i?"info":"success"):(a=void 0,c=void 0);let u=ee.hasAnyConnection(Z.CONNECTOR_ID.WALLET_CONNECT),d=t.subtype==="walletConnect"||t.subtype==="external"?u:!1;return V` + this.onClickConnector(t)} + tabIdx=${Ce(this.tabIdx)} + ?disabled=${d} + rdnsId=${Ce(n.explorerWallet?.rdns||void 0)} + walletRank=${Ce(n.explorerWallet?.order)} + .namespaces=${this.getConnectorNamespaces(t)} + > + + `}onClickConnector(t){let r=J.state.data?.redirectView;if(t.subtype==="walletConnect"){re.setActiveConnector(t.connector),se.isMobile()?J.push("AllWallets"):J.push("ConnectingWalletConnect",{redirectView:r});return}if(t.subtype==="multiChain"){re.setActiveConnector(t.connector),J.push("ConnectingMultiChain",{redirectView:r});return}if(t.subtype==="injected"){re.setActiveConnector(t.connector),J.push("ConnectingExternal",{connector:t.connector,redirectView:r,wallet:t.connector.explorerWallet});return}if(t.subtype==="announced"){if(t.connector.id==="walletConnect"){se.isMobile()?J.push("AllWallets"):J.push("ConnectingWalletConnect",{redirectView:r});return}J.push("ConnectingExternal",{connector:t.connector,redirectView:r,wallet:t.connector.explorerWallet});return}J.push("ConnectingExternal",{connector:t.connector,redirectView:r})}renderWallet(t,r){let n=t.wallet,o=St.getWalletImage(n),i=ee.hasAnyConnection(Z.CONNECTOR_ID.WALLET_CONNECT),a=this.loadingTelegram,c=t.subtype==="recent"?"recent":void 0,u=t.subtype==="recent"?"info":void 0;return V` + this.onClickWallet(t)} + size="sm" + data-testid=${`wallet-selector-${n.id}`} + tabIdx=${Ce(this.tabIdx)} + ?loading=${a} + ?disabled=${i} + rdnsId=${Ce(n.rdns||void 0)} + walletRank=${Ce(n.order)} + tagLabel=${Ce(c)} + .tagVariant=${u} + > + + `}onClickWallet(t){let r=J.state.data?.redirectView,n=$.state.activeChain;if(t.subtype==="featured"){re.selectWalletConnector(t.wallet);return}if(t.subtype==="recent"){if(this.loadingTelegram)return;re.selectWalletConnector(t.wallet);return}if(t.subtype==="custom"){if(this.loadingTelegram)return;J.push("ConnectingWalletConnect",{wallet:t.wallet,redirectView:r});return}if(this.loadingTelegram)return;let o=n?re.getConnector({id:t.wallet.id,namespace:n}):void 0;o?J.push("ConnectingExternal",{connector:o,redirectView:r}):J.push("ConnectingWalletConnect",{wallet:t.wallet,redirectView:r})}};Km.styles=R8e;_x([q({type:Number})],Km.prototype,"tabIdx",void 0);_x([le()],Km.prototype,"explorerWallets",void 0);_x([le()],Km.prototype,"connections",void 0);_x([le()],Km.prototype,"connectorImages",void 0);_x([le()],Km.prototype,"loadingTelegram",void 0);Km=_x([ne("w3m-connector-list")],Km)});var k8e,U8e=b(()=>{l();Rt();k8e=fe` + :host { + flex: 1; + height: 100%; + } + + button { + width: 100%; + height: 100%; + display: inline-flex; + align-items: center; + padding: ${({spacing:e})=>e[1]} ${({spacing:e})=>e[2]}; + column-gap: ${({spacing:e})=>e[1]}; + color: ${({tokens:e})=>e.theme.textSecondary}; + border-radius: ${({borderRadius:e})=>e[20]}; + background-color: transparent; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color; + } + + /* -- Hover & Active states ----------------------------------------------------------- */ + button[data-active='true'] { + color: ${({tokens:e})=>e.theme.textPrimary}; + background-color: ${({tokens:e})=>e.theme.foregroundTertiary}; + } + + button:hover:enabled:not([data-active='true']), + button:active:enabled:not([data-active='true']) { + wui-text, + wui-icon { + color: ${({tokens:e})=>e.theme.textPrimary}; + } + } +`});var mE,iet,aet,Yy,D8e=b(()=>{l();he();$e();uo();Rs();Mt();Bt();U8e();mE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},iet={lg:"lg-regular",md:"md-regular",sm:"sm-regular"},aet={lg:"md",md:"sm",sm:"sm"},Yy=class extends ie{constructor(){super(...arguments),this.icon="mobile",this.size="md",this.label="",this.active=!1}render(){return V` + + `}};Yy.styles=[Me,Gt,k8e];mE([q()],Yy.prototype,"icon",void 0);mE([q()],Yy.prototype,"size",void 0);mE([q()],Yy.prototype,"label",void 0);mE([q({type:Boolean})],Yy.prototype,"active",void 0);Yy=mE([ne("wui-tab-item")],Yy)});var L8e,M8e=b(()=>{l();Rt();L8e=fe` + :host { + display: inline-flex; + align-items: center; + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + border-radius: ${({borderRadius:e})=>e[32]}; + padding: ${({spacing:e})=>e["01"]}; + box-sizing: border-box; + } + + :host([data-size='sm']) { + height: 26px; + } + + :host([data-size='md']) { + height: 36px; + } +`});var gE,Jy,H8e=b(()=>{l();he();$e();Mt();Bt();D8e();M8e();gE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Jy=class extends ie{constructor(){super(...arguments),this.tabs=[],this.onTabChange=()=>null,this.size="md",this.activeTab=0}render(){return this.dataset.size=this.size,this.tabs.map((t,r)=>{let n=r===this.activeTab;return V` + this.onTabClick(r)} + icon=${t.icon} + size=${this.size} + label=${t.label} + ?active=${n} + data-active=${n} + data-testid="tab-${t.label?.toLowerCase()}" + > + `})}onTabClick(t){this.activeTab=t,this.onTabChange(t)}};Jy.styles=[Me,Gt,L8e];gE([q({type:Array})],Jy.prototype,"tabs",void 0);gE([q()],Jy.prototype,"onTabChange",void 0);gE([q()],Jy.prototype,"size",void 0);gE([le()],Jy.prototype,"activeTab",void 0);Jy=gE([ne("wui-tabs")],Jy)});var $8e=b(()=>{l();H8e()});var gj,zP,F8e=b(()=>{l();he();$e();Ve();jr();$8e();gj=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},zP=class extends ie{constructor(){super(...arguments),this.platformTabs=[],this.unsubscribe=[],this.platforms=[],this.onSelectPlatfrom=void 0}disconnectCallback(){this.unsubscribe.forEach(t=>t())}render(){let t=this.generateTabs();return V` + + + + `}generateTabs(){let t=this.platforms.map(r=>r==="browser"?{label:"Browser",icon:"extension",platform:"browser"}:r==="mobile"?{label:"Mobile",icon:"mobile",platform:"mobile"}:r==="qrcode"?{label:"Mobile",icon:"mobile",platform:"qrcode"}:r==="web"?{label:"Webapp",icon:"browser",platform:"web"}:r==="desktop"?{label:"Desktop",icon:"desktop",platform:"desktop"}:{label:"Browser",icon:"extension",platform:"unsupported"});return this.platformTabs=t.map(({platform:r})=>r),t}onTabChange(t){let r=this.platformTabs[t];r&&this.onSelectPlatfrom?.(r)}};gj([q({type:Array})],zP.prototype,"platforms",void 0);gj([q()],zP.prototype,"onSelectPlatfrom",void 0);zP=gj([ne("w3m-connecting-header")],zP)});var z8e,V8e=b(()=>{l();he();z8e=Er` + :host { + display: flex; + } + + :host([data-size='sm']) > svg { + width: 12px; + height: 12px; + } + + :host([data-size='md']) > svg { + width: 16px; + height: 16px; + } + + :host([data-size='lg']) > svg { + width: 24px; + height: 24px; + } + + :host([data-size='xl']) > svg { + width: 32px; + height: 32px; + } + + svg { + animation: rotate 1.4s linear infinite; + color: var(--local-color); + } + + :host([data-size='md']) > svg > circle { + stroke-width: 6px; + } + + :host([data-size='sm']) > svg > circle { + stroke-width: 8px; + } + + @keyframes rotate { + 100% { + transform: rotate(360deg); + } + } +`});var yj,yE,wE=b(()=>{l();he();$e();Rt();Mt();Bt();V8e();yj=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},yE=class extends ie{constructor(){super(...arguments),this.color="primary",this.size="lg"}render(){let t={primary:$t.tokens.theme.textPrimary,secondary:$t.tokens.theme.textSecondary,tertiary:$t.tokens.theme.textTertiary,invert:$t.tokens.theme.textInvert,error:$t.tokens.core.textError,warning:$t.tokens.core.textWarning,"accent-primary":$t.tokens.core.textAccentPrimary};return this.style.cssText=` + --local-color: ${this.color==="inherit"?"inherit":t[this.color]}; + `,this.dataset.size=this.size,V` + + `}};yE.styles=[Me,z8e];yj([q()],yE.prototype,"color",void 0);yj([q()],yE.prototype,"size",void 0);yE=yj([ne("wui-loading-spinner")],yE)});var j8e,q8e=b(()=>{l();Rt();j8e=fe` + :host { + width: var(--local-width); + } + + button { + width: var(--local-width); + white-space: nowrap; + column-gap: ${({spacing:e})=>e[2]}; + transition: + scale ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-1"]}, + background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + border-radius ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}; + will-change: scale, background-color, border-radius; + cursor: pointer; + } + + /* -- Sizes --------------------------------------------------- */ + button[data-size='sm'] { + border-radius: ${({borderRadius:e})=>e[2]}; + padding: 0 ${({spacing:e})=>e[2]}; + height: 28px; + } + + button[data-size='md'] { + border-radius: ${({borderRadius:e})=>e[3]}; + padding: 0 ${({spacing:e})=>e[4]}; + height: 38px; + } + + button[data-size='lg'] { + border-radius: ${({borderRadius:e})=>e[4]}; + padding: 0 ${({spacing:e})=>e[5]}; + height: 48px; + } + + /* -- Variants --------------------------------------------------------- */ + button[data-variant='accent-primary'] { + background-color: ${({tokens:e})=>e.core.backgroundAccentPrimary}; + color: ${({tokens:e})=>e.theme.textInvert}; + } + + button[data-variant='accent-secondary'] { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + color: ${({tokens:e})=>e.core.textAccentPrimary}; + } + + button[data-variant='neutral-primary'] { + background-color: ${({tokens:e})=>e.theme.backgroundInvert}; + color: ${({tokens:e})=>e.theme.textInvert}; + } + + button[data-variant='neutral-secondary'] { + background-color: transparent; + border: 1px solid ${({tokens:e})=>e.theme.borderSecondary}; + color: ${({tokens:e})=>e.theme.textPrimary}; + } + + button[data-variant='neutral-tertiary'] { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + color: ${({tokens:e})=>e.theme.textPrimary}; + } + + button[data-variant='error-primary'] { + background-color: ${({tokens:e})=>e.core.textError}; + color: ${({tokens:e})=>e.theme.textInvert}; + } + + button[data-variant='error-secondary'] { + background-color: ${({tokens:e})=>e.core.backgroundError}; + color: ${({tokens:e})=>e.core.textError}; + } + + button[data-variant='shade'] { + background: var(--wui-color-gray-glass-002); + color: var(--wui-color-fg-200); + border: none; + box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-005); + } + + /* -- Focus states --------------------------------------------------- */ + button[data-size='sm']:focus-visible:enabled { + border-radius: 28px; + } + + button[data-size='md']:focus-visible:enabled { + border-radius: 38px; + } + + button[data-size='lg']:focus-visible:enabled { + border-radius: 48px; + } + button[data-variant='shade']:focus-visible:enabled { + background: var(--wui-color-gray-glass-005); + box-shadow: + inset 0 0 0 1px var(--wui-color-gray-glass-010), + 0 0 0 4px var(--wui-color-gray-glass-002); + } + + /* -- Hover & Active states ----------------------------------------------------------- */ + @media (hover: hover) { + button[data-size='sm']:hover:enabled { + border-radius: 28px; + } + + button[data-size='md']:hover:enabled { + border-radius: 38px; + } + + button[data-size='lg']:hover:enabled { + border-radius: 48px; + } + + button[data-variant='shade']:hover:enabled { + background: var(--wui-color-gray-glass-002); + } + + button[data-variant='shade']:active:enabled { + background: var(--wui-color-gray-glass-005); + } + } + + button[data-size='sm']:active:enabled { + border-radius: 28px; + } + + button[data-size='md']:active:enabled { + border-radius: 38px; + } + + button[data-size='lg']:active:enabled { + border-radius: 48px; + } + + /* -- Disabled states --------------------------------------------------- */ + button:disabled { + opacity: 0.3; + } +`});var Qy,cet,uet,Hp,wj=b(()=>{l();he();$e();uo();wE();Rs();Mt();Bt();q8e();Qy=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},cet={lg:"lg-regular-mono",md:"md-regular-mono",sm:"sm-regular-mono"},uet={lg:"md",md:"md",sm:"sm"},Hp=class extends ie{constructor(){super(...arguments),this.size="lg",this.disabled=!1,this.fullWidth=!1,this.loading=!1,this.variant="accent-primary"}render(){this.style.cssText=` + --local-width: ${this.fullWidth?"100%":"auto"}; + `;let t=this.textVariant??cet[this.size];return V` + + `}loadingTemplate(){if(this.loading){let t=uet[this.size],r=this.variant==="neutral-primary"||this.variant==="accent-primary"?"invert":"primary";return V``}return null}};Hp.styles=[Me,Gt,j8e];Qy([q()],Hp.prototype,"size",void 0);Qy([q({type:Boolean})],Hp.prototype,"disabled",void 0);Qy([q({type:Boolean})],Hp.prototype,"fullWidth",void 0);Qy([q({type:Boolean})],Hp.prototype,"loading",void 0);Qy([q()],Hp.prototype,"variant",void 0);Qy([q()],Hp.prototype,"textVariant",void 0);Hp=Qy([ne("wui-button")],Hp)});var bE=b(()=>{l();wj()});var $p=b(()=>{l();uo()});var VP=b(()=>{l();Sx()});var W8e,K8e=b(()=>{l();Rt();W8e=fe` + button { + border: none; + background: transparent; + height: 20px; + padding: ${({spacing:e})=>e[2]}; + column-gap: ${({spacing:e})=>e[1]}; + border-radius: ${({borderRadius:e})=>e[1]}; + padding: 0 ${({spacing:e})=>e[1]}; + border-radius: ${({spacing:e})=>e[1]}; + } + + /* -- Variants --------------------------------------------------------- */ + button[data-variant='accent'] { + color: ${({tokens:e})=>e.core.textAccentPrimary}; + } + + button[data-variant='secondary'] { + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + /* -- Focus states --------------------------------------------------- */ + button:focus-visible:enabled { + box-shadow: 0px 0px 0px 4px rgba(9, 136, 240, 0.2); + } + + button[data-variant='accent']:focus-visible:enabled { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + button[data-variant='secondary']:focus-visible:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + /* -- Hover & Active states ----------------------------------------------------------- */ + button[data-variant='accent']:hover:enabled { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + button[data-variant='secondary']:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + button[data-variant='accent']:focus-visible { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + button[data-variant='secondary']:focus-visible { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + box-shadow: 0px 0px 0px 4px rgba(9, 136, 240, 0.2); + } + + button[disabled] { + opacity: 0.5; + cursor: not-allowed; + } +`});var xE,det,fet,Xy,Z8e=b(()=>{l();he();$e();uo();Rs();Mt();Bt();K8e();xE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},det={sm:"sm-medium",md:"md-medium"},fet={accent:"accent-primary",secondary:"secondary"},Xy=class extends ie{constructor(){super(...arguments),this.size="md",this.disabled=!1,this.variant="accent",this.icon=void 0}render(){return V` + + `}iconTemplate(){return this.icon?V``:null}};Xy.styles=[Me,Gt,W8e];xE([q()],Xy.prototype,"size",void 0);xE([q({type:Boolean})],Xy.prototype,"disabled",void 0);xE([q()],Xy.prototype,"variant",void 0);xE([q()],Xy.prototype,"icon",void 0);Xy=xE([ne("wui-link")],Xy)});var jP=b(()=>{l();Z8e()});var G8e,Y8e=b(()=>{l();Rt();G8e=fe` + :host { + display: block; + width: 100px; + height: 100px; + } + + svg { + width: 100px; + height: 100px; + } + + rect { + fill: none; + stroke: ${e=>e.colors.accent100}; + stroke-width: 3px; + stroke-linecap: round; + animation: dash 1s linear infinite; + } + + @keyframes dash { + to { + stroke-dashoffset: 0px; + } + } +`});var J8e,qP,Q8e=b(()=>{l();he();$e();Mt();Bt();Y8e();J8e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},qP=class extends ie{constructor(){super(...arguments),this.radius=36}render(){return this.svgLoaderTemplate()}svgLoaderTemplate(){let t=this.radius>50?50:this.radius,n=36-t,o=116+n,s=245+n,i=360+n*1.75;return V` + + + + `}};qP.styles=[Me,G8e];J8e([q({type:Number})],qP.prototype,"radius",void 0);qP=J8e([ne("wui-loading-thumbnail")],qP)});var X8e=b(()=>{l();Q8e()});var Zn=b(()=>{l();Rs()});var vE=b(()=>{l();HP()});var e4e,t4e=b(()=>{l();Rt();e4e=fe` + wui-flex { + width: 100%; + height: 52px; + box-sizing: border-box; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: ${({borderRadius:e})=>e[5]}; + padding-left: ${({spacing:e})=>e[3]}; + padding-right: ${({spacing:e})=>e[3]}; + display: flex; + align-items: center; + justify-content: space-between; + gap: ${({spacing:e})=>e[6]}; + } + + wui-text { + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + wui-icon { + width: 12px; + height: 12px; + } +`});var WP,Px,r4e=b(()=>{l();he();$e();uo();Rs();$y();Mt();Bt();wj();t4e();WP=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Px=class extends ie{constructor(){super(...arguments),this.disabled=!1,this.label="",this.buttonLabel=""}render(){return V` + + ${this.label} + + ${this.buttonLabel} + + + + `}};Px.styles=[Me,Gt,e4e];WP([q({type:Boolean})],Px.prototype,"disabled",void 0);WP([q()],Px.prototype,"label",void 0);WP([q()],Px.prototype,"buttonLabel",void 0);Px=WP([ne("wui-cta-button")],Px)});var n4e=b(()=>{l();r4e()});var o4e,s4e=b(()=>{l();Ve();o4e=fe` + :host { + display: block; + padding: 0 ${({spacing:e})=>e[5]} ${({spacing:e})=>e[5]}; + } +`});var i4e,KP,ZP=b(()=>{l();he();$e();ct();Ve();n4e();s4e();i4e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},KP=class extends ie{constructor(){super(...arguments),this.wallet=void 0}render(){if(!this.wallet)return this.style.display="none",null;let{name:t,app_store:r,play_store:n,chrome_store:o,homepage:s}=this.wallet,i=se.isMobile(),a=se.isIos(),c=se.isAndroid(),u=[r,n,s,o].filter(Boolean).length>1,d=hr.getTruncateString({string:t,charsStart:12,charsEnd:0,truncate:"end"});return u&&!i?V` + J.push("Downloads",{wallet:this.wallet})} + > + `:!u&&s?V` + + `:r&&a?V` + + `:n&&c?V` + + `:(this.style.display="none",null)}onAppStore(){this.wallet?.app_store&&se.openHref(this.wallet.app_store,"_blank")}onPlayStore(){this.wallet?.play_store&&se.openHref(this.wallet.play_store,"_blank")}onHomePage(){this.wallet?.homepage&&se.openHref(this.wallet.homepage,"_blank")}};KP.styles=[o4e];i4e([q({type:Object})],KP.prototype,"wallet",void 0);KP=i4e([ne("w3m-mobile-download-links")],KP)});var a4e,c4e=b(()=>{l();Ve();a4e=fe` + @keyframes shake { + 0% { + transform: translateX(0); + } + 25% { + transform: translateX(3px); + } + 50% { + transform: translateX(-3px); + } + 75% { + transform: translateX(3px); + } + 100% { + transform: translateX(0); + } + } + + wui-flex:first-child:not(:only-child) { + position: relative; + } + + wui-wallet-image { + width: 56px; + height: 56px; + } + + wui-loading-thumbnail { + position: absolute; + } + + wui-icon-box { + position: absolute; + right: calc(${({spacing:e})=>e[1]} * -1); + bottom: calc(${({spacing:e})=>e[1]} * -1); + opacity: 0; + transform: scale(0.5); + transition-property: opacity, transform; + transition-duration: ${({durations:e})=>e.lg}; + transition-timing-function: ${({easings:e})=>e["ease-out-power-2"]}; + will-change: opacity, transform; + } + + wui-text[align='center'] { + width: 100%; + padding: 0px ${({spacing:e})=>e[4]}; + } + + [data-error='true'] wui-icon-box { + opacity: 1; + transform: scale(1); + } + + [data-error='true'] > wui-flex:first-child { + animation: shake 250ms ${({easings:e})=>e["ease-out-power-2"]} both; + } + + [data-retry='false'] wui-link { + display: none; + } + + [data-retry='true'] wui-link { + display: block; + opacity: 1; + } + + w3m-mobile-download-links { + padding: 0px; + width: 100%; + } +`});var Tl,cn,Nx=b(()=>{l();he();$e();kr();ct();bE();jr();$p();VP();jP();X8e();Zn();vE();ZP();c4e();Tl=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},cn=class extends ie{constructor(){super(),this.wallet=J.state.data?.wallet,this.connector=J.state.data?.connector,this.timeout=void 0,this.secondaryBtnIcon="refresh",this.onConnect=void 0,this.onRender=void 0,this.onAutoConnect=void 0,this.isWalletConnect=!0,this.unsubscribe=[],this.imageSrc=St.getConnectorImage(this.connector)??St.getWalletImage(this.wallet),this.name=this.wallet?.name??this.connector?.name??"Wallet",this.isRetrying=!1,this.uri=ee.state.wcUri,this.error=ee.state.wcError,this.ready=!1,this.showRetry=!1,this.label=void 0,this.secondaryBtnLabel="Try again",this.secondaryLabel="Accept connection request in the wallet",this.isLoading=!1,this.isMobile=!1,this.onRetry=void 0,this.unsubscribe.push(ee.subscribeKey("wcUri",t=>{this.uri=t,this.isRetrying&&this.onRetry&&(this.isRetrying=!1,this.onConnect?.())}),ee.subscribeKey("wcError",t=>this.error=t)),(se.isTelegram()||se.isSafari())&&se.isIos()&&ee.state.wcUri&&this.onConnect?.()}firstUpdated(){this.onAutoConnect?.(),this.showRetry=!this.onAutoConnect}disconnectedCallback(){this.unsubscribe.forEach(t=>t()),ee.setWcError(!1),clearTimeout(this.timeout)}render(){this.onRender?.(),this.onShowRetry();let t=this.error?"Connection can be declined if a previous request is still active":this.secondaryLabel,r="";return this.label?r=this.label:(r=`Continue in ${this.name}`,this.error&&(r="Connection declined")),V` + + + + + ${this.error?null:this.loaderTemplate()} + + + + + + + ${r} + + ${t} + + + ${this.secondaryBtnLabel?V` + + + ${this.secondaryBtnLabel} + + `:null} + + + ${this.isWalletConnect?V` + + + Copy link + + + `:null} + + + + `}onShowRetry(){this.error&&!this.showRetry&&(this.showRetry=!0,this.shadowRoot?.querySelector("wui-button")?.animate([{opacity:0},{opacity:1}],{fill:"forwards",easing:"ease"}))}onTryAgain(){ee.setWcError(!1),this.onRetry?(this.isRetrying=!0,this.onRetry?.()):this.onConnect?.()}loaderTemplate(){let t=nn.state.themeVariables["--w3m-border-radius-master"],r=t?parseInt(t.replace("px",""),10):4;return V``}onCopyUri(){try{this.uri&&(se.copyToClopboard(this.uri),Je.showSuccess("Link copied"))}catch{Je.showError("Failed to copy")}}};cn.styles=a4e;Tl([le()],cn.prototype,"isRetrying",void 0);Tl([le()],cn.prototype,"uri",void 0);Tl([le()],cn.prototype,"error",void 0);Tl([le()],cn.prototype,"ready",void 0);Tl([le()],cn.prototype,"showRetry",void 0);Tl([le()],cn.prototype,"label",void 0);Tl([le()],cn.prototype,"secondaryBtnLabel",void 0);Tl([le()],cn.prototype,"secondaryLabel",void 0);Tl([le()],cn.prototype,"isLoading",void 0);Tl([q({type:Boolean})],cn.prototype,"isMobile",void 0);Tl([q()],cn.prototype,"onRetry",void 0)});var pet,l4e,u4e=b(()=>{l();ut();ct();Ve();Nx();pet=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},l4e=class extends cn{constructor(){if(super(),!this.wallet)throw new Error("w3m-connecting-wc-browser: No wallet provided");this.onConnect=this.onConnectProxy.bind(this),this.onAutoConnect=this.onConnectProxy.bind(this),Ae.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"browser",displayIndex:this.wallet?.display_index,walletRank:this.wallet.order,view:J.state.view}})}async onConnectProxy(){try{this.error=!1;let{connectors:t}=re.state,r=t.find(n=>n.type==="ANNOUNCED"&&n.info?.rdns===this.wallet?.rdns||n.type==="INJECTED"||n.name===this.wallet?.name);if(r)await ee.connectExternal(r,r.chain);else throw new Error("w3m-connecting-wc-browser: No connector found");De.close()}catch(t){t instanceof hc&&t.originalName===js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST?Ae.sendEvent({type:"track",event:"USER_REJECTED",properties:{message:t.message}}):Ae.sendEvent({type:"track",event:"CONNECT_ERROR",properties:{message:t?.message??"Unknown"}}),this.error=!0}}};l4e=pet([ne("w3m-connecting-wc-browser")],l4e)});var het,d4e,f4e=b(()=>{l();ct();Ve();Nx();het=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},d4e=class extends cn{constructor(){if(super(),!this.wallet)throw new Error("w3m-connecting-wc-desktop: No wallet provided");this.onConnect=this.onConnectProxy.bind(this),this.onRender=this.onRenderProxy.bind(this),Ae.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"desktop",displayIndex:this.wallet?.display_index,walletRank:this.wallet.order,view:J.state.view}})}onRenderProxy(){!this.ready&&this.uri&&(this.ready=!0,this.onConnect?.())}onConnectProxy(){if(this.wallet?.desktop_link&&this.uri)try{this.error=!1;let{desktop_link:t,name:r}=this.wallet,{redirect:n,href:o}=se.formatNativeUrl(t,this.uri);ee.setWcLinking({name:r,href:o}),ee.setRecentWallet(this.wallet),se.openHref(n,"_blank")}catch{this.error=!0}}};d4e=het([ne("w3m-connecting-wc-desktop")],d4e)});var Rx,e2,p4e=b(()=>{l();$e();ct();Ve();Nx();Rx=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},e2=class extends cn{constructor(){if(super(),this.btnLabelTimeout=void 0,this.redirectDeeplink=void 0,this.redirectUniversalLink=void 0,this.target=void 0,this.preferUniversalLinks=Y.state.experimental_preferUniversalLinks,this.isLoading=!0,this.onConnect=()=>{fp.onConnectMobile(this.wallet)},!this.wallet)throw new Error("w3m-connecting-wc-mobile: No wallet provided");this.secondaryBtnLabel="Open",this.secondaryLabel=Ye.CONNECT_LABELS.MOBILE,this.secondaryBtnIcon="externalLink",this.onHandleURI(),this.unsubscribe.push(ee.subscribeKey("wcUri",()=>{this.onHandleURI()})),Ae.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"mobile",displayIndex:this.wallet?.display_index,walletRank:this.wallet.order,view:J.state.view}})}disconnectedCallback(){super.disconnectedCallback(),clearTimeout(this.btnLabelTimeout)}onHandleURI(){this.isLoading=!this.uri,!this.ready&&this.uri&&(this.ready=!0,this.onConnect?.())}onTryAgain(){ee.setWcError(!1),this.onConnect?.()}};Rx([le()],e2.prototype,"redirectDeeplink",void 0);Rx([le()],e2.prototype,"redirectUniversalLink",void 0);Rx([le()],e2.prototype,"target",void 0);Rx([le()],e2.prototype,"preferUniversalLinks",void 0);Rx([le()],e2.prototype,"isLoading",void 0);e2=Rx([ne("w3m-connecting-wc-mobile")],e2)});var m4e=_e((PAr,h4e)=>{l();h4e.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Zm=_e(t2=>{l();var bj,met=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];t2.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};t2.getSymbolTotalCodewords=function(t){return met[t]};t2.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t};t2.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');bj=t};t2.isKanjiModeEnabled=function(){return typeof bj<"u"};t2.toSJIS=function(t){return bj(t)}});var GP=_e(Sc=>{l();Sc.L={bit:1};Sc.M={bit:0};Sc.Q={bit:3};Sc.H={bit:2};function get(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return Sc.L;case"m":case"medium":return Sc.M;case"q":case"quartile":return Sc.Q;case"h":case"high":return Sc.H;default:throw new Error("Unknown EC Level: "+e)}}Sc.isValid=function(t){return t&&typeof t.bit<"u"&&t.bit>=0&&t.bit<4};Sc.from=function(t,r){if(Sc.isValid(t))return t;try{return get(t)}catch{return r}}});var w4e=_e((UAr,y4e)=>{l();function g4e(){this.buffer=[],this.length=0}g4e.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let r=0;r>>t-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};y4e.exports=g4e});var x4e=_e((LAr,b4e)=>{l();function EE(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}EE.prototype.set=function(e,t,r,n){let o=e*this.size+t;this.data[o]=r,n&&(this.reservedBit[o]=!0)};EE.prototype.get=function(e,t){return this.data[e*this.size+t]};EE.prototype.xor=function(e,t,r){this.data[e*this.size+t]^=r};EE.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};b4e.exports=EE});var v4e=_e(YP=>{l();var yet=Zm().getSymbolSize;YP.getRowColCoords=function(t){if(t===1)return[];let r=Math.floor(t/7)+2,n=yet(t),o=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let i=1;i{l();var wet=Zm().getSymbolSize,E4e=7;A4e.getPositions=function(t){let r=wet(t);return[[0,0],[r-E4e,0],[0,r-E4e]]}});var S4e=_e(qr=>{l();qr.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var r2={N1:3,N2:3,N3:40,N4:10};qr.isValid=function(t){return t!=null&&t!==""&&!isNaN(t)&&t>=0&&t<=7};qr.from=function(t){return qr.isValid(t)?parseInt(t,10):void 0};qr.getPenaltyN1=function(t){let r=t.size,n=0,o=0,s=0,i=null,a=null;for(let c=0;c=5&&(n+=r2.N1+(o-5)),i=d,o=1),d=t.get(u,c),d===a?s++:(s>=5&&(n+=r2.N1+(s-5)),a=d,s=1)}o>=5&&(n+=r2.N1+(o-5)),s>=5&&(n+=r2.N1+(s-5))}return n};qr.getPenaltyN2=function(t){let r=t.size,n=0;for(let o=0;o=10&&(o===1488||o===93)&&n++,s=s<<1&2047|t.get(a,i),a>=10&&(s===1488||s===93)&&n++}return n*r2.N3};qr.getPenaltyN4=function(t){let r=0,n=t.data.length;for(let s=0;s{l();var Gm=GP(),JP=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],QP=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];xj.getBlocksCount=function(t,r){switch(r){case Gm.L:return JP[(t-1)*4+0];case Gm.M:return JP[(t-1)*4+1];case Gm.Q:return JP[(t-1)*4+2];case Gm.H:return JP[(t-1)*4+3];default:return}};xj.getTotalCodewordsCount=function(t,r){switch(r){case Gm.L:return QP[(t-1)*4+0];case Gm.M:return QP[(t-1)*4+1];case Gm.Q:return QP[(t-1)*4+2];case Gm.H:return QP[(t-1)*4+3];default:return}}});var I4e=_e(eN=>{l();var AE=new Uint8Array(512),XP=new Uint8Array(256);(function(){let t=1;for(let r=0;r<255;r++)AE[r]=t,XP[t]=r,t<<=1,t&256&&(t^=285);for(let r=255;r<512;r++)AE[r]=AE[r-255]})();eN.log=function(t){if(t<1)throw new Error("log("+t+")");return XP[t]};eN.exp=function(t){return AE[t]};eN.mul=function(t,r){return t===0||r===0?0:AE[XP[t]+XP[r]]}});var T4e=_e(CE=>{l();var Ej=I4e();CE.mul=function(t,r){let n=new Uint8Array(t.length+r.length-1);for(let o=0;o=0;){let o=n[0];for(let i=0;i{l();var _4e=T4e();function Aj(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Aj.prototype.initialize=function(t){this.degree=t,this.genPoly=_4e.generateECPolynomial(this.degree)};Aj.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(t.length+this.degree);r.set(t);let n=_4e.mod(r,this.genPoly),o=this.degree-n.length;if(o>0){let s=new Uint8Array(this.degree);return s.set(n,o),s}return n};P4e.exports=Aj});var Cj=_e(R4e=>{l();R4e.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}});var Sj=_e(Fp=>{l();var O4e="[0-9]+",xet="[A-Z $%*+\\-./:]+",SE="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";SE=SE.replace(/u/g,"\\u");var vet="(?:(?![A-Z0-9 $%*+\\-./:]|"+SE+`)(?:.|[\r +]))+`;Fp.KANJI=new RegExp(SE,"g");Fp.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Fp.BYTE=new RegExp(vet,"g");Fp.NUMERIC=new RegExp(O4e,"g");Fp.ALPHANUMERIC=new RegExp(xet,"g");var Eet=new RegExp("^"+SE+"$"),Aet=new RegExp("^"+O4e+"$"),Cet=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Fp.testKanji=function(t){return Eet.test(t)};Fp.testNumeric=function(t){return Aet.test(t)};Fp.testAlphanumeric=function(t){return Cet.test(t)}});var Ym=_e(Gn=>{l();var Iet=Cj(),Ij=Sj();Gn.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};Gn.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};Gn.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};Gn.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};Gn.MIXED={bit:-1};Gn.getCharCountIndicator=function(t,r){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!Iet.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?t.ccBits[0]:r<27?t.ccBits[1]:t.ccBits[2]};Gn.getBestModeForData=function(t){return Ij.testNumeric(t)?Gn.NUMERIC:Ij.testAlphanumeric(t)?Gn.ALPHANUMERIC:Ij.testKanji(t)?Gn.KANJI:Gn.BYTE};Gn.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")};Gn.isValid=function(t){return t&&t.bit&&t.ccBits};function Tet(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"numeric":return Gn.NUMERIC;case"alphanumeric":return Gn.ALPHANUMERIC;case"kanji":return Gn.KANJI;case"byte":return Gn.BYTE;default:throw new Error("Unknown mode: "+e)}}Gn.from=function(t,r){if(Gn.isValid(t))return t;try{return Tet(t)}catch{return r}}});var L4e=_e(n2=>{l();var tN=Zm(),_et=vj(),B4e=GP(),Jm=Ym(),Tj=Cj(),U4e=7973,k4e=tN.getBCHDigit(U4e);function Pet(e,t,r){for(let n=1;n<=40;n++)if(t<=n2.getCapacity(n,r,e))return n}function D4e(e,t){return Jm.getCharCountIndicator(e,t)+4}function Net(e,t){let r=0;return e.forEach(function(n){let o=D4e(n.mode,t);r+=o+n.getBitsLength()}),r}function Ret(e,t){for(let r=1;r<=40;r++)if(Net(e,r)<=n2.getCapacity(r,t,Jm.MIXED))return r}n2.from=function(t,r){return Tj.isValid(t)?parseInt(t,10):r};n2.getCapacity=function(t,r,n){if(!Tj.isValid(t))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=Jm.BYTE);let o=tN.getSymbolTotalCodewords(t),s=_et.getTotalCodewordsCount(t,r),i=(o-s)*8;if(n===Jm.MIXED)return i;let a=i-D4e(n,t);switch(n){case Jm.NUMERIC:return Math.floor(a/10*3);case Jm.ALPHANUMERIC:return Math.floor(a/11*2);case Jm.KANJI:return Math.floor(a/13);case Jm.BYTE:default:return Math.floor(a/8)}};n2.getBestVersionForData=function(t,r){let n,o=B4e.from(r,B4e.M);if(Array.isArray(t)){if(t.length>1)return Ret(t,o);if(t.length===0)return 1;n=t[0]}else n=t;return Pet(n.mode,n.getLength(),o)};n2.getEncodedBits=function(t){if(!Tj.isValid(t)||t<7)throw new Error("Invalid QR Code version");let r=t<<12;for(;tN.getBCHDigit(r)-k4e>=0;)r^=U4e<{l();var _j=Zm(),H4e=1335,Oet=21522,M4e=_j.getBCHDigit(H4e);$4e.getEncodedBits=function(t,r){let n=t.bit<<3|r,o=n<<10;for(;_j.getBCHDigit(o)-M4e>=0;)o^=H4e<<_j.getBCHDigit(o)-M4e;return(n<<10|o)^Oet}});var V4e=_e((lCr,z4e)=>{l();var Bet=Ym();function Ox(e){this.mode=Bet.NUMERIC,this.data=e.toString()}Ox.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)};Ox.prototype.getLength=function(){return this.data.length};Ox.prototype.getBitsLength=function(){return Ox.getBitsLength(this.data.length)};Ox.prototype.write=function(t){let r,n,o;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),o=parseInt(n,10),t.put(o,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),o=parseInt(n,10),t.put(o,s*3+1))};z4e.exports=Ox});var q4e=_e((dCr,j4e)=>{l();var ket=Ym(),Pj=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Bx(e){this.mode=ket.ALPHANUMERIC,this.data=e}Bx.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};Bx.prototype.getLength=function(){return this.data.length};Bx.prototype.getBitsLength=function(){return Bx.getBitsLength(this.data.length)};Bx.prototype.write=function(t){let r;for(r=0;r+2<=this.data.length;r+=2){let n=Pj.indexOf(this.data[r])*45;n+=Pj.indexOf(this.data[r+1]),t.put(n,11)}this.data.length%2&&t.put(Pj.indexOf(this.data[r]),6)};j4e.exports=Bx});var K4e=_e((pCr,W4e)=>{"use strict";l();W4e.exports=function(t){for(var r=[],n=t.length,o=0;o=55296&&s<=56319&&n>o+1){var i=t.charCodeAt(o+1);i>=56320&&i<=57343&&(s=(s-55296)*1024+i-56320+65536,o+=1)}if(s<128){r.push(s);continue}if(s<2048){r.push(s>>6|192),r.push(s&63|128);continue}if(s<55296||s>=57344&&s<65536){r.push(s>>12|224),r.push(s>>6&63|128),r.push(s&63|128);continue}if(s>=65536&&s<=1114111){r.push(s>>18|240),r.push(s>>12&63|128),r.push(s>>6&63|128),r.push(s&63|128);continue}r.push(239,191,189)}return new Uint8Array(r).buffer}});var G4e=_e((mCr,Z4e)=>{l();var Uet=K4e(),Det=Ym();function kx(e){this.mode=Det.BYTE,typeof e=="string"&&(e=Uet(e)),this.data=new Uint8Array(e)}kx.getBitsLength=function(t){return t*8};kx.prototype.getLength=function(){return this.data.length};kx.prototype.getBitsLength=function(){return kx.getBitsLength(this.data.length)};kx.prototype.write=function(e){for(let t=0,r=this.data.length;t{l();var Let=Ym(),Met=Zm();function Ux(e){this.mode=Let.KANJI,this.data=e}Ux.getBitsLength=function(t){return t*13};Ux.prototype.getLength=function(){return this.data.length};Ux.prototype.getBitsLength=function(){return Ux.getBitsLength(this.data.length)};Ux.prototype.write=function(e){let t;for(t=0;t=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` +Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),e.put(r,13)}};Y4e.exports=Ux});var Rj=_e((bCr,Nj)=>{"use strict";l();var IE={single_source_shortest_paths:function(e,t,r){var n={},o={};o[t]=0;var s=IE.PriorityQueue.make();s.push(t,0);for(var i,a,c,u,d,f,p,h,y;!s.empty();){i=s.pop(),a=i.value,u=i.cost,d=e[a]||{};for(c in d)d.hasOwnProperty(c)&&(f=d[c],p=u+f,h=o[c],y=typeof o[c]>"u",(y||h>p)&&(o[c]=p,s.push(c,p),n[c]=a))}if(typeof r<"u"&&typeof o[r]>"u"){var w=["Could not find a path from ",t," to ",r,"."].join("");throw new Error(w)}return n},extract_shortest_path_from_predecessor_list:function(e,t){for(var r=[],n=t,o;n;)r.push(n),o=e[n],n=e[n];return r.reverse(),r},find_path:function(e,t,r){var n=IE.single_source_shortest_paths(e,t,r);return IE.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(e){var t=IE.PriorityQueue,r={},n;e=e||{};for(n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);return r.queue=[],r.sorter=e.sorter||t.default_sorter,r},default_sorter:function(e,t){return e.cost-t.cost},push:function(e,t){var r={value:e,cost:t};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Nj<"u"&&(Nj.exports=IE)});var s3e=_e(Dx=>{l();var mr=Ym(),e3e=V4e(),t3e=q4e(),r3e=G4e(),n3e=J4e(),TE=Sj(),rN=Zm(),Het=Rj();function Q4e(e){return unescape(encodeURIComponent(e)).length}function _E(e,t,r){let n=[],o;for(;(o=e.exec(r))!==null;)n.push({data:o[0],index:o.index,mode:t,length:o[0].length});return n}function o3e(e){let t=_E(TE.NUMERIC,mr.NUMERIC,e),r=_E(TE.ALPHANUMERIC,mr.ALPHANUMERIC,e),n,o;return rN.isKanjiModeEnabled()?(n=_E(TE.BYTE,mr.BYTE,e),o=_E(TE.KANJI,mr.KANJI,e)):(n=_E(TE.BYTE_KANJI,mr.BYTE,e),o=[]),t.concat(r,n,o).sort(function(i,a){return i.index-a.index}).map(function(i){return{data:i.data,mode:i.mode,length:i.length}})}function Oj(e,t){switch(t){case mr.NUMERIC:return e3e.getBitsLength(e);case mr.ALPHANUMERIC:return t3e.getBitsLength(e);case mr.KANJI:return n3e.getBitsLength(e);case mr.BYTE:return r3e.getBitsLength(e)}}function $et(e){return e.reduce(function(t,r){let n=t.length-1>=0?t[t.length-1]:null;return n&&n.mode===r.mode?(t[t.length-1].data+=r.data,t):(t.push(r),t)},[])}function Fet(e){let t=[];for(let r=0;r{l();var oN=Zm(),Bj=GP(),Vet=w4e(),jet=x4e(),qet=v4e(),Wet=C4e(),Dj=S4e(),Lj=vj(),Ket=N4e(),nN=L4e(),Zet=F4e(),Get=Ym(),kj=s3e();function Yet(e,t){let r=e.size,n=Wet.getPositions(t);for(let o=0;o=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?e.set(s+a,i+c,!0,!0):e.set(s+a,i+c,!1,!0))}}function Jet(e){let t=e.size;for(let r=8;r>a&1)===1,e.set(o,s,i,!0),e.set(s,o,i,!0)}function Uj(e,t,r){let n=e.size,o=Zet.getEncodedBits(t,r),s,i;for(s=0;s<15;s++)i=(o>>s&1)===1,s<6?e.set(s,8,i,!0):s<8?e.set(s+1,8,i,!0):e.set(n-15+s,8,i,!0),s<8?e.set(8,n-s-1,i,!0):s<9?e.set(8,15-s-1+1,i,!0):e.set(8,15-s-1,i,!0);e.set(n-8,8,1,!0)}function ett(e,t){let r=e.size,n=-1,o=r-1,s=7,i=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!e.isReserved(o,a-c)){let u=!1;i>>s&1)===1),e.set(o,a-c,u),s--,s===-1&&(i++,s=7)}if(o+=n,o<0||r<=o){o-=n,n=-n;break}}}function ttt(e,t,r){let n=new Vet;r.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),Get.getCharCountIndicator(c.mode,e)),c.write(n)});let o=oN.getSymbolTotalCodewords(e),s=Lj.getTotalCodewordsCount(e,t),i=(o-s)*8;for(n.getLengthInBits()+4<=i&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(i-n.getLengthInBits())/8;for(let c=0;c=7&&Xet(c,t),ett(c,i),isNaN(n)&&(n=Dj.getBestMask(c,Uj.bind(null,c,r))),Dj.applyMask(n,c),Uj(c,r,n),{modules:c,version:t,errorCorrectionLevel:r,maskPattern:n,segments:o}}i3e.create=function(t,r){if(typeof t>"u"||t==="")throw new Error("No input text");let n=Bj.M,o,s;return typeof r<"u"&&(n=Bj.from(r.errorCorrectionLevel,Bj.M),o=nN.from(r.version),s=Dj.from(r.maskPattern),r.toSJISFunc&&oN.setToSJISFunction(r.toSJISFunc)),ntt(t,o,n,s)}});var Mj=_e(o2=>{l();function c3e(e){if(typeof e=="number"&&(e=e.toString()),typeof e!="string")throw new Error("Color should be defined as hex string");let t=e.slice().replace("#","").split("");if(t.length<3||t.length===5||t.length>8)throw new Error("Invalid hex color: "+e);(t.length===3||t.length===4)&&(t=Array.prototype.concat.apply([],t.map(function(n){return[n,n]}))),t.length===6&&t.push("F","F");let r=parseInt(t.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+t.slice(0,6).join("")}}o2.getOptions=function(t){t||(t={}),t.color||(t.color={});let r=typeof t.margin>"u"||t.margin===null||t.margin<0?4:t.margin,n=t.width&&t.width>=21?t.width:void 0,o=t.scale||4;return{width:n,scale:n?4:o,margin:r,color:{dark:c3e(t.color.dark||"#000000ff"),light:c3e(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}};o2.getScale=function(t,r){return r.width&&r.width>=t+r.margin*2?r.width/(t+r.margin*2):r.scale};o2.getImageWidth=function(t,r){let n=o2.getScale(t,r);return Math.floor((t+r.margin*2)*n)};o2.qrToImageData=function(t,r,n){let o=r.modules.size,s=r.modules.data,i=o2.getScale(o,n),a=Math.floor((o+n.margin*2)*i),c=n.margin*i,u=[n.color.light,n.color.dark];for(let d=0;d=c&&f>=c&&d{l();var Hj=Mj();function ott(e,t,r){e.clearRect(0,0,t.width,t.height),t.style||(t.style={}),t.height=r,t.width=r,t.style.height=r+"px",t.style.width=r+"px"}function stt(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}sN.render=function(t,r,n){let o=n,s=r;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),r||(s=stt()),o=Hj.getOptions(o);let i=Hj.getImageWidth(t.modules.size,o),a=s.getContext("2d"),c=a.createImageData(i,i);return Hj.qrToImageData(c.data,t,o),ott(a,s,i),a.putImageData(c,0,0),s};sN.renderToDataURL=function(t,r,n){let o=n;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),o||(o={});let s=sN.render(t,r,o),i=o.type||"image/png",a=o.rendererOpts||{};return s.toDataURL(i,a.quality)}});var f3e=_e(d3e=>{l();var itt=Mj();function u3e(e,t){let r=e.a/255,n=t+'="'+e.hex+'"';return r<1?n+" "+t+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function $j(e,t,r){let n=e+t;return typeof r<"u"&&(n+=" "+r),n}function att(e,t,r){let n="",o=0,s=!1,i=0;for(let a=0;a0&&c>0&&e[a-1]||(n+=s?$j("M",c+r,.5+u+r):$j("m",o,0),o=0,s=!1),c+1':"",u="',d='viewBox="0 0 '+a+" "+a+'"',p=''+c+u+` +`;return typeof n=="function"&&n(null,p),p}});var h3e=_e(PE=>{l();var ctt=m4e(),Fj=a3e(),p3e=l3e(),ltt=f3e();function zj(e,t,r,n,o){let s=[].slice.call(arguments,1),i=s.length,a=typeof s[i-1]=="function";if(!a&&!ctt())throw new Error("Callback required as last argument");if(a){if(i<2)throw new Error("Too few arguments provided");i===2?(o=r,r=t,t=n=void 0):i===3&&(t.getContext&&typeof o>"u"?(o=n,n=void 0):(o=n,n=r,r=t,t=void 0))}else{if(i<1)throw new Error("Too few arguments provided");return i===1?(r=t,t=n=void 0):i===2&&!t.getContext&&(n=r,r=t,t=void 0),new Promise(function(c,u){try{let d=Fj.create(r,n);c(e(d,t,n))}catch(d){u(d)}})}try{let c=Fj.create(r,n);o(null,e(c,t,n))}catch(c){o(c)}}PE.create=Fj.create;PE.toCanvas=zj.bind(null,p3e.render);PE.toDataURL=zj.bind(null,p3e.renderToDataURL);PE.toString=zj.bind(null,function(e,t,r){return ltt.render(e,r)})});function Vj(e,t,r){return e===t?!1:(e-t<0?t-e:e-t)<=r+utt}function dtt(e,t){let r=Array.prototype.slice.call(g3e.default.create(e,{errorCorrectionLevel:t}).modules.data,0),n=Math.sqrt(r.length);return r.reduce((o,s,i)=>(i%n===0?o.push([s]):o[o.length-1].push(s))&&o,[])}var g3e,utt,m3e,zp,y3e,w3e=b(()=>{l();g3e=Ht(h3e(),1);he();utt=.1,m3e=2.5,zp=7;y3e={generate({uri:e,size:t,logoSize:r,padding:n=8,dotColor:o="var(--apkt-colors-black)"}){let i=[],a=dtt(e,"Q"),c=(t-2*n)/a.length,u=[{x:0,y:0},{x:1,y:0},{x:0,y:1}];u.forEach(({x:w,y:x})=>{let v=(a.length-zp)*c*w+n,T=(a.length-zp)*c*x+n,E=.45;for(let S=0;S + `)}});let d=Math.floor((r+25)/c),f=a.length/2-d/2,p=a.length/2+d/2-1,h=[];a.forEach((w,x)=>{w.forEach((v,T)=>{if(a[x][T]&&!(xa.length-(zp+1)&&Ta.length-(zp+1))&&!(x>f&&xf&&T{y[w]?y[w]?.push(x):y[w]=[x]}),Object.entries(y).map(([w,x])=>{let v=x.filter(T=>x.every(E=>!Vj(T,E,c)));return[Number(w),v]}).forEach(([w,x])=>{x.forEach(v=>{i.push(He``)})}),Object.entries(y).filter(([w,x])=>x.length>1).map(([w,x])=>{let v=x.filter(T=>x.some(E=>Vj(T,E,c)));return[Number(w),v]}).map(([w,x])=>{x.sort((T,E)=>TS.some(_=>Vj(T,_,c)));E?E.push(T):v.push([T])}return[w,v.map(T=>[T[0],T[T.length-1]])]}).forEach(([w,x])=>{x.forEach(([v,T])=>{i.push(He` + + `)})}),i}}});var b3e,x3e=b(()=>{l();Rt();b3e=fe` + :host { + position: relative; + user-select: none; + display: block; + overflow: hidden; + aspect-ratio: 1 / 1; + width: 100%; + height: 100%; + background-color: ${({colors:e})=>e.white}; + border: 1px solid ${({tokens:e})=>e.theme.borderPrimary}; + } + + :host { + border-radius: ${({borderRadius:e})=>e[4]}; + display: flex; + align-items: center; + justify-content: center; + } + + :host([data-clear='true']) > wui-icon { + display: none; + } + + svg:first-child, + wui-image, + wui-icon { + position: absolute; + top: 50%; + left: 50%; + transform: translateY(-50%) translateX(-50%); + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + box-shadow: inset 0 0 0 4px ${({tokens:e})=>e.theme.backgroundPrimary}; + border-radius: ${({borderRadius:e})=>e[6]}; + } + + wui-image { + width: 25%; + height: 25%; + border-radius: ${({borderRadius:e})=>e[2]}; + } + + wui-icon { + width: 100%; + height: 100%; + color: #3396ff !important; + transform: translateY(-50%) translateX(-50%) scale(0.25); + } + + wui-icon > svg { + width: inherit; + height: inherit; + } +`});var Qm,Dd,v3e=b(()=>{l();he();$e();uo();Ky();$y();w3e();Mt();Bt();x3e();Qm=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Dd=class extends ie{constructor(){super(...arguments),this.uri="",this.size=500,this.theme="dark",this.imageSrc=void 0,this.alt=void 0,this.arenaClear=void 0,this.farcaster=void 0}render(){return this.dataset.theme=this.theme,this.dataset.clear=String(this.arenaClear),V` + ${this.templateVisual()} ${this.templateSvg()} + `}templateSvg(){return He` + + ${y3e.generate({uri:this.uri,size:this.size,logoSize:this.arenaClear?0:this.size/4})} + + `}templateVisual(){return this.imageSrc?V``:this.farcaster?V``:V``}};Dd.styles=[Me,b3e];Qm([q()],Dd.prototype,"uri",void 0);Qm([q({type:Number})],Dd.prototype,"size",void 0);Qm([q()],Dd.prototype,"theme",void 0);Qm([q()],Dd.prototype,"imageSrc",void 0);Qm([q()],Dd.prototype,"alt",void 0);Qm([q({type:Boolean})],Dd.prototype,"arenaClear",void 0);Qm([q({type:Boolean})],Dd.prototype,"farcaster",void 0);Dd=Qm([ne("wui-qr-code")],Dd)});var E3e=b(()=>{l();v3e()});var A3e,C3e=b(()=>{l();Rt();A3e=fe` + :host { + display: block; + background: linear-gradient( + 90deg, + ${({tokens:e})=>e.theme.foregroundPrimary} 0%, + ${({tokens:e})=>e.theme.foregroundSecondary} 50%, + ${({tokens:e})=>e.theme.foregroundPrimary} 100% + ); + background-size: 200% 100%; + animation: shimmer 2s linear infinite; + border-radius: ${({borderRadius:e})=>e[1]}; + } + + :host([data-rounded='true']) { + border-radius: ${({borderRadius:e})=>e[16]}; + } + + @keyframes shimmer { + 0% { + background-position: 100% 0; + } + 100% { + background-position: -100% 0; + } + } +`});var NE,s2,jj=b(()=>{l();he();$e();Bt();C3e();NE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},s2=class extends ie{constructor(){super(...arguments),this.width="",this.height="",this.variant="default",this.rounded=!1}render(){return this.style.cssText=` + width: ${this.width}; + height: ${this.height}; + `,this.dataset.rounded=this.rounded?"true":"false",V``}};s2.styles=[A3e];NE([q()],s2.prototype,"width",void 0);NE([q()],s2.prototype,"height",void 0);NE([q()],s2.prototype,"variant",void 0);NE([q({type:Boolean})],s2.prototype,"rounded",void 0);s2=NE([ne("wui-shimmer")],s2)});var RE=b(()=>{l();jj()});var S3e,I3e=b(()=>{l();S3e="https://reown.com"});var T3e,_3e=b(()=>{l();Rt();T3e=fe` + .reown-logo { + height: 24px; + } + + a { + text-decoration: none; + cursor: pointer; + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + a:hover { + opacity: 0.9; + } +`});var ftt,qj,P3e=b(()=>{l();he();uo();Rs();$y();I3e();Mt();Bt();_3e();ftt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},qj=class extends ie{render(){return V` + + + UX by + + + + `}};qj.styles=[Me,Gt,T3e];qj=ftt([ne("wui-ux-by-reown")],qj)});var Wj=b(()=>{l();P3e()});var N3e,R3e=b(()=>{l();Ve();N3e=fe` + wui-shimmer { + width: 100%; + aspect-ratio: 1 / 1; + border-radius: ${({borderRadius:e})=>e[4]}; + } + + wui-qr-code { + opacity: 0; + animation-duration: ${({durations:e})=>e.xl}; + animation-timing-function: ${({easings:e})=>e["ease-out-power-2"]}; + animation-name: fade-in; + animation-fill-mode: forwards; + } + + @keyframes fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } + } +`});var O3e,iN,B3e=b(()=>{l();he();$e();kr();ct();Ve();jr();$p();jP();E3e();RE();Zn();Wj();Nx();ZP();R3e();O3e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},iN=class extends cn{constructor(){super(),this.basic=!1}firstUpdated(){this.basic||Ae.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet?.name??"WalletConnect",platform:"qrcode",displayIndex:this.wallet?.display_index,walletRank:this.wallet?.order,view:J.state.view}})}disconnectedCallback(){super.disconnectedCallback(),this.unsubscribe?.forEach(t=>t())}render(){return this.onRenderProxy(),V` + + ${this.qrCodeTemplate()} + Scan this QR Code with your phone + ${this.copyTemplate()} + + + `}onRenderProxy(){!this.ready&&this.uri&&(this.ready=!0)}qrCodeTemplate(){if(!this.uri||!this.ready)return null;let t=this.wallet?this.wallet.name:void 0;ee.setWcLinking(void 0),ee.setRecentWallet(this.wallet);let r=nn.state.themeVariables["--apkt-qr-color"]??nn.state.themeVariables["--w3m-qr-color"];return V` `}copyTemplate(){let t=!this.uri||!this.ready;return V` + Copy link + + `}};iN.styles=N3e;O3e([q({type:Boolean})],iN.prototype,"basic",void 0);iN=O3e([ne("w3m-connecting-wc-qrcode")],iN)});var ptt,k3e,U3e=b(()=>{l();he();kr();ct();Ve();jr();Zn();vE();ZP();ptt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},k3e=class extends ie{constructor(){if(super(),this.wallet=J.state.data?.wallet,!this.wallet)throw new Error("w3m-connecting-wc-unsupported: No wallet provided");Ae.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"browser",displayIndex:this.wallet?.display_index,walletRank:this.wallet?.order,view:J.state.view}})}render(){return V` + + + + Not Detected + + + + `}};k3e=ptt([ne("w3m-connecting-wc-unsupported")],k3e)});var D3e,Kj,L3e=b(()=>{l();$e();ct();Ve();Nx();D3e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Kj=class extends cn{constructor(){if(super(),this.isLoading=!0,!this.wallet)throw new Error("w3m-connecting-wc-web: No wallet provided");this.onConnect=this.onConnectProxy.bind(this),this.secondaryBtnLabel="Open",this.secondaryLabel=Ye.CONNECT_LABELS.MOBILE,this.secondaryBtnIcon="externalLink",this.updateLoadingState(),this.unsubscribe.push(ee.subscribeKey("wcUri",()=>{this.updateLoadingState()})),Ae.sendEvent({type:"track",event:"SELECT_WALLET",properties:{name:this.wallet.name,platform:"web",displayIndex:this.wallet?.display_index,walletRank:this.wallet?.order,view:J.state.view}})}updateLoadingState(){this.isLoading=!this.uri}onConnectProxy(){if(this.wallet?.webapp_link&&this.uri)try{this.error=!1;let{webapp_link:t,name:r}=this.wallet,{redirect:n,href:o}=se.formatUniversalUrl(t,this.uri);ee.setWcLinking({name:r,href:o}),ee.setRecentWallet(this.wallet),se.openHref(n,"_blank")}catch{this.error=!0}}};D3e([le()],Kj.prototype,"isLoading",void 0);Kj=D3e([ne("w3m-connecting-wc-web")],Kj)});var M3e,H3e=b(()=>{l();Ve();M3e=fe` + :host([data-mobile-fullscreen='true']) { + height: 100%; + display: flex; + flex-direction: column; + } + + :host([data-mobile-fullscreen='true']) wui-ux-by-reown { + margin-top: auto; + } +`});var i2,Vp,$3e=b(()=>{l();he();$e();ut();ct();Ve();Il();F8e();u4e();f4e();p4e();B3e();U3e();L3e();H3e();i2=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Vp=class extends ie{constructor(){super(),this.wallet=J.state.data?.wallet,this.unsubscribe=[],this.platform=void 0,this.platforms=[],this.isSiwxEnabled=!!Y.state.siwx,this.remoteFeatures=Y.state.remoteFeatures,this.displayBranding=!0,this.basic=!1,this.determinePlatforms(),this.initializeConnection(),this.unsubscribe.push(Y.subscribeKey("remoteFeatures",t=>this.remoteFeatures=t))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){return Y.state.enableMobileFullScreen&&this.setAttribute("data-mobile-fullscreen","true"),V` + ${this.headerTemplate()} +
${this.platformTemplate()}
+ ${this.reownBrandingTemplate()} + `}reownBrandingTemplate(){return!this.remoteFeatures?.reownBranding||!this.displayBranding?null:V``}async initializeConnection(t=!1){if(!(this.platform==="browser"||Y.state.manualWCControl&&!t))try{let{wcPairingExpiry:r,status:n}=ee.state,{redirectView:o}=J.state.data??{};if(t||Y.state.enableEmbedded||se.isPairingExpired(r)||n==="connecting"){let s=ee.getConnections($.state.activeChain),i=this.remoteFeatures?.multiWallet,a=s.length>0;await ee.connectWalletConnect({cache:"never"}),this.isSiwxEnabled||(a&&i?(J.replace("ProfileWallets"),Je.showSuccess("New Wallet Added")):o?J.replace(o):De.close())}}catch(r){if(r instanceof Error&&r.message.includes("An error occurred when attempting to switch chain")&&!Y.state.enableNetworkSwitch&&$.state.activeChain){$.setActiveCaipNetwork(Du.getUnsupportedNetwork(`${$.state.activeChain}:${$.state.activeCaipNetwork?.id}`)),$.showUnsupportedChainUI();return}r instanceof hc&&r.originalName===js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST?Ae.sendEvent({type:"track",event:"USER_REJECTED",properties:{message:r.message}}):Ae.sendEvent({type:"track",event:"CONNECT_ERROR",properties:{message:r?.message??"Unknown"}}),ee.setWcError(!0),Je.showError(r.message??"Connection error"),ee.resetWcConnection(),J.goBack()}}determinePlatforms(){if(!this.wallet){this.platforms.push("qrcode"),this.platform="qrcode";return}if(this.platform)return;let{mobile_link:t,desktop_link:r,webapp_link:n,injected:o,rdns:s}=this.wallet,i=o?.map(({injected_id:y})=>y).filter(Boolean),a=[...s?[s]:i??[]],c=Y.state.isUniversalProvider?!1:a.length,u=t,d=n,f=ee.checkInstalled(a),p=c&&f,h=r&&!se.isMobile();p&&!$.state.noAdapters&&this.platforms.push("browser"),u&&this.platforms.push(se.isMobile()?"mobile":"qrcode"),d&&this.platforms.push("web"),h&&this.platforms.push("desktop"),!p&&c&&!$.state.noAdapters&&this.platforms.push("unsupported"),this.platform=this.platforms[0]}platformTemplate(){switch(this.platform){case"browser":return V``;case"web":return V``;case"desktop":return V` + this.initializeConnection(!0)}> + + `;case"mobile":return V` + this.initializeConnection(!0)}> + + `;case"qrcode":return V``;default:return V``}}headerTemplate(){return this.platforms.length>1?V` + + + `:null}async onSelectPlatform(t){let r=this.shadowRoot?.querySelector("div");r&&(await r.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.platform=t,r.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"}))}};Vp.styles=M3e;i2([le()],Vp.prototype,"platform",void 0);i2([le()],Vp.prototype,"platforms",void 0);i2([le()],Vp.prototype,"isSiwxEnabled",void 0);i2([le()],Vp.prototype,"remoteFeatures",void 0);i2([q({type:Boolean})],Vp.prototype,"displayBranding",void 0);i2([q({type:Boolean})],Vp.prototype,"basic",void 0);Vp=i2([ne("w3m-connecting-wc-view")],Vp)});var Zj,OE,F3e=b(()=>{l();he();$e();ct();Ve();jr();N8e();B8e();$3e();Zj=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},OE=class extends ie{constructor(){super(),this.unsubscribe=[],this.isMobile=se.isMobile(),this.remoteFeatures=Y.state.remoteFeatures,this.unsubscribe.push(Y.subscribeKey("remoteFeatures",t=>this.remoteFeatures=t))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){if(this.isMobile){let{featured:t,recommended:r}=ge.state,{customWallets:n}=Y.state,o=de.getRecentWallets(),s=t.length||r.length||n?.length||o.length;return V` + ${s?V``:null} + + `}return V` + + + + + + ${this.reownBrandingTemplate()} `}reownBrandingTemplate(){return this.remoteFeatures?.reownBranding?V` + + `:null}};Zj([le()],OE.prototype,"isMobile",void 0);Zj([le()],OE.prototype,"remoteFeatures",void 0);OE=Zj([ne("w3m-connecting-wc-basic-view")],OE)});var GIr,z3e,V3e=b(()=>{l();Up();({I:GIr}=rwe),z3e=e=>e.strings===void 0});function htt(e){this._$AN!==void 0?(aN(this),this._$AM=e,j3e(this)):this._$AM=e}function mtt(e,t=!1,r=0){let n=this._$AH,o=this._$AN;if(o!==void 0&&o.size!==0)if(t)if(Array.isArray(n))for(let s=r;s{l();V3e();pE();pE();BE=(e,t)=>{let r=e._$AN;if(r===void 0)return!1;for(let n of r)n._$AO?.(t,!1),BE(n,t);return!0},aN=e=>{let t,r;do{if((t=e._$AM)===void 0)break;r=t._$AN,r.delete(e),e=t}while(r?.size===0)},j3e=e=>{for(let t;t=e._$AM;e=t){let r=t._$AN;if(r===void 0)t._$AN=r=new Set;else if(r.has(e))break;r.add(e),gtt(t)}};gtt=e=>{e.type==LP.CHILD&&(e._$AP??=mtt,e._$AQ??=htt)},cN=class extends Ex{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,r,n){super._$AT(t,r,n),j3e(this),this.isConnected=t._$AU}_$AO(t,r=!0){t!==this.isConnected&&(this.isConnected=t,t?this.reconnected?.():this.disconnected?.()),r&&(BE(this,t),aN(this))}setValue(t){if(z3e(this._$Ct))this._$Ct._$AI(t,this);else{let r=[...this._$Ct._$AH];r[this._$Ci]=t,this._$Ct._$AI(r,this,0)}}disconnected(){}reconnected(){}}});var Lx,Yj,Gj,Mx,W3e=b(()=>{l();Up();q3e();pE();Lx=()=>new Yj,Yj=class{},Gj=new WeakMap,Mx=fE(class extends cN{render(e){return hn}update(e,[t]){let r=t!==this.G;return r&&this.rt(void 0),(r||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),hn}rt(e){if(this.G!==void 0)if(this.isConnected||(e=void 0),typeof this.G=="function"){let t=this.ht??globalThis,r=Gj.get(t);r===void 0&&(r=new WeakMap,Gj.set(t,r)),r.get(this.G)!==void 0&&this.G.call(this.ht,void 0),r.set(this.G,e),e!==void 0&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return typeof this.G=="function"?Gj.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}})});var lN=b(()=>{l();W3e()});var K3e,Z3e=b(()=>{l();Rt();K3e=fe` + :host { + display: flex; + align-items: center; + justify-content: center; + } + + label { + position: relative; + display: inline-block; + user-select: none; + transition: + background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + color ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + border ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + box-shadow ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + width ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + height ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + transform ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + opacity ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color, color, border, box-shadow, width, height, transform, opacity; + } + + input { + width: 0; + height: 0; + opacity: 0; + } + + span { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: ${({colors:e})=>e.neutrals300}; + border-radius: ${({borderRadius:e})=>e.round}; + border: 1px solid transparent; + will-change: border; + transition: + background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + color ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + border ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + box-shadow ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + width ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + height ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + transform ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + opacity ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color, color, border, box-shadow, width, height, transform, opacity; + } + + span:before { + content: ''; + position: absolute; + background-color: ${({colors:e})=>e.white}; + border-radius: 50%; + } + + /* -- Sizes --------------------------------------------------------- */ + label[data-size='lg'] { + width: 48px; + height: 32px; + } + + label[data-size='md'] { + width: 40px; + height: 28px; + } + + label[data-size='sm'] { + width: 32px; + height: 22px; + } + + label[data-size='lg'] > span:before { + height: 24px; + width: 24px; + left: 4px; + top: 3px; + } + + label[data-size='md'] > span:before { + height: 20px; + width: 20px; + left: 4px; + top: 3px; + } + + label[data-size='sm'] > span:before { + height: 16px; + width: 16px; + left: 3px; + top: 2px; + } + + /* -- Focus states --------------------------------------------------- */ + input:focus-visible:not(:checked) + span, + input:focus:not(:checked) + span { + border: 1px solid ${({tokens:e})=>e.core.iconAccentPrimary}; + background-color: ${({tokens:e})=>e.theme.textTertiary}; + box-shadow: 0px 0px 0px 4px rgba(9, 136, 240, 0.2); + } + + input:focus-visible:checked + span, + input:focus:checked + span { + border: 1px solid ${({tokens:e})=>e.core.iconAccentPrimary}; + box-shadow: 0px 0px 0px 4px rgba(9, 136, 240, 0.2); + } + + /* -- Checked states --------------------------------------------------- */ + input:checked + span { + background-color: ${({tokens:e})=>e.core.iconAccentPrimary}; + } + + label[data-size='lg'] > input:checked + span:before { + transform: translateX(calc(100% - 9px)); + } + + label[data-size='md'] > input:checked + span:before { + transform: translateX(calc(100% - 9px)); + } + + label[data-size='sm'] > input:checked + span:before { + transform: translateX(calc(100% - 7px)); + } + + /* -- Hover states ------------------------------------------------------- */ + label:hover > input:not(:checked):not(:disabled) + span { + background-color: ${({colors:e})=>e.neutrals400}; + } + + label:hover > input:checked:not(:disabled) + span { + background-color: ${({colors:e})=>e.accent080}; + } + + /* -- Disabled state --------------------------------------------------- */ + label:has(input:disabled) { + pointer-events: none; + user-select: none; + } + + input:not(:checked):disabled + span { + background-color: ${({colors:e})=>e.neutrals700}; + } + + input:checked:disabled + span { + background-color: ${({colors:e})=>e.neutrals700}; + } + + input:not(:checked):disabled + span::before { + background-color: ${({colors:e})=>e.neutrals400}; + } + + input:checked:disabled + span::before { + background-color: ${({tokens:e})=>e.theme.textTertiary}; + } +`});var uN,Hx,G3e=b(()=>{l();he();$e();lN();Mt();Bt();Z3e();uN=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Hx=class extends ie{constructor(){super(...arguments),this.inputElementRef=Lx(),this.checked=!1,this.disabled=!1,this.size="md"}render(){return V` + + `}dispatchChangeEvent(){this.dispatchEvent(new CustomEvent("switchChange",{detail:this.inputElementRef.value?.checked,bubbles:!0,composed:!0}))}};Hx.styles=[Me,Gt,K3e];uN([q({type:Boolean})],Hx.prototype,"checked",void 0);uN([q({type:Boolean})],Hx.prototype,"disabled",void 0);uN([q()],Hx.prototype,"size",void 0);Hx=uN([ne("wui-toggle")],Hx)});var Y3e,J3e=b(()=>{l();Rt();Y3e=fe` + :host { + height: auto; + } + + :host > wui-flex { + height: 100%; + display: flex; + align-items: center; + justify-content: center; + column-gap: ${({spacing:e})=>e[2]}; + padding: ${({spacing:e})=>e[2]} ${({spacing:e})=>e[3]}; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: ${({borderRadius:e})=>e[4]}; + box-shadow: inset 0 0 0 1px ${({tokens:e})=>e.theme.foregroundPrimary}; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color; + cursor: pointer; + } + + wui-switch { + pointer-events: none; + } +`});var Q3e,dN,X3e=b(()=>{l();he();$e();Mt();Bt();G3e();J3e();Q3e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},dN=class extends ie{constructor(){super(...arguments),this.checked=!1}render(){return V` + + + + + `}handleToggleChange(t){t.stopPropagation(),this.checked=t.detail,this.dispatchSwitchEvent()}dispatchSwitchEvent(){this.dispatchEvent(new CustomEvent("certifiedSwitchChange",{detail:this.checked,bubbles:!0,composed:!0}))}};dN.styles=[Me,Gt,Y3e];Q3e([q({type:Boolean})],dN.prototype,"checked",void 0);dN=Q3e([ne("wui-certified-switch")],dN)});var e5e=b(()=>{l();X3e()});var t5e,r5e=b(()=>{l();Rt();t5e=fe` + :host { + position: relative; + width: 100%; + display: inline-flex; + flex-direction: column; + gap: ${({spacing:e})=>e[3]}; + color: ${({tokens:e})=>e.theme.textPrimary}; + caret-color: ${({tokens:e})=>e.core.textAccentPrimary}; + } + + .wui-input-text-container { + position: relative; + display: flex; + } + + input { + width: 100%; + border-radius: ${({borderRadius:e})=>e[4]}; + color: inherit; + background: transparent; + border: 1px solid ${({tokens:e})=>e.theme.borderPrimary}; + caret-color: ${({tokens:e})=>e.core.textAccentPrimary}; + padding: ${({spacing:e})=>e[3]} ${({spacing:e})=>e[3]} + ${({spacing:e})=>e[3]} ${({spacing:e})=>e[10]}; + font-size: ${({textSize:e})=>e.large}; + line-height: ${({typography:e})=>e["lg-regular"].lineHeight}; + letter-spacing: ${({typography:e})=>e["lg-regular"].letterSpacing}; + font-weight: ${({fontWeight:e})=>e.regular}; + font-family: ${({fontFamily:e})=>e.regular}; + } + + input[data-size='lg'] { + padding: ${({spacing:e})=>e[4]} ${({spacing:e})=>e[3]} + ${({spacing:e})=>e[4]} ${({spacing:e})=>e[10]}; + } + + @media (hover: hover) and (pointer: fine) { + input:hover:enabled { + border: 1px solid ${({tokens:e})=>e.theme.borderSecondary}; + } + } + + input:disabled { + cursor: unset; + border: 1px solid ${({tokens:e})=>e.theme.borderPrimary}; + } + + input::placeholder { + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + input:focus:enabled { + border: 1px solid ${({tokens:e})=>e.theme.borderSecondary}; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + -webkit-box-shadow: 0px 0px 0px 4px ${({tokens:e})=>e.core.foregroundAccent040}; + -moz-box-shadow: 0px 0px 0px 4px ${({tokens:e})=>e.core.foregroundAccent040}; + box-shadow: 0px 0px 0px 4px ${({tokens:e})=>e.core.foregroundAccent040}; + } + + div.wui-input-text-container:has(input:disabled) { + opacity: 0.5; + } + + wui-icon.wui-input-text-left-icon { + position: absolute; + top: 50%; + transform: translateY(-50%); + pointer-events: none; + left: ${({spacing:e})=>e[4]}; + color: ${({tokens:e})=>e.theme.iconDefault}; + } + + button.wui-input-text-submit-button { + position: absolute; + top: 50%; + transform: translateY(-50%); + right: ${({spacing:e})=>e[3]}; + width: 24px; + height: 24px; + border: none; + background: transparent; + border-radius: ${({borderRadius:e})=>e[2]}; + color: ${({tokens:e})=>e.core.textAccentPrimary}; + } + + button.wui-input-text-submit-button:disabled { + opacity: 1; + } + + button.wui-input-text-submit-button.loading wui-icon { + animation: spin 1s linear infinite; + } + + button.wui-input-text-submit-button:hover { + background: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + input:has(+ .wui-input-text-submit-button) { + padding-right: ${({spacing:e})=>e[12]}; + } + + input[type='number'] { + -moz-appearance: textfield; + } + + input[type='search']::-webkit-search-decoration, + input[type='search']::-webkit-search-cancel-button, + input[type='search']::-webkit-search-results-button, + input[type='search']::-webkit-search-results-decoration { + -webkit-appearance: none; + } + + /* -- Keyframes --------------------------------------------------- */ + @keyframes spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } + } +`});var Ic,Ji,n5e=b(()=>{l();he();$e();kr();lN();uo();Rs();Mt();Bt();r5e();Ic=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ji=class extends ie{constructor(){super(...arguments),this.inputElementRef=Lx(),this.disabled=!1,this.loading=!1,this.placeholder="",this.type="text",this.value="",this.size="md"}render(){return V`
+ ${this.templateLeftIcon()} + + ${this.templateSubmitButton()} + +
+ ${this.templateError()} ${this.templateWarning()}`}templateLeftIcon(){return this.icon?V``:null}templateSubmitButton(){return this.onSubmit?V``:null}templateError(){return this.errorText?V`${this.errorText}`:null}templateWarning(){return this.warningText?V`${this.warningText}`:null}dispatchInputChangeEvent(){this.dispatchEvent(new CustomEvent("inputChange",{detail:this.inputElementRef.value?.value,bubbles:!0,composed:!0}))}};Ji.styles=[Me,Gt,t5e];Ic([q()],Ji.prototype,"icon",void 0);Ic([q({type:Boolean})],Ji.prototype,"disabled",void 0);Ic([q({type:Boolean})],Ji.prototype,"loading",void 0);Ic([q()],Ji.prototype,"placeholder",void 0);Ic([q()],Ji.prototype,"type",void 0);Ic([q()],Ji.prototype,"value",void 0);Ic([q()],Ji.prototype,"errorText",void 0);Ic([q()],Ji.prototype,"warningText",void 0);Ic([q()],Ji.prototype,"onSubmit",void 0);Ic([q()],Ji.prototype,"size",void 0);Ic([q({attribute:!1})],Ji.prototype,"onKeyDown",void 0);Ji=Ic([ne("wui-input-text")],Ji)});var o5e,s5e=b(()=>{l();Rt();o5e=fe` + :host { + position: relative; + display: inline-block; + width: 100%; + } + + wui-icon { + position: absolute; + top: 50%; + transform: translateY(-50%); + right: ${({spacing:e})=>e[3]}; + color: ${({tokens:e})=>e.theme.iconDefault}; + cursor: pointer; + padding: ${({spacing:e})=>e[2]}; + background-color: transparent; + border-radius: ${({borderRadius:e})=>e[4]}; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + } + + @media (hover: hover) { + wui-icon:hover { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + } +`});var i5e,fN,a5e=b(()=>{l();he();$e();lN();Mt();Bt();n5e();s5e();i5e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},fN=class extends ie{constructor(){super(...arguments),this.inputComponentRef=Lx(),this.inputValue=""}render(){return V` + + ${this.inputValue?V``:null} + + `}onInputChange(t){this.inputValue=t.detail||""}clearValue(){let r=this.inputComponentRef.value?.inputElementRef.value;r&&(r.value="",this.inputValue="",r.focus(),r.dispatchEvent(new Event("input")))}};fN.styles=[Me,o5e];i5e([q()],fN.prototype,"inputValue",void 0);fN=i5e([ne("wui-search-bar")],fN)});var c5e=b(()=>{l();a5e()});var pN,Jj=b(()=>{l();he();pN=He` + +`});var l5e,u5e=b(()=>{l();Rt();l5e=fe` + :host { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + height: 104px; + width: 104px; + row-gap: ${({spacing:e})=>e[2]}; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: ${({borderRadius:e})=>e[5]}; + position: relative; + } + + wui-shimmer[data-type='network'] { + border: none; + -webkit-clip-path: var(--apkt-path-network); + clip-path: var(--apkt-path-network); + } + + svg { + position: absolute; + width: 48px; + height: 54px; + z-index: 1; + } + + svg > path { + stroke: ${({tokens:e})=>e.theme.foregroundSecondary}; + stroke-width: 1px; + } + + @media (max-width: 350px) { + :host { + width: 100%; + } + } +`});var d5e,hN,f5e=b(()=>{l();he();$e();Jj();jj();Mt();Bt();u5e();d5e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},hN=class extends ie{constructor(){super(...arguments),this.type="wallet"}render(){return V` + ${this.shimmerTemplate()} + + `}shimmerTemplate(){return this.type==="network"?V` + ${pN}`:V``}};hN.styles=[Me,Gt,l5e];d5e([q()],hN.prototype,"type",void 0);hN=d5e([ne("wui-card-select-loader")],hN)});var p5e=b(()=>{l();f5e()});var h5e,m5e=b(()=>{l();he();h5e=Er` + :host { + display: grid; + width: inherit; + height: inherit; + } +`});var Tc,Qi,g5e=b(()=>{l();he();$e();Mt();gx();Bt();m5e();Tc=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Qi=class extends ie{render(){return this.style.cssText=` + grid-template-rows: ${this.gridTemplateRows}; + grid-template-columns: ${this.gridTemplateColumns}; + justify-items: ${this.justifyItems}; + align-items: ${this.alignItems}; + justify-content: ${this.justifyContent}; + align-content: ${this.alignContent}; + column-gap: ${this.columnGap&&`var(--apkt-spacing-${this.columnGap})`}; + row-gap: ${this.rowGap&&`var(--apkt-spacing-${this.rowGap})`}; + gap: ${this.gap&&`var(--apkt-spacing-${this.gap})`}; + padding-top: ${this.padding&&hr.getSpacingStyles(this.padding,0)}; + padding-right: ${this.padding&&hr.getSpacingStyles(this.padding,1)}; + padding-bottom: ${this.padding&&hr.getSpacingStyles(this.padding,2)}; + padding-left: ${this.padding&&hr.getSpacingStyles(this.padding,3)}; + margin-top: ${this.margin&&hr.getSpacingStyles(this.margin,0)}; + margin-right: ${this.margin&&hr.getSpacingStyles(this.margin,1)}; + margin-bottom: ${this.margin&&hr.getSpacingStyles(this.margin,2)}; + margin-left: ${this.margin&&hr.getSpacingStyles(this.margin,3)}; + `,V``}};Qi.styles=[Me,h5e];Tc([q()],Qi.prototype,"gridTemplateRows",void 0);Tc([q()],Qi.prototype,"gridTemplateColumns",void 0);Tc([q()],Qi.prototype,"justifyItems",void 0);Tc([q()],Qi.prototype,"alignItems",void 0);Tc([q()],Qi.prototype,"justifyContent",void 0);Tc([q()],Qi.prototype,"alignContent",void 0);Tc([q()],Qi.prototype,"columnGap",void 0);Tc([q()],Qi.prototype,"rowGap",void 0);Tc([q()],Qi.prototype,"gap",void 0);Tc([q()],Qi.prototype,"padding",void 0);Tc([q()],Qi.prototype,"margin",void 0);Qi=Tc([ne("wui-grid")],Qi)});var Qj=b(()=>{l();g5e()});var y5e,w5e=b(()=>{l();Ve();y5e=fe` + button { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + cursor: pointer; + width: 104px; + row-gap: ${({spacing:e})=>e[2]}; + padding: ${({spacing:e})=>e[3]} ${({spacing:e})=>e[0]}; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: clamp(0px, ${({borderRadius:e})=>e[4]}, 20px); + transition: + color ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-1"]}, + background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}, + border-radius ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}; + will-change: background-color, color, border-radius; + outline: none; + border: none; + } + + button > wui-flex > wui-text { + color: ${({tokens:e})=>e.theme.textPrimary}; + max-width: 86px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + justify-content: center; + } + + button > wui-flex > wui-text.certified { + max-width: 66px; + } + + @media (hover: hover) and (pointer: fine) { + button:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + } + + button:disabled > wui-flex > wui-text { + color: ${({tokens:e})=>e.core.glass010}; + } + + [data-selected='true'] { + background-color: ${({colors:e})=>e.accent020}; + } + + @media (hover: hover) and (pointer: fine) { + [data-selected='true']:hover:enabled { + background-color: ${({colors:e})=>e.accent010}; + } + } + + [data-selected='true']:active:enabled { + background-color: ${({colors:e})=>e.accent010}; + } + + @media (max-width: 350px) { + button { + width: 100%; + } + } +`});var Ld,_c,Xj=b(()=>{l();he();$e();kr();ct();Ve();jr();$p();RE();Zn();vE();w5e();Ld=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},_c=class extends ie{constructor(){super(),this.observer=new IntersectionObserver(()=>{}),this.visible=!1,this.imageSrc=void 0,this.imageLoading=!1,this.isImpressed=!1,this.explorerId="",this.walletQuery="",this.certified=!1,this.displayIndex=0,this.wallet=void 0,this.observer=new IntersectionObserver(t=>{t.forEach(r=>{r.isIntersecting?(this.visible=!0,this.fetchImageSrc(),this.sendImpressionEvent()):this.visible=!1})},{threshold:.01})}firstUpdated(){this.observer.observe(this)}disconnectedCallback(){this.observer.disconnect()}render(){let t=this.wallet?.badge_type==="certified";return V` + + `}imageTemplate(){return!this.visible&&!this.imageSrc||this.imageLoading?this.shimmerTemplate():V` + + + `}shimmerTemplate(){return V``}async fetchImageSrc(){this.wallet&&(this.imageSrc=St.getWalletImage(this.wallet),!this.imageSrc&&(this.imageLoading=!0,this.imageSrc=await St.fetchWalletImage(this.wallet.image_id),this.imageLoading=!1))}sendImpressionEvent(){!this.wallet||this.isImpressed||(this.isImpressed=!0,Ae.sendWalletImpressionEvent({name:this.wallet.name,walletRank:this.wallet.order,explorerId:this.explorerId,view:J.state.view,query:this.walletQuery,certified:this.certified,displayIndex:this.displayIndex}))}};_c.styles=y5e;Ld([le()],_c.prototype,"visible",void 0);Ld([le()],_c.prototype,"imageSrc",void 0);Ld([le()],_c.prototype,"imageLoading",void 0);Ld([le()],_c.prototype,"isImpressed",void 0);Ld([q()],_c.prototype,"explorerId",void 0);Ld([q()],_c.prototype,"walletQuery",void 0);Ld([q()],_c.prototype,"certified",void 0);Ld([q()],_c.prototype,"displayIndex",void 0);Ld([q({type:Object})],_c.prototype,"wallet",void 0);_c=Ld([ne("w3m-all-wallets-list-item")],_c)});var b5e,x5e=b(()=>{l();Ve();b5e=fe` + wui-grid { + max-height: clamp(360px, 400px, 80vh); + overflow: scroll; + scrollbar-width: none; + grid-auto-rows: min-content; + grid-template-columns: repeat(auto-fill, 104px); + } + + :host([data-mobile-fullscreen='true']) wui-grid { + max-height: none; + } + + @media (max-width: 350px) { + wui-grid { + grid-template-columns: repeat(2, 1fr); + } + } + + wui-grid[data-scroll='false'] { + overflow: hidden; + } + + wui-grid::-webkit-scrollbar { + display: none; + } + + w3m-all-wallets-list-item { + opacity: 0; + animation-duration: ${({durations:e})=>e.xl}; + animation-timing-function: ${({easings:e})=>e["ease-inout-power-2"]}; + animation-name: fade-in; + animation-fill-mode: forwards; + } + + @keyframes fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } + } + + wui-loading-spinner { + padding-top: ${({spacing:e})=>e[4]}; + padding-bottom: ${({spacing:e})=>e[4]}; + justify-content: center; + grid-column: 1 / span 4; + } +`});var kE,v5e,a2,E5e=b(()=>{l();he();$e();kr();ct();Ve();p5e();Qj();Xj();x5e();kE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},v5e="local-paginator",a2=class extends ie{constructor(){super(),this.unsubscribe=[],this.paginationObserver=void 0,this.loading=!ge.state.wallets.length,this.wallets=ge.state.wallets,this.mobileFullScreen=Y.state.enableMobileFullScreen,this.unsubscribe.push(ge.subscribeKey("wallets",t=>this.wallets=t))}firstUpdated(){this.initialFetch(),this.createPaginationObserver()}disconnectedCallback(){this.unsubscribe.forEach(t=>t()),this.paginationObserver?.disconnect()}render(){return this.mobileFullScreen&&this.setAttribute("data-mobile-fullscreen","true"),V` + + ${this.loading?this.shimmerTemplate(16):this.walletsTemplate()} + ${this.paginationLoaderTemplate()} + + `}async initialFetch(){this.loading=!0;let t=this.shadowRoot?.querySelector("wui-grid");t&&(await ge.fetchWalletsByPage({page:1}),await t.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.loading=!1,t.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"}))}shimmerTemplate(t,r){return[...Array(t)].map(()=>V` + + `)}walletsTemplate(){return ys.getWalletConnectWallets(this.wallets).map((t,r)=>V` + this.onConnectWallet(t)} + .wallet=${t} + explorerId=${t.id} + certified=${this.badge==="certified"} + displayIndex=${r} + > + `)}paginationLoaderTemplate(){let{wallets:t,recommended:r,featured:n,count:o,mobileFilteredOutWalletsLength:s}=ge.state,i=window.innerWidth<352?3:4,a=t.length+r.length,u=Math.ceil(a/i)*i-a+i;return u-=t.length?n.length%i:0,o===0&&n.length>0?null:o===0||[...n,...t,...r].length{if(r?.isIntersecting&&!this.loading){let{page:n,count:o,wallets:s}=ge.state;s.length{l();wE()});var A5e,C5e=b(()=>{l();he();A5e=Er` + wui-grid, + wui-loading-spinner, + wui-flex { + height: 360px; + } + + wui-grid { + overflow: scroll; + scrollbar-width: none; + grid-auto-rows: min-content; + grid-template-columns: repeat(auto-fill, 104px); + } + + :host([data-mobile-fullscreen='true']) wui-grid { + max-height: none; + height: auto; + } + + wui-grid[data-scroll='false'] { + overflow: hidden; + } + + wui-grid::-webkit-scrollbar { + display: none; + } + + wui-loading-spinner { + justify-content: center; + align-items: center; + } + + @media (max-width: 350px) { + wui-grid { + grid-template-columns: repeat(2, 1fr); + } + } +`});var DE,c2,S5e=b(()=>{l();he();$e();ct();Ve();jr();Qj();VP();UE();Zn();Xj();C5e();DE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},c2=class extends ie{constructor(){super(...arguments),this.prevQuery="",this.prevBadge=void 0,this.loading=!0,this.mobileFullScreen=Y.state.enableMobileFullScreen,this.query=""}render(){return this.mobileFullScreen&&this.setAttribute("data-mobile-fullscreen","true"),this.onSearch(),this.loading?V``:this.walletsTemplate()}async onSearch(){(this.query.trim()!==this.prevQuery.trim()||this.badge!==this.prevBadge)&&(this.prevQuery=this.query,this.prevBadge=this.badge,this.loading=!0,await ge.searchWallet({search:this.query,badge:this.badge}),this.loading=!1)}walletsTemplate(){let{search:t}=ge.state,r=ys.markWalletsAsInstalled(t),n=ys.filterWalletsByWcSupport(r);return n.length?V` + + ${n.map((o,s)=>V` + this.onConnectWallet(o)} + .wallet=${o} + data-testid="wallet-search-item-${o.id}" + explorerId=${o.id} + certified=${this.badge==="certified"} + walletQuery=${this.query} + displayIndex=${s} + > + `)} + + `:V` + + + + No Wallet found + + + `}onConnectWallet(t){re.selectWalletConnector(t)}};c2.styles=A5e;DE([le()],c2.prototype,"loading",void 0);DE([le()],c2.prototype,"mobileFullScreen",void 0);DE([q()],c2.prototype,"query",void 0);DE([q()],c2.prototype,"badge",void 0);c2=DE([ne("w3m-all-wallets-search")],c2)});var eq,LE,I5e=b(()=>{l();he();$e();ct();Ve();e5e();jr();VP();c5e();E5e();S5e();eq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},LE=class extends ie{constructor(){super(...arguments),this.search="",this.badge=void 0,this.onDebouncedSearch=se.debounce(t=>{this.search=t})}render(){let t=this.search.length>=2;return V` + + + + ${this.qrButtonTemplate()} + + ${t||this.badge?V``:V``} + `}onInputChange(t){this.onDebouncedSearch(t.detail)}onCertifiedSwitchChange(t){t.detail?(this.badge="certified",Je.showSvg("Only WalletConnect certified",{icon:"walletConnectBrown",iconColor:"accent-100"})):this.badge=void 0}qrButtonTemplate(){return se.isMobile()?V` + + `:null}onWalletConnectQr(){J.push("ConnectingWalletConnect")}};eq([le()],LE.prototype,"search",void 0);eq([le()],LE.prototype,"badge",void 0);LE=eq([ne("w3m-all-wallets-view")],LE)});var T5e,_5e=b(()=>{l();Rt();T5e=fe` + :host { + width: 100%; + } + + :host([data-type='primary']) > button { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + } + + :host([data-type='secondary']) > button { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + button { + display: flex; + align-items: center; + justify-content: space-between; + padding: ${({spacing:e})=>e[3]}; + width: 100%; + border-radius: ${({borderRadius:e})=>e[4]}; + transition: + background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + scale ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color, scale; + } + + wui-text { + text-transform: capitalize; + } + + wui-image { + color: ${({tokens:e})=>e.theme.textPrimary}; + } + + @media (hover: hover) { + :host([data-type='primary']) > button:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + :host([data-type='secondary']) > button:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + } + + button:disabled { + opacity: 0.5; + cursor: not-allowed; + } +`});var Xi,Bs,P5e=b(()=>{l();he();$e();kr();wE();Rs();Mt();Bt();_5e();Xi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Bs=class extends ie{constructor(){super(...arguments),this.type="primary",this.imageSrc="google",this.imageSize=void 0,this.loading=!1,this.boxColor="foregroundPrimary",this.disabled=!1,this.rightIcon=!0,this.boxed=!0,this.rounded=!1,this.fullSize=!1}render(){return this.dataset.rounded=this.rounded?"true":"false",this.dataset.type=this.type,V` + + `}templateLeftIcon(){return this.icon?V``:V``}templateRightIcon(){return this.rightIcon?this.loading?V``:V``:null}};Bs.styles=[Me,Gt,T5e];Xi([q()],Bs.prototype,"type",void 0);Xi([q()],Bs.prototype,"imageSrc",void 0);Xi([q()],Bs.prototype,"imageSize",void 0);Xi([q()],Bs.prototype,"icon",void 0);Xi([q()],Bs.prototype,"iconColor",void 0);Xi([q({type:Boolean})],Bs.prototype,"loading",void 0);Xi([q()],Bs.prototype,"tabIdx",void 0);Xi([q()],Bs.prototype,"boxColor",void 0);Xi([q({type:Boolean})],Bs.prototype,"disabled",void 0);Xi([q({type:Boolean})],Bs.prototype,"rightIcon",void 0);Xi([q({type:Boolean})],Bs.prototype,"boxed",void 0);Xi([q({type:Boolean})],Bs.prototype,"rounded",void 0);Xi([q({type:Boolean})],Bs.prototype,"fullSize",void 0);Bs=Xi([ne("wui-list-item")],Bs)});var tq=b(()=>{l();P5e()});var ytt,rq,N5e=b(()=>{l();he();ct();Ve();jr();tq();Zn();ytt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},rq=class extends ie{constructor(){super(...arguments),this.wallet=J.state.data?.wallet}render(){if(!this.wallet)throw new Error("w3m-downloads-view");return V` + + ${this.chromeTemplate()} ${this.iosTemplate()} ${this.androidTemplate()} + ${this.homepageTemplate()} + + `}chromeTemplate(){return this.wallet?.chrome_store?V` + Chrome Extension + `:null}iosTemplate(){return this.wallet?.app_store?V` + iOS App + `:null}androidTemplate(){return this.wallet?.play_store?V` + Android App + `:null}homepageTemplate(){return this.wallet?.homepage?V` + + Website + + `:null}openStore(t){t.href&&this.wallet&&(Ae.sendEvent({type:"track",event:"GET_WALLET",properties:{name:this.wallet.name,walletRank:this.wallet.order,explorerId:this.wallet.id,type:t.type}}),se.openHref(t.href,"_blank"))}onChromeStore(){this.wallet?.chrome_store&&this.openStore({href:this.wallet.chrome_store,type:"chrome_store"})}onAppStore(){this.wallet?.app_store&&this.openStore({href:this.wallet.app_store,type:"app_store"})}onPlayStore(){this.wallet?.play_store&&this.openStore({href:this.wallet.play_store,type:"play_store"})}onHomePage(){this.wallet?.homepage&&this.openStore({href:this.wallet.homepage,type:"homepage"})}};rq=ytt([ne("w3m-downloads-view")],rq)});var R5e={};Te(R5e,{W3mAllWalletsView:()=>LE,W3mConnectingWcBasicView:()=>OE,W3mDownloadsView:()=>rq});var O5e=b(()=>{l();F3e();I5e();N5e()});var B5e,k5e=b(()=>{l();Rt();B5e=fe` + :host { + display: block; + border-radius: clamp(0px, ${({borderRadius:e})=>e[8]}, 44px); + box-shadow: 0 0 0 1px ${({tokens:e})=>e.theme.foregroundPrimary}; + overflow: hidden; + } +`});var wtt,nq,U5e=b(()=>{l();he();Mt();Bt();k5e();wtt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},nq=class extends ie{render(){return V``}};nq.styles=[Me,B5e];nq=wtt([ne("wui-card")],nq)});var D5e=b(()=>{l();U5e()});var L5e,M5e=b(()=>{l();Rt();L5e=fe` + :host { + width: 100%; + } + + :host > wui-flex { + width: 100%; + display: flex; + align-items: center; + justify-content: center; + gap: ${({spacing:e})=>e[2]}; + padding: ${({spacing:e})=>e[3]}; + border-radius: ${({borderRadius:e})=>e[6]}; + border: 1px solid ${({tokens:e})=>e.theme.borderPrimary}; + box-sizing: border-box; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + box-shadow: 0px 0px 16px 0px rgba(0, 0, 0, 0.25); + color: ${({tokens:e})=>e.theme.textPrimary}; + } + + :host > wui-flex[data-type='info'] { + .icon-box { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + + wui-icon { + color: ${({tokens:e})=>e.theme.iconDefault}; + } + } + } + :host > wui-flex[data-type='success'] { + .icon-box { + background-color: ${({tokens:e})=>e.core.backgroundSuccess}; + + wui-icon { + color: ${({tokens:e})=>e.core.borderSuccess}; + } + } + } + :host > wui-flex[data-type='warning'] { + .icon-box { + background-color: ${({tokens:e})=>e.core.backgroundWarning}; + + wui-icon { + color: ${({tokens:e})=>e.core.borderWarning}; + } + } + } + :host > wui-flex[data-type='error'] { + .icon-box { + background-color: ${({tokens:e})=>e.core.backgroundError}; + + wui-icon { + color: ${({tokens:e})=>e.core.borderError}; + } + } + } + + wui-flex { + width: 100%; + } + + wui-text { + word-break: break-word; + flex: 1; + } + + .close { + cursor: pointer; + color: ${({tokens:e})=>e.theme.iconDefault}; + } + + .icon-box { + height: 40px; + width: 40px; + border-radius: ${({borderRadius:e})=>e[2]}; + background-color: var(--local-icon-bg-value); + } +`});var oq,btt,ME,H5e=b(()=>{l();he();$e();kr();ct();uo();Rs();$y();Mt();Bt();M5e();oq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},btt={info:"info",success:"checkmark",warning:"warningCircle",error:"warning"},ME=class extends ie{constructor(){super(...arguments),this.message="",this.type="info"}render(){return V` + + + + + + ${this.message} + + + + `}onClose(){sn.close()}};ME.styles=[Me,L5e];oq([q()],ME.prototype,"message",void 0);oq([q()],ME.prototype,"type",void 0);ME=oq([ne("wui-alertbar")],ME)});var $5e=b(()=>{l();H5e()});var F5e,z5e=b(()=>{l();Ve();F5e=fe` + :host { + display: block; + position: absolute; + top: ${({spacing:e})=>e[3]}; + left: ${({spacing:e})=>e[4]}; + right: ${({spacing:e})=>e[4]}; + opacity: 0; + pointer-events: none; + } +`});var V5e,xtt,mN,j5e=b(()=>{l();he();$e();ct();Ve();$5e();z5e();V5e=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},xtt={info:{backgroundColor:"fg-350",iconColor:"fg-325",icon:"info"},success:{backgroundColor:"success-glass-reown-020",iconColor:"success-125",icon:"checkmark"},warning:{backgroundColor:"warning-glass-reown-020",iconColor:"warning-100",icon:"warningCircle"},error:{backgroundColor:"error-glass-reown-020",iconColor:"error-125",icon:"warning"}},mN=class extends ie{constructor(){super(),this.unsubscribe=[],this.open=sn.state.open,this.onOpen(!0),this.unsubscribe.push(sn.subscribeKey("open",t=>{this.open=t,this.onOpen(!1)}))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){let{message:t,variant:r}=sn.state,n=xtt[r];return V` + + `}onOpen(t){this.open?(this.animate([{opacity:0,transform:"scale(0.85)"},{opacity:1,transform:"scale(1)"}],{duration:150,fill:"forwards",easing:"ease"}),this.style.cssText="pointer-events: auto"):t||(this.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(0.85)"}],{duration:150,fill:"forwards",easing:"ease"}),this.style.cssText="pointer-events: none")}};mN.styles=F5e;V5e([le()],mN.prototype,"open",void 0);mN=V5e([ne("w3m-alertbar")],mN)});var q5e,W5e=b(()=>{l();Rt();q5e=fe` + :host { + position: relative; + } + + button { + display: flex; + justify-content: center; + align-items: center; + background-color: transparent; + padding: ${({spacing:e})=>e[1]}; + } + + /* -- Colors --------------------------------------------------- */ + button[data-type='accent'] wui-icon { + color: ${({tokens:e})=>e.core.iconAccentPrimary}; + } + + button[data-type='neutral'][data-variant='primary'] wui-icon { + color: ${({tokens:e})=>e.theme.iconInverse}; + } + + button[data-type='neutral'][data-variant='secondary'] wui-icon { + color: ${({tokens:e})=>e.theme.iconDefault}; + } + + button[data-type='success'] wui-icon { + color: ${({tokens:e})=>e.core.iconSuccess}; + } + + button[data-type='error'] wui-icon { + color: ${({tokens:e})=>e.core.iconError}; + } + + /* -- Sizes --------------------------------------------------- */ + button[data-size='xs'] { + width: 16px; + height: 16px; + + border-radius: ${({borderRadius:e})=>e[1]}; + } + + button[data-size='sm'] { + width: 20px; + height: 20px; + border-radius: ${({borderRadius:e})=>e[1]}; + } + + button[data-size='md'] { + width: 24px; + height: 24px; + border-radius: ${({borderRadius:e})=>e[2]}; + } + + button[data-size='lg'] { + width: 28px; + height: 28px; + border-radius: ${({borderRadius:e})=>e[2]}; + } + + button[data-size='xs'] wui-icon { + width: 8px; + height: 8px; + } + + button[data-size='sm'] wui-icon { + width: 12px; + height: 12px; + } + + button[data-size='md'] wui-icon { + width: 16px; + height: 16px; + } + + button[data-size='lg'] wui-icon { + width: 20px; + height: 20px; + } + + /* -- Hover --------------------------------------------------- */ + @media (hover: hover) { + button[data-type='accent']:hover:enabled { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + button[data-variant='primary'][data-type='neutral']:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + button[data-variant='secondary'][data-type='neutral']:hover:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + button[data-type='success']:hover:enabled { + background-color: ${({tokens:e})=>e.core.backgroundSuccess}; + } + + button[data-type='error']:hover:enabled { + background-color: ${({tokens:e})=>e.core.backgroundError}; + } + } + + /* -- Focus --------------------------------------------------- */ + button:focus-visible { + box-shadow: 0 0 0 4px ${({tokens:e})=>e.core.foregroundAccent020}; + } + + /* -- Properties --------------------------------------------------- */ + button[data-full-width='true'] { + width: 100%; + } + + :host([fullWidth]) { + width: 100%; + } + + button[disabled] { + opacity: 0.5; + cursor: not-allowed; + } +`});var Xm,Md,K5e=b(()=>{l();he();$e();kr();uo();Mt();Bt();W5e();Xm=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Md=class extends ie{constructor(){super(...arguments),this.icon="card",this.variant="primary",this.type="accent",this.size="md",this.iconSize=void 0,this.fullWidth=!1,this.disabled=!1}render(){return V``}};Md.styles=[Me,Gt,q5e];Xm([q()],Md.prototype,"icon",void 0);Xm([q()],Md.prototype,"variant",void 0);Xm([q()],Md.prototype,"type",void 0);Xm([q()],Md.prototype,"size",void 0);Xm([q()],Md.prototype,"iconSize",void 0);Xm([q({type:Boolean})],Md.prototype,"fullWidth",void 0);Xm([q({type:Boolean})],Md.prototype,"disabled",void 0);Md=Xm([ne("wui-icon-button")],Md)});var sq=b(()=>{l();K5e()});var Z5e,G5e=b(()=>{l();Rt();Z5e=fe` + button { + display: block; + display: flex; + align-items: center; + padding: ${({spacing:e})=>e[1]}; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color; + border-radius: ${({borderRadius:e})=>e[32]}; + } + + wui-image { + border-radius: 100%; + } + + wui-text { + padding-left: ${({spacing:e})=>e[1]}; + } + + .left-icon-container, + .right-icon-container { + width: 24px; + height: 24px; + justify-content: center; + align-items: center; + } + + wui-icon { + color: ${({tokens:e})=>e.theme.iconDefault}; + } + + /* -- Sizes --------------------------------------------------- */ + button[data-size='lg'] { + height: 32px; + } + + button[data-size='md'] { + height: 28px; + } + + button[data-size='sm'] { + height: 24px; + } + + button[data-size='lg'] wui-image { + width: 24px; + height: 24px; + } + + button[data-size='md'] wui-image { + width: 20px; + height: 20px; + } + + button[data-size='sm'] wui-image { + width: 16px; + height: 16px; + } + + button[data-size='lg'] .left-icon-container { + width: 24px; + height: 24px; + } + + button[data-size='md'] .left-icon-container { + width: 20px; + height: 20px; + } + + button[data-size='sm'] .left-icon-container { + width: 16px; + height: 16px; + } + + /* -- Variants --------------------------------------------------------- */ + button[data-type='filled-dropdown'] { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + button[data-type='text-dropdown'] { + background-color: transparent; + } + + /* -- Focus states --------------------------------------------------- */ + button:focus-visible:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + box-shadow: 0 0 0 4px ${({tokens:e})=>e.core.foregroundAccent040}; + } + + /* -- Hover & Active states ----------------------------------------------------------- */ + @media (hover: hover) and (pointer: fine) { + button:hover:enabled, + button:active:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + } + + /* -- Disabled states --------------------------------------------------- */ + button:disabled { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + opacity: 0.5; + } +`});var $x,vtt,Ett,e1,Y5e=b(()=>{l();he();$e();uo();Ky();Rs();Mt();Bt();G5e();$x=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},vtt={lg:"lg-regular",md:"md-regular",sm:"sm-regular"},Ett={lg:"lg",md:"md",sm:"sm"},e1=class extends ie{constructor(){super(...arguments),this.imageSrc="",this.text="",this.size="lg",this.type="text-dropdown",this.disabled=!1}render(){return V``}textTemplate(){let t=vtt[this.size];return this.text?V`${this.text}`:null}imageTemplate(){if(this.imageSrc)return V``;let t=Ett[this.size];return V` + + `}};e1.styles=[Me,Gt,Z5e];$x([q()],e1.prototype,"imageSrc",void 0);$x([q()],e1.prototype,"text",void 0);$x([q()],e1.prototype,"size",void 0);$x([q()],e1.prototype,"type",void 0);$x([q({type:Boolean})],e1.prototype,"disabled",void 0);e1=$x([ne("wui-select")],e1)});var J5e=b(()=>{l();Y5e()});var Q5e=b(()=>{l();hj()});var jp,iq=b(()=>{l();jp={ACCOUNT_TABS:[{label:"Tokens"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150},VIEWS_WITH_LEGAL_FOOTER:["Connect","ConnectWallets","OnRampTokenSelect","OnRampFiatSelect","OnRampProviders"],VIEWS_WITH_DEFAULT_FOOTER:["Networks"]}});var X5e,eve=b(()=>{l();Rt();X5e=fe` + button { + background-color: transparent; + padding: ${({spacing:e})=>e[1]}; + } + + button:focus-visible { + box-shadow: 0 0 0 4px ${({tokens:e})=>e.core.foregroundAccent020}; + } + + button[data-variant='accent']:hover:enabled, + button[data-variant='accent']:focus-visible { + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + } + + button[data-variant='primary']:hover:enabled, + button[data-variant='primary']:focus-visible, + button[data-variant='secondary']:hover:enabled, + button[data-variant='secondary']:focus-visible { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + button[data-size='xs'] > wui-icon { + width: 8px; + height: 8px; + } + + button[data-size='sm'] > wui-icon { + width: 12px; + height: 12px; + } + + button[data-size='xs'], + button[data-size='sm'] { + border-radius: ${({borderRadius:e})=>e[1]}; + } + + button[data-size='md'], + button[data-size='lg'] { + border-radius: ${({borderRadius:e})=>e[2]}; + } + + button[data-size='md'] > wui-icon { + width: 16px; + height: 16px; + } + + button[data-size='lg'] > wui-icon { + width: 20px; + height: 20px; + } + + button:disabled { + background-color: transparent; + cursor: not-allowed; + opacity: 0.5; + } + + button:hover:not(:disabled) { + background-color: var(--wui-color-accent-glass-015); + } + + button:focus-visible:not(:disabled) { + background-color: var(--wui-color-accent-glass-015); + box-shadow: + inset 0 0 0 1px var(--wui-color-accent-100), + 0 0 0 4px var(--wui-color-accent-glass-020); + } +`});var Fx,t1,tve=b(()=>{l();he();$e();uo();Mt();Bt();eve();Fx=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},t1=class extends ie{constructor(){super(...arguments),this.size="md",this.disabled=!1,this.icon="copy",this.iconColor="default",this.variant="accent"}render(){let t={accent:"accent-primary",primary:"inverse",secondary:"default"};return V` + + `}};t1.styles=[Me,Gt,X5e];Fx([q()],t1.prototype,"size",void 0);Fx([q({type:Boolean})],t1.prototype,"disabled",void 0);Fx([q()],t1.prototype,"icon",void 0);Fx([q()],t1.prototype,"iconColor",void 0);Fx([q()],t1.prototype,"variant",void 0);t1=Fx([ne("wui-icon-link")],t1)});var rve=b(()=>{l();tve()});var gN=b(()=>{l();Ky()});var nve,ove=b(()=>{l();he();nve=He` + +`});var sve,ive=b(()=>{l();he();sve=He` + + + +`});var ave,cve=b(()=>{l();Rt();ave=fe` + :host { + position: relative; + border-radius: inherit; + display: flex; + justify-content: center; + align-items: center; + width: var(--local-width); + height: var(--local-height); + } + + :host([data-round='true']) { + background: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: 100%; + outline: 1px solid ${({tokens:e})=>e.core.glass010}; + } + + svg { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 1; + } + + svg > path { + stroke: var(--local-stroke); + } + + wui-image { + width: 100%; + height: 100%; + -webkit-clip-path: var(--local-path); + clip-path: var(--local-path); + background: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + wui-icon { + transform: translateY(-5%); + width: var(--local-icon-size); + height: var(--local-icon-size); + } +`});var l2,qp,lve=b(()=>{l();he();$e();ove();Jj();ive();uo();Ky();Mt();Bt();cve();l2=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},qp=class extends ie{constructor(){super(...arguments),this.size="md",this.name="uknown",this.networkImagesBySize={sm:sve,md:pN,lg:nve},this.selected=!1,this.round=!1}render(){let t={sm:"4",md:"6",lg:"10"};return this.round?(this.dataset.round="true",this.style.cssText=` + --local-width: var(--apkt-spacing-10); + --local-height: var(--apkt-spacing-10); + --local-icon-size: var(--apkt-spacing-4); + `):this.style.cssText=` + + --local-path: var(--apkt-path-network-${this.size}); + --local-width: var(--apkt-width-network-${this.size}); + --local-height: var(--apkt-height-network-${this.size}); + --local-icon-size: var(--apkt-spacing-${t[this.size]}); + `,V`${this.templateVisual()} ${this.svgTemplate()} `}svgTemplate(){return this.round?null:this.networkImagesBySize[this.size]}templateVisual(){return this.imageSrc?V``:V``}};qp.styles=[Me,ave];l2([q()],qp.prototype,"size",void 0);l2([q()],qp.prototype,"name",void 0);l2([q({type:Object})],qp.prototype,"networkImagesBySize",void 0);l2([q()],qp.prototype,"imageSrc",void 0);l2([q({type:Boolean})],qp.prototype,"selected",void 0);l2([q({type:Boolean})],qp.prototype,"round",void 0);qp=l2([ne("wui-network-image")],qp)});var uve=b(()=>{l();lve()});var dve,fve=b(()=>{l();Rt();dve=fe` + :host { + position: relative; + display: flex; + width: 100%; + height: 1px; + background-color: ${({tokens:e})=>e.theme.borderPrimary}; + justify-content: center; + align-items: center; + } + + :host > wui-text { + position: absolute; + padding: 0px 8px; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color; + } + + :host([data-bg-color='primary']) > wui-text { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + } + + :host([data-bg-color='secondary']) > wui-text { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } +`});var aq,HE,pve=b(()=>{l();he();$e();Rs();Mt();Bt();fve();aq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},HE=class extends ie{constructor(){super(...arguments),this.text="",this.bgColor="primary"}render(){return this.dataset.bgColor=this.bgColor,V`${this.template()}`}template(){return this.text?V`${this.text}`:null}};HE.styles=[Me,dve];aq([q()],HE.prototype,"text",void 0);aq([q()],HE.prototype,"bgColor",void 0);HE=aq([ne("wui-separator")],HE)});var cq=b(()=>{l();pve()});var hve=b(()=>{l();L6()});var pt,Wp,Ot,zx=b(()=>{l();pt={INVALID_PAYMENT_CONFIG:"INVALID_PAYMENT_CONFIG",INVALID_RECIPIENT:"INVALID_RECIPIENT",INVALID_ASSET:"INVALID_ASSET",INVALID_AMOUNT:"INVALID_AMOUNT",UNKNOWN_ERROR:"UNKNOWN_ERROR",UNABLE_TO_INITIATE_PAYMENT:"UNABLE_TO_INITIATE_PAYMENT",INVALID_CHAIN_NAMESPACE:"INVALID_CHAIN_NAMESPACE",GENERIC_PAYMENT_ERROR:"GENERIC_PAYMENT_ERROR",UNABLE_TO_GET_EXCHANGES:"UNABLE_TO_GET_EXCHANGES",ASSET_NOT_SUPPORTED:"ASSET_NOT_SUPPORTED",UNABLE_TO_GET_PAY_URL:"UNABLE_TO_GET_PAY_URL",UNABLE_TO_GET_BUY_STATUS:"UNABLE_TO_GET_BUY_STATUS",UNABLE_TO_GET_TOKEN_BALANCES:"UNABLE_TO_GET_TOKEN_BALANCES",UNABLE_TO_GET_QUOTE:"UNABLE_TO_GET_QUOTE",UNABLE_TO_GET_QUOTE_STATUS:"UNABLE_TO_GET_QUOTE_STATUS",INVALID_RECIPIENT_ADDRESS_FOR_ASSET:"INVALID_RECIPIENT_ADDRESS_FOR_ASSET"},Wp={[pt.INVALID_PAYMENT_CONFIG]:"Invalid payment configuration",[pt.INVALID_RECIPIENT]:"Invalid recipient address",[pt.INVALID_ASSET]:"Invalid asset specified",[pt.INVALID_AMOUNT]:"Invalid payment amount",[pt.INVALID_RECIPIENT_ADDRESS_FOR_ASSET]:"Invalid recipient address for the asset selected",[pt.UNKNOWN_ERROR]:"Unknown payment error occurred",[pt.UNABLE_TO_INITIATE_PAYMENT]:"Unable to initiate payment",[pt.INVALID_CHAIN_NAMESPACE]:"Invalid chain namespace",[pt.GENERIC_PAYMENT_ERROR]:"Unable to process payment",[pt.UNABLE_TO_GET_EXCHANGES]:"Unable to get exchanges",[pt.ASSET_NOT_SUPPORTED]:"Asset not supported by the selected exchange",[pt.UNABLE_TO_GET_PAY_URL]:"Unable to get payment URL",[pt.UNABLE_TO_GET_BUY_STATUS]:"Unable to get buy status",[pt.UNABLE_TO_GET_TOKEN_BALANCES]:"Unable to get token balances",[pt.UNABLE_TO_GET_QUOTE]:"Unable to get quote. Please choose a different token",[pt.UNABLE_TO_GET_QUOTE_STATUS]:"Unable to get quote status"},Ot=class e extends Error{get message(){return Wp[this.code]}constructor(t,r){super(Wp[t]),this.name="AppKitPayError",this.code=t,this.details=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}}});var mve,lq,uq=b(()=>{l();mve="https://rpc.walletconnect.org/v1/json-rpc",lq="reown_test"});function gve(){let{chainNamespace:e}=lt.parseCaipNetworkId(Pe.state.paymentAsset.network);if(!se.isAddress(Pe.state.recipient,e))throw new Ot(pt.INVALID_RECIPIENT_ADDRESS_FOR_ASSET,`Provide valid recipient address for namespace "${e}"`)}async function yve(e,t,r){if(t!==Z.CHAIN.EVM)throw new Ot(pt.INVALID_CHAIN_NAMESPACE);if(!r.fromAddress)throw new Ot(pt.INVALID_PAYMENT_CONFIG,"fromAddress is required for native EVM payments.");let n=typeof r.amount=="string"?parseFloat(r.amount):r.amount;if(isNaN(n))throw new Ot(pt.INVALID_PAYMENT_CONFIG);let o=e.metadata?.decimals??18,s=ee.parseUnits(n.toString(),o);if(typeof s!="bigint")throw new Ot(pt.GENERIC_PAYMENT_ERROR);return await ee.sendTransaction({chainNamespace:t,to:r.recipient,address:r.fromAddress,value:s,data:"0x"})??void 0}async function wve(e,t){if(!t.fromAddress)throw new Ot(pt.INVALID_PAYMENT_CONFIG,"fromAddress is required for ERC20 EVM payments.");let r=e.asset,n=t.recipient,o=Number(e.metadata.decimals),s=ee.parseUnits(t.amount.toString(),o);if(s===void 0)throw new Ot(pt.GENERIC_PAYMENT_ERROR);return await ee.writeContract({fromAddress:t.fromAddress,tokenAddress:r,args:[n,s],method:"transfer",abi:f4.getERC20Abi(r),chainNamespace:Z.CHAIN.EVM})??void 0}async function bve(e,t){if(e!==Z.CHAIN.SOLANA)throw new Ot(pt.INVALID_CHAIN_NAMESPACE);if(!t.fromAddress)throw new Ot(pt.INVALID_PAYMENT_CONFIG,"fromAddress is required for Solana payments.");let r=typeof t.amount=="string"?parseFloat(t.amount):t.amount;if(isNaN(r)||r<=0)throw new Ot(pt.INVALID_PAYMENT_CONFIG,"Invalid payment amount.");try{if(!ar.getProvider(e))throw new Ot(pt.GENERIC_PAYMENT_ERROR,"No Solana provider available.");let o=await ee.sendTransaction({chainNamespace:Z.CHAIN.SOLANA,to:t.recipient,value:r,tokenMint:t.tokenMint});if(!o)throw new Ot(pt.GENERIC_PAYMENT_ERROR,"Transaction failed.");return o}catch(n){throw n instanceof Ot?n:new Ot(pt.GENERIC_PAYMENT_ERROR,`Solana payment failed: ${n}`)}}async function xve({sourceToken:e,toToken:t,amount:r,recipient:n}){let o=ee.parseUnits(r,e.metadata.decimals),s=ee.parseUnits(r,t.metadata.decimals);return Promise.resolve({type:yN,origin:{amount:o?.toString()??"0",currency:e},destination:{amount:s?.toString()??"0",currency:t},fees:[{id:"service",label:"Service Fee",amount:"0",currency:t}],steps:[{requestId:yN,type:"deposit",deposit:{amount:o?.toString()??"0",currency:e.asset,receiver:n}}],timeInSeconds:6})}function $E(e){if(!e)return null;let t=e.steps[0];return!t||t.type!==vve?null:t}function wN(e,t=0){if(!e)return[];let r=e.steps.filter(o=>o.type===Eve),n=r.filter((o,s)=>s+1>t);return r.length>0&&r.length<3?n:[]}var bN=b(()=>{l();ut();ct();Kp();zx();zx()});function Att(){let e=Y.getSnapshot().projectId;return`${mve}?projectId=${e}`}function pq(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t||"appkit",sv:r||"html-wagmi-4.2.2"}}async function hq(e,t){let r=Att(),{sdkType:n,sdkVersion:o,projectId:s}=Y.getSnapshot(),i={jsonrpc:"2.0",id:1,method:e,params:{...t||{},st:n,sv:o,projectId:s}},c=await(await fetch(r,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json"}})).json();if(c.error)throw new dq(c.error.message);return c}async function mq(e){return(await hq("reown_getExchanges",e)).result}async function gq(e){return(await hq("reown_getExchangePayUrl",e)).result}async function Ave(e){return(await hq("reown_getExchangeBuyStatus",e)).result}async function Ctt(e){let t=ht.bigNumber(e.amount).times(10**e.toToken.metadata.decimals).toString(),{chainId:r,chainNamespace:n}=lt.parseCaipNetworkId(e.sourceToken.network),{chainId:o,chainNamespace:s}=lt.parseCaipNetworkId(e.toToken.network),i=e.sourceToken.asset==="native"?EH(n):e.sourceToken.asset,a=e.toToken.asset==="native"?EH(s):e.toToken.asset;return await fq.post({path:"/appkit/v1/transfers/quote",body:{user:e.address,originChainId:r.toString(),originCurrency:i,destinationChainId:o.toString(),destinationCurrency:a,recipient:e.recipient,amount:t},params:pq()})}async function Cve(e){let t=an.isLowerCaseMatch(e.sourceToken.network,e.toToken.network),r=an.isLowerCaseMatch(e.sourceToken.asset,e.toToken.asset);return t&&r?xve(e):Ctt(e)}async function Sve(e){return await fq.get({path:"/appkit/v1/transfers/status",params:{requestId:e.requestId,...pq()}})}async function Ive(e){return await fq.get({path:`/appkit/v1/transfers/assets/exchanges/${e}`,params:pq()})}var fq,dq,Tve=b(()=>{l();ut();ct();Il();uq();bN();fq=new Di({baseUrl:se.getApiUrl(),clientId:null}),dq=class extends Error{}});function xN(e,t){let{chainNamespace:r,chainId:n}=lt.parseCaipNetworkId(e),o=Itt[r];if(!o)throw new Error(`Unsupported chain namespace for CAIP-19 formatting: ${r}`);let s=o.native.assetNamespace,i=o.native.assetReference;return t!=="native"&&(s=o.defaultTokenNamespace,i=t),`${`${r}:${n}`}/${s}:${i}`}function _ve(e){let{chainNamespace:t}=lt.parseCaipNetworkId(e);return Stt.includes(t)}function Pve(e){let r=$.getAllRequestedCaipNetworks().find(o=>o.caipNetworkId===e.chainId),n=e.address;if(!r)throw new Error(`Target network not found for balance chainId "${e.chainId}"`);if(an.isLowerCaseMatch(e.symbol,r.nativeCurrency.symbol))n="native";else if(se.isCaipAddress(n)){let{address:o}=lt.parseCaipAddress(n);n=o}else if(!n)throw new Error(`Balance address not found for balance symbol "${e.symbol}"`);return{network:r.caipNetworkId,asset:n,metadata:{name:e.name,symbol:e.symbol,decimals:Number(e.quantity.decimals),logoURI:e.iconUrl},amount:e.quantity.numeric}}function Nve(e){return{chainId:e.network,address:`${e.network}:${e.asset}`,symbol:e.metadata.symbol,name:e.metadata.name,iconUrl:e.metadata.logoURI||"",price:0,quantity:{numeric:"0",decimals:e.metadata.decimals.toString()}}}function u2(e){let t=ht.bigNumber(e,{safe:!0});return t.lt(.001)?"<0.001":t.round(4).toString()}function Rve(e){let r=$.getAllRequestedCaipNetworks().find(n=>n.caipNetworkId===e.network);return r?!!r.testnet:!1}var Stt,Itt,FE=b(()=>{l();ut();ct();Il();Stt=["eip155","solana"],Itt={eip155:{native:{assetNamespace:"slip44",assetReference:"60"},defaultTokenNamespace:"erc20"},solana:{native:{assetNamespace:"slip44",assetReference:"501"},defaultTokenNamespace:"token"}}});var Ove,yq,yN,vve,Eve,ce,Pe,Kp=b(()=>{l();Lr();Hn();ut();ct();hve();Il();zx();zx();Tve();FE();bN();Ove=0,yq="unknown",yN="direct-transfer",vve="deposit",Eve="transaction",ce=rt({paymentAsset:{network:"eip155:1",asset:"0x0",metadata:{name:"0x0",symbol:"0x0",decimals:0}},recipient:"0x0",amount:0,isConfigured:!1,error:null,isPaymentInProgress:!1,exchanges:[],isLoading:!1,openInNewTab:!0,redirectUrl:void 0,payWithExchange:void 0,currentPayment:void 0,analyticsSet:!1,paymentId:void 0,choice:"pay",tokenBalances:{[Z.CHAIN.EVM]:[],[Z.CHAIN.SOLANA]:[]},isFetchingTokenBalances:!1,selectedPaymentAsset:null,quote:void 0,quoteStatus:"waiting",quoteError:null,isFetchingQuote:!1,selectedExchange:void 0,exchangeUrlForQuote:void 0,requestId:void 0}),Pe={state:ce,subscribe(e){return Dt(ce,()=>e(ce))},subscribeKey(e,t){return Tt(ce,e,t)},async handleOpenPay(e){this.resetState(),this.setPaymentConfig(e),this.initializeAnalytics(),gve(),await this.prepareTokenLogo(),ce.isConfigured=!0,Ae.sendEvent({type:"track",event:"PAY_MODAL_OPEN",properties:{exchanges:ce.exchanges,configuration:{network:ce.paymentAsset.network,asset:ce.paymentAsset.asset,recipient:ce.recipient,amount:ce.amount}}}),await De.open({view:"Pay"})},resetState(){ce.paymentAsset={network:"eip155:1",asset:"0x0",metadata:{name:"0x0",symbol:"0x0",decimals:0}},ce.recipient="0x0",ce.amount=0,ce.isConfigured=!1,ce.error=null,ce.isPaymentInProgress=!1,ce.isLoading=!1,ce.currentPayment=void 0,ce.selectedExchange=void 0,ce.exchangeUrlForQuote=void 0,ce.requestId=void 0},resetQuoteState(){ce.quote=void 0,ce.quoteStatus="waiting",ce.quoteError=null,ce.isFetchingQuote=!1,ce.requestId=void 0},setPaymentConfig(e){if(!e.paymentAsset)throw new Ot(pt.INVALID_PAYMENT_CONFIG);try{ce.choice=e.choice??"pay",ce.paymentAsset=e.paymentAsset,ce.recipient=e.recipient,ce.amount=e.amount,ce.openInNewTab=e.openInNewTab??!0,ce.redirectUrl=e.redirectUrl,ce.payWithExchange=e.payWithExchange,ce.error=null}catch(t){throw new Ot(pt.INVALID_PAYMENT_CONFIG,t.message)}},setSelectedPaymentAsset(e){ce.selectedPaymentAsset=e},setSelectedExchange(e){ce.selectedExchange=e},setRequestId(e){ce.requestId=e},setPaymentInProgress(e){ce.isPaymentInProgress=e},getPaymentAsset(){return ce.paymentAsset},getExchanges(){return ce.exchanges},async fetchExchanges(){try{ce.isLoading=!0;let e=await mq({page:Ove});ce.exchanges=e.exchanges.slice(0,2)}catch{throw Je.showError(Wp.UNABLE_TO_GET_EXCHANGES),new Ot(pt.UNABLE_TO_GET_EXCHANGES)}finally{ce.isLoading=!1}},async getAvailableExchanges(e){try{let t=e?.asset&&e?.network?xN(e.network,e.asset):void 0;return await mq({page:e?.page??Ove,asset:t,amount:e?.amount?.toString()})}catch{throw new Ot(pt.UNABLE_TO_GET_EXCHANGES)}},async getPayUrl(e,t,r=!1){try{let n=Number(t.amount),o=await gq({exchangeId:e,asset:xN(t.network,t.asset),amount:n.toString(),recipient:`${t.network}:${t.recipient}`});return Ae.sendEvent({type:"track",event:"PAY_EXCHANGE_SELECTED",properties:{source:"pay",exchange:{id:e},configuration:{network:t.network,asset:t.asset,recipient:t.recipient,amount:n},currentPayment:{type:"exchange",exchangeId:e},headless:r}}),r&&(this.initiatePayment(),Ae.sendEvent({type:"track",event:"PAY_INITIATED",properties:{source:"pay",paymentId:ce.paymentId||yq,configuration:{network:t.network,asset:t.asset,recipient:t.recipient,amount:n},currentPayment:{type:"exchange",exchangeId:e}}})),o}catch(n){throw n instanceof Error&&n.message.includes("is not supported")?new Ot(pt.ASSET_NOT_SUPPORTED):new Error(n.message)}},async generateExchangeUrlForQuote({exchangeId:e,paymentAsset:t,amount:r,recipient:n}){let o=await gq({exchangeId:e,asset:xN(t.network,t.asset),amount:r.toString(),recipient:n});ce.exchangeSessionId=o.sessionId,ce.exchangeUrlForQuote=o.url},async openPayUrl(e,t,r=!1){try{let n=await this.getPayUrl(e.exchangeId,t,r);if(!n)throw new Ot(pt.UNABLE_TO_GET_PAY_URL);let s=e.openInNewTab??!0?"_blank":"_self";return se.openHref(n.url,s),n}catch(n){throw n instanceof Ot?ce.error=n.message:ce.error=Wp.GENERIC_PAYMENT_ERROR,new Ot(pt.UNABLE_TO_GET_PAY_URL)}},async onTransfer({chainNamespace:e,fromAddress:t,toAddress:r,amount:n,paymentAsset:o}){if(ce.currentPayment={type:"wallet",status:"IN_PROGRESS"},!ce.isPaymentInProgress)try{this.initiatePayment();let i=$.getAllRequestedCaipNetworks().find(c=>c.caipNetworkId===o.network);if(!i)throw new Error("Target network not found");let a=$.state.activeCaipNetwork;switch(an.isLowerCaseMatch(a?.caipNetworkId,i.caipNetworkId)||await $.switchActiveNetwork(i),e){case Z.CHAIN.EVM:o.asset==="native"&&(ce.currentPayment.result=await yve(o,e,{recipient:r,amount:n,fromAddress:t})),o.asset.startsWith("0x")&&(ce.currentPayment.result=await wve(o,{recipient:r,amount:n,fromAddress:t})),ce.currentPayment.status="SUCCESS";break;case Z.CHAIN.SOLANA:ce.currentPayment.result=await bve(e,{recipient:r,amount:n,fromAddress:t,tokenMint:o.asset==="native"?void 0:o.asset}),ce.currentPayment.status="SUCCESS";break;default:throw new Ot(pt.INVALID_CHAIN_NAMESPACE)}}catch(s){throw s instanceof Ot?ce.error=s.message:ce.error=Wp.GENERIC_PAYMENT_ERROR,ce.currentPayment.status="FAILED",Je.showError(ce.error),s}finally{ce.isPaymentInProgress=!1}},async onSendTransaction(e){try{let{namespace:t,transactionStep:r}=e;Pe.initiatePayment();let o=$.getAllRequestedCaipNetworks().find(i=>i.caipNetworkId===ce.paymentAsset?.network);if(!o)throw new Error("Target network not found");let s=$.state.activeCaipNetwork;if(an.isLowerCaseMatch(s?.caipNetworkId,o.caipNetworkId)||await $.switchActiveNetwork(o),t===Z.CHAIN.EVM){let{from:i,to:a,data:c,value:u}=r.transaction;await ee.sendTransaction({address:i,to:a,data:c,value:BigInt(u),chainNamespace:t})}else if(t===Z.CHAIN.SOLANA){let{instructions:i}=r.transaction;await ee.writeSolanaTransaction({instructions:i})}}catch(t){throw t instanceof Ot?ce.error=t.message:ce.error=Wp.GENERIC_PAYMENT_ERROR,Je.showError(ce.error),t}finally{ce.isPaymentInProgress=!1}},getExchangeById(e){return ce.exchanges.find(t=>t.id===e)},validatePayConfig(e){let{paymentAsset:t,recipient:r,amount:n}=e;if(!t)throw new Ot(pt.INVALID_PAYMENT_CONFIG);if(!r)throw new Ot(pt.INVALID_RECIPIENT);if(!t.asset)throw new Ot(pt.INVALID_ASSET);if(n==null||n<=0)throw new Ot(pt.INVALID_AMOUNT)},async handlePayWithExchange(e){try{ce.currentPayment={type:"exchange",exchangeId:e};let{network:t,asset:r}=ce.paymentAsset,n={network:t,asset:r,amount:ce.amount,recipient:ce.recipient},o=await this.getPayUrl(e,n);if(!o)throw new Ot(pt.UNABLE_TO_INITIATE_PAYMENT);return ce.currentPayment.sessionId=o.sessionId,ce.currentPayment.status="IN_PROGRESS",ce.currentPayment.exchangeId=e,this.initiatePayment(),{url:o.url,openInNewTab:ce.openInNewTab}}catch(t){return t instanceof Ot?ce.error=t.message:ce.error=Wp.GENERIC_PAYMENT_ERROR,ce.isPaymentInProgress=!1,Je.showError(ce.error),null}},async getBuyStatus(e,t){try{let r=await Ave({sessionId:t,exchangeId:e});return(r.status==="SUCCESS"||r.status==="FAILED")&&Ae.sendEvent({type:"track",event:r.status==="SUCCESS"?"PAY_SUCCESS":"PAY_ERROR",properties:{message:r.status==="FAILED"?se.parseError(ce.error):void 0,source:"pay",paymentId:ce.paymentId||yq,configuration:{network:ce.paymentAsset.network,asset:ce.paymentAsset.asset,recipient:ce.recipient,amount:ce.amount},currentPayment:{type:"exchange",exchangeId:ce.currentPayment?.exchangeId,sessionId:ce.currentPayment?.sessionId,result:r.txHash}}}),r}catch{throw new Ot(pt.UNABLE_TO_GET_BUY_STATUS)}},async fetchTokensFromEOA({caipAddress:e,caipNetwork:t,namespace:r}){if(!e)return[];let{address:n}=lt.parseCaipAddress(e),o=t;return r===Z.CHAIN.EVM&&(o=void 0),await al.getMyTokensWithBalance({address:n,caipNetwork:o})},async fetchTokensFromExchange(){if(!ce.selectedExchange)return[];let e=await Ive(ce.selectedExchange.id),t=Object.values(e.assets).flat();return await Promise.all(t.map(async n=>{let o=Nve(n),{chainNamespace:s}=lt.parseCaipNetworkId(o.chainId),i=o.address;if(se.isCaipAddress(i)){let{address:c}=lt.parseCaipAddress(i);i=c}let a=await St.getImageByToken(i??"",s).catch(()=>{});return o.iconUrl=a??"",o}))},async fetchTokens({caipAddress:e,caipNetwork:t,namespace:r}){try{ce.isFetchingTokenBalances=!0;let s=await(!!ce.selectedExchange?this.fetchTokensFromExchange():this.fetchTokensFromEOA({caipAddress:e,caipNetwork:t,namespace:r}));ce.tokenBalances={...ce.tokenBalances,[r]:s}}catch(n){let o=n instanceof Error?n.message:"Unable to get token balances";Je.showError(o)}finally{ce.isFetchingTokenBalances=!1}},async fetchQuote({amount:e,address:t,sourceToken:r,toToken:n,recipient:o}){try{Pe.resetQuoteState(),ce.isFetchingQuote=!0;let s=await Cve({amount:e,address:ce.selectedExchange?void 0:t,sourceToken:r,toToken:n,recipient:o});if(ce.selectedExchange){let i=$E(s);if(i){let a=`${r.network}:${i.deposit.receiver}`,c=ht.formatNumber(i.deposit.amount,{decimals:r.metadata.decimals??0,round:8});await Pe.generateExchangeUrlForQuote({exchangeId:ce.selectedExchange.id,paymentAsset:r,amount:c.toString(),recipient:a})}}ce.quote=s}catch(s){let i=Wp.UNABLE_TO_GET_QUOTE;if(s instanceof Error&&s.cause&&s.cause instanceof Response)try{let a=await s.cause.json();a.error&&typeof a.error=="string"&&(i=a.error)}catch{}throw ce.quoteError=i,Je.showError(i),new Ot(pt.UNABLE_TO_GET_QUOTE)}finally{ce.isFetchingQuote=!1}},async fetchQuoteStatus({requestId:e}){try{if(e===yN){let r=ce.selectedExchange,n=ce.exchangeSessionId;if(r&&n){switch((await this.getBuyStatus(r.id,n)).status){case"IN_PROGRESS":ce.quoteStatus="waiting";break;case"SUCCESS":ce.quoteStatus="success",ce.isPaymentInProgress=!1;break;case"FAILED":ce.quoteStatus="failure",ce.isPaymentInProgress=!1;break;case"UNKNOWN":ce.quoteStatus="waiting";break;default:ce.quoteStatus="waiting";break}return}ce.quoteStatus="success";return}let{status:t}=await Sve({requestId:e});ce.quoteStatus=t}catch{throw ce.quoteStatus="failure",new Ot(pt.UNABLE_TO_GET_QUOTE_STATUS)}},initiatePayment(){ce.isPaymentInProgress=!0,ce.paymentId=crypto.randomUUID()},initializeAnalytics(){ce.analyticsSet||(ce.analyticsSet=!0,this.subscribeKey("isPaymentInProgress",e=>{if(ce.currentPayment?.status&&ce.currentPayment.status!=="UNKNOWN"){let t={IN_PROGRESS:"PAY_INITIATED",SUCCESS:"PAY_SUCCESS",FAILED:"PAY_ERROR"}[ce.currentPayment.status];Ae.sendEvent({type:"track",event:t,properties:{message:ce.currentPayment.status==="FAILED"?se.parseError(ce.error):void 0,source:"pay",paymentId:ce.paymentId||yq,configuration:{network:ce.paymentAsset.network,asset:ce.paymentAsset.asset,recipient:ce.recipient,amount:ce.amount},currentPayment:{type:ce.currentPayment.type,exchangeId:ce.currentPayment.exchangeId,sessionId:ce.currentPayment.sessionId,result:ce.currentPayment.result}}})}}))},async prepareTokenLogo(){if(!ce.paymentAsset.metadata.logoURI)try{let{chainNamespace:e}=lt.parseCaipNetworkId(ce.paymentAsset.network),t=await St.getImageByToken(ce.paymentAsset.asset,e);ce.paymentAsset.metadata.logoURI=t}catch{}}}});var Bve,kve=b(()=>{l();Ve();Bve=fe` + wui-separator { + margin: var(--apkt-spacing-3) calc(var(--apkt-spacing-3) * -1) var(--apkt-spacing-2) + calc(var(--apkt-spacing-3) * -1); + width: calc(100% + var(--apkt-spacing-3) * 2); + } + + .token-display { + padding: var(--apkt-spacing-3) var(--apkt-spacing-3); + border-radius: var(--apkt-borderRadius-5); + background-color: var(--apkt-tokens-theme-backgroundPrimary); + margin-top: var(--apkt-spacing-3); + margin-bottom: var(--apkt-spacing-3); + } + + .token-display wui-text { + text-transform: none; + } + + wui-loading-spinner { + padding: var(--apkt-spacing-2); + } + + .left-image-container { + position: relative; + justify-content: center; + align-items: center; + } + + .token-image { + border-radius: ${({borderRadius:e})=>e.round}; + width: 40px; + height: 40px; + } + + .chain-image { + position: absolute; + width: 20px; + height: 20px; + bottom: -3px; + right: -5px; + border-radius: ${({borderRadius:e})=>e.round}; + border: 2px solid ${({tokens:e})=>e.theme.backgroundPrimary}; + } + + .payment-methods-container { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-top-right-radius: ${({borderRadius:e})=>e[8]}; + border-top-left-radius: ${({borderRadius:e})=>e[8]}; + } +`});var r1,Hd,Uve=b(()=>{l();he();$e();kr();ct();Ve();bE();jr();$p();sq();rve();gN();tq();UE();UE();uve();cq();Zn();vE();Kp();FE();uq();kve();r1=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Hd=class extends ie{constructor(){super(),this.unsubscribe=[],this.amount=Pe.state.amount,this.namespace=void 0,this.paymentAsset=Pe.state.paymentAsset,this.activeConnectorIds=re.state.activeConnectorIds,this.caipAddress=void 0,this.exchanges=Pe.state.exchanges,this.isLoading=Pe.state.isLoading,this.initializeNamespace(),this.unsubscribe.push(Pe.subscribeKey("amount",t=>this.amount=t)),this.unsubscribe.push(re.subscribeKey("activeConnectorIds",t=>this.activeConnectorIds=t)),this.unsubscribe.push(Pe.subscribeKey("exchanges",t=>this.exchanges=t)),this.unsubscribe.push(Pe.subscribeKey("isLoading",t=>this.isLoading=t)),Pe.fetchExchanges(),Pe.setSelectedExchange(void 0)}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){return V` + + ${this.paymentDetailsTemplate()} ${this.paymentMethodsTemplate()} + + `}paymentMethodsTemplate(){return V` + + ${this.payWithWalletTemplate()} ${this.templateSeparator()} + ${this.templateExchangeOptions()} + + `}initializeNamespace(){let t=$.state.activeChain;this.namespace=t,this.caipAddress=$.getAccountData(t)?.caipAddress,this.unsubscribe.push($.subscribeChainProp("accountState",r=>{this.caipAddress=r?.caipAddress},t))}paymentDetailsTemplate(){let r=$.getAllRequestedCaipNetworks().find(n=>n.caipNetworkId===this.paymentAsset.network);return V` + + + + ${u2(this.amount||"0")} + + + + + ${this.paymentAsset.metadata.symbol||"Unknown"} + + on ${r?.name||"Unknown"} + + + + + + + + + `}payWithWalletTemplate(){return _ve(this.paymentAsset.network)?this.caipAddress?this.connectedWalletTemplate():this.disconnectedWalletTemplate():V``}connectedWalletTemplate(){let{name:t,image:r}=this.getWalletProperties({namespace:this.namespace});return V` + + + Pay with ${t} + + + + Disconnect + + + `}disconnectedWalletTemplate(){return V` + Pay with wallet + `}templateExchangeOptions(){if(this.isLoading)return V` + + `;let t=this.exchanges.filter(r=>Rve(this.paymentAsset)?r.id===lq:r.id!==lq);return t.length===0?V` + No exchanges available + `:t.map(r=>V` + this.onExchangePayment(r)} + data-testid="exchange-option-${r.id}" + ?chevron=${!0} + imageSrc=${Ce(r.imageUrl)} + > + + Pay with ${r.name} + + + `)}templateSeparator(){return V``}async onWalletPayment(){if(!this.namespace)throw new Error("Namespace not found");this.caipAddress?J.push("PayQuote"):(await re.connect(),await De.open({view:"PayQuote"}))}onExchangePayment(t){Pe.setSelectedExchange(t),J.push("PayQuote")}async onDisconnect(){try{await ee.disconnect(),await De.open({view:"Pay"})}catch{console.error("Failed to disconnect"),Je.showError("Failed to disconnect")}}getWalletProperties({namespace:t}){if(!t)return{name:void 0,image:void 0};let r=this.activeConnectorIds[t];if(!r)return{name:void 0,image:void 0};let n=re.getConnector({id:r,namespace:t});if(!n)return{name:void 0,image:void 0};let o=St.getConnectorImage(n);return{name:n.name,image:o}}};Hd.styles=Bve;r1([le()],Hd.prototype,"amount",void 0);r1([le()],Hd.prototype,"namespace",void 0);r1([le()],Hd.prototype,"paymentAsset",void 0);r1([le()],Hd.prototype,"activeConnectorIds",void 0);r1([le()],Hd.prototype,"caipAddress",void 0);r1([le()],Hd.prototype,"exchanges",void 0);r1([le()],Hd.prototype,"isLoading",void 0);Hd=r1([ne("w3m-pay-view")],Hd)});var Dve,Lve=b(()=>{l();Rt();Dve=fe` + :host { + display: inline-flex; + align-items: center; + justify-content: center; + } + + .pulse-container { + position: relative; + width: var(--pulse-size); + height: var(--pulse-size); + display: flex; + align-items: center; + justify-content: center; + } + + .pulse-rings { + position: absolute; + inset: 0; + pointer-events: none; + } + + .pulse-ring { + position: absolute; + inset: 0; + border-radius: 50%; + border: 2px solid var(--pulse-color); + opacity: 0; + animation: pulse var(--pulse-duration, 2s) ease-out infinite; + } + + .pulse-content { + position: relative; + z-index: 1; + display: flex; + align-items: center; + justify-content: center; + } + + @keyframes pulse { + 0% { + transform: scale(0.5); + opacity: var(--pulse-opacity, 0.3); + } + 50% { + opacity: calc(var(--pulse-opacity, 0.3) * 0.5); + } + 100% { + transform: scale(1.2); + opacity: 0; + } + } +`});var Vx,Ttt,_tt,Ptt,Ntt,Rtt,n1,Mve=b(()=>{l();he();$e();Rt();Mt();Bt();Lve();Vx=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ttt=3,_tt=2,Ptt=.3,Ntt="200px",Rtt={"accent-primary":$t.tokens.core.backgroundAccentPrimary},n1=class extends ie{constructor(){super(...arguments),this.rings=Ttt,this.duration=_tt,this.opacity=Ptt,this.size=Ntt,this.variant="accent-primary"}render(){let t=Rtt[this.variant];this.style.cssText=` + --pulse-size: ${this.size}; + --pulse-duration: ${this.duration}s; + --pulse-color: ${t}; + --pulse-opacity: ${this.opacity}; + `;let r=Array.from({length:this.rings},(n,o)=>this.renderRing(o,this.rings));return V` +
+
${r}
+
+ +
+
+ `}renderRing(t,r){let o=`animation-delay: ${t/r*this.duration}s;`;return V`
`}};n1.styles=[Me,Dve];Vx([q({type:Number})],n1.prototype,"rings",void 0);Vx([q({type:Number})],n1.prototype,"duration",void 0);Vx([q({type:Number})],n1.prototype,"opacity",void 0);Vx([q()],n1.prototype,"size",void 0);Vx([q()],n1.prototype,"variant",void 0);n1=Vx([ne("wui-pulse")],n1)});var Hve=b(()=>{l();Mve()});var wq,bq,$ve=b(()=>{l();wq=[{id:"received",title:"Receiving funds",icon:"dollar"},{id:"processing",title:"Swapping asset",icon:"recycleHorizontal"},{id:"sending",title:"Sending asset to the recipient address",icon:"send"}],bq=["success","submitted","failure","timeout","refund"]});var Fve,zve=b(()=>{l();Ve();Fve=fe` + :host { + display: block; + height: 100%; + width: 100%; + } + + wui-image { + border-radius: ${({borderRadius:e})=>e.round}; + } + + .token-badge-container { + position: absolute; + bottom: 6px; + left: 50%; + transform: translateX(-50%); + border-radius: ${({borderRadius:e})=>e[4]}; + z-index: 3; + min-width: 105px; + } + + .token-badge-container.loading { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + border: 3px solid ${({tokens:e})=>e.theme.backgroundPrimary}; + } + + .token-badge-container.success { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + border: 3px solid ${({tokens:e})=>e.theme.backgroundPrimary}; + } + + .token-image-container { + position: relative; + } + + .token-image { + border-radius: ${({borderRadius:e})=>e.round}; + width: 64px; + height: 64px; + } + + .token-image.success { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + .token-image.error { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + .token-image.loading { + background: ${({colors:e})=>e.accent010}; + } + + .token-image wui-icon { + width: 32px; + height: 32px; + } + + .token-badge { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border: 1px solid ${({tokens:e})=>e.theme.foregroundSecondary}; + border-radius: ${({borderRadius:e})=>e[4]}; + } + + .token-badge wui-text { + white-space: nowrap; + } + + .payment-lifecycle-container { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-top-right-radius: ${({borderRadius:e})=>e[6]}; + border-top-left-radius: ${({borderRadius:e})=>e[6]}; + } + + .payment-step-badge { + padding: ${({spacing:e})=>e[1]} ${({spacing:e})=>e[2]}; + border-radius: ${({borderRadius:e})=>e[1]}; + } + + .payment-step-badge.loading { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + .payment-step-badge.error { + background-color: ${({tokens:e})=>e.core.backgroundError}; + } + + .payment-step-badge.success { + background-color: ${({tokens:e})=>e.core.backgroundSuccess}; + } + + .step-icon-container { + position: relative; + height: 40px; + width: 40px; + border-radius: ${({borderRadius:e})=>e.round}; + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + .step-icon-box { + position: absolute; + right: -4px; + bottom: -1px; + padding: 2px; + border-radius: ${({borderRadius:e})=>e.round}; + border: 2px solid ${({tokens:e})=>e.theme.backgroundPrimary}; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + .step-icon-box.success { + background-color: ${({tokens:e})=>e.core.backgroundSuccess}; + } +`});var $d,Ott,Btt,Pc,Vve=b(()=>{l();he();$e();MP();kr();ut();ct();Ve();jr();gN();UE();Hve();cq();Zn();Il();Kp();FE();$ve();zve();$d=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ott={received:["pending","success","submitted"],processing:["success","submitted"],sending:["success","submitted"]},Btt=3e3,Pc=class extends ie{constructor(){super(),this.unsubscribe=[],this.pollingInterval=null,this.paymentAsset=Pe.state.paymentAsset,this.quoteStatus=Pe.state.quoteStatus,this.quote=Pe.state.quote,this.amount=Pe.state.amount,this.namespace=void 0,this.caipAddress=void 0,this.profileName=null,this.activeConnectorIds=re.state.activeConnectorIds,this.selectedExchange=Pe.state.selectedExchange,this.initializeNamespace(),this.unsubscribe.push(Pe.subscribeKey("quoteStatus",t=>this.quoteStatus=t),Pe.subscribeKey("quote",t=>this.quote=t),re.subscribeKey("activeConnectorIds",t=>this.activeConnectorIds=t),Pe.subscribeKey("selectedExchange",t=>this.selectedExchange=t))}connectedCallback(){super.connectedCallback(),this.startPolling()}disconnectedCallback(){super.disconnectedCallback(),this.stopPolling(),this.unsubscribe.forEach(t=>t())}render(){return V` + + ${this.tokenTemplate()} ${this.paymentTemplate()} ${this.paymentLifecycleTemplate()} + + `}tokenTemplate(){let t=u2(this.amount||"0"),r=this.paymentAsset.metadata.symbol??"Unknown",o=$.getAllRequestedCaipNetworks().find(a=>a.caipNetworkId===this.paymentAsset.network),s=this.quoteStatus==="failure"||this.quoteStatus==="timeout"||this.quoteStatus==="refund";return this.quoteStatus==="success"||this.quoteStatus==="submitted"?V` + + + + `:s?V` + + + + `:V` + + + + + + + + + + + + + ${t} ${r} + + + + + `}paymentTemplate(){return V` + + ${this.renderPayment()} + + ${this.renderWallet()} + + `}paymentLifecycleTemplate(){let t=this.getStepsWithStatus();return V` + + + PAYMENT CYCLE + + ${this.renderPaymentCycleBadge()} + + + + ${t.map(r=>this.renderStep(r))} + + + `}renderPaymentCycleBadge(){let t=this.quoteStatus==="failure"||this.quoteStatus==="timeout"||this.quoteStatus==="refund",r=this.quoteStatus==="success"||this.quoteStatus==="submitted";if(t)return V` + + + Failed + + `;if(r)return V` + + + Completed + + `;let n=this.quote?.timeInSeconds??0;return V` + + + + Est. ${n} sec + + + + + `}renderPayment(){let r=$.getAllRequestedCaipNetworks().find(i=>{let a=this.quote?.origin.currency.network;if(!a)return!1;let{chainId:c}=lt.parseCaipNetworkId(a);return an.isLowerCaseMatch(i.id.toString(),c.toString())}),n=ht.formatNumber(this.quote?.origin.amount||"0",{decimals:this.quote?.origin.currency.metadata.decimals??0}).toString(),o=u2(n),s=this.quote?.origin.currency.metadata.symbol??"Unknown";return V` + + Payment Method + + + + ${o} + ${s} + + + + on + + ${r?.name} + + + + `}renderWallet(){return V` + + Wallet + + ${this.renderWalletText()} + + `}renderWalletText(){let{image:t}=this.getWalletProperties({namespace:this.namespace}),{address:r}=this.caipAddress?lt.parseCaipAddress(this.caipAddress):{},n=this.selectedExchange?.name;return this.selectedExchange?V` + + ${n} + + + `:V` + + + ${hr.getTruncateString({string:this.profileName||r||n||"",charsStart:this.profileName?16:4,charsEnd:this.profileName?0:6,truncate:this.profileName?"end":"middle"})} + + + + + `}getStepsWithStatus(){return this.quoteStatus==="failure"||this.quoteStatus==="timeout"||this.quoteStatus==="refund"?wq.map(r=>({...r,status:"failed"})):wq.map(r=>{let o=(Ott[r.id]??[]).includes(this.quoteStatus)?"completed":"pending";return{...r,status:o}})}renderStep({title:t,icon:r,status:n}){return V` + + + + + + ${this.renderStatusIndicator(n)} + + + + ${t} + + `}renderStatusIndicator(t){return t==="completed"?V``:t==="failed"?V``:t==="pending"?V``:null}startPolling(){this.pollingInterval||(this.fetchQuoteStatus(),this.pollingInterval=setInterval(()=>{this.fetchQuoteStatus()},Btt))}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null)}async fetchQuoteStatus(){let t=Pe.state.requestId;if(!t||bq.includes(this.quoteStatus))this.stopPolling();else try{await Pe.fetchQuoteStatus({requestId:t}),bq.includes(this.quoteStatus)&&this.stopPolling()}catch{this.stopPolling()}}initializeNamespace(){let t=$.state.activeChain;this.namespace=t,this.caipAddress=$.getAccountData(t)?.caipAddress,this.profileName=$.getAccountData(t)?.profileName??null,this.unsubscribe.push($.subscribeChainProp("accountState",r=>{this.caipAddress=r?.caipAddress,this.profileName=r?.profileName??null},t))}getWalletProperties({namespace:t}){if(!t)return{name:void 0,image:void 0};let r=this.activeConnectorIds[t];if(!r)return{name:void 0,image:void 0};let n=re.getConnector({id:r,namespace:t});if(!n)return{name:void 0,image:void 0};let o=St.getConnectorImage(n);return{name:n.name,image:o}}};Pc.styles=Fve;$d([le()],Pc.prototype,"paymentAsset",void 0);$d([le()],Pc.prototype,"quoteStatus",void 0);$d([le()],Pc.prototype,"quote",void 0);$d([le()],Pc.prototype,"amount",void 0);$d([le()],Pc.prototype,"namespace",void 0);$d([le()],Pc.prototype,"caipAddress",void 0);$d([le()],Pc.prototype,"profileName",void 0);$d([le()],Pc.prototype,"activeConnectorIds",void 0);$d([le()],Pc.prototype,"selectedExchange",void 0);Pc=$d([ne("w3m-pay-loading-view")],Pc)});var jve,qve=b(()=>{l();Rt();jve=fe` + button { + display: flex; + align-items: center; + height: 40px; + padding: ${({spacing:e})=>e[2]}; + border-radius: ${({borderRadius:e})=>e[4]}; + column-gap: ${({spacing:e})=>e[1]}; + background-color: transparent; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: background-color; + } + + wui-image, + .icon-box { + width: ${({spacing:e})=>e[6]}; + height: ${({spacing:e})=>e[6]}; + border-radius: ${({borderRadius:e})=>e[4]}; + } + + wui-text { + flex: 1; + } + + .icon-box { + position: relative; + } + + .icon-box[data-active='true'] { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + .circle { + position: absolute; + left: 16px; + top: 15px; + width: 8px; + height: 8px; + background-color: ${({tokens:e})=>e.core.textSuccess}; + box-shadow: 0 0 0 2px ${({tokens:e})=>e.theme.foregroundPrimary}; + border-radius: 50%; + } + + /* -- Hover & Active states ----------------------------------------------------------- */ + @media (hover: hover) { + button:hover:enabled, + button:active:enabled { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + } +`});var _l,Ha,Wve=b(()=>{l();he();$e();kr();uo();Ky();Rs();$y();Mt();gx();Bt();qve();_l=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ha=class extends ie{constructor(){super(...arguments),this.address="",this.profileName="",this.alt="",this.imageSrc="",this.icon=void 0,this.iconSize="md",this.enableGreenCircle=!0,this.loading=!1,this.charsStart=4,this.charsEnd=6}render(){return V` + + `}leftImageTemplate(){let t=this.icon?V``:V``;return V` + + ${t} + ${this.enableGreenCircle?V``:null} + + `}textTemplate(){return V` + + ${hr.getTruncateString({string:this.profileName||this.address,charsStart:this.profileName?16:this.charsStart,charsEnd:this.profileName?0:this.charsEnd,truncate:this.profileName?"end":"middle"})} + + `}rightImageTemplate(){return V``}};Ha.styles=[Me,Gt,jve];_l([q()],Ha.prototype,"address",void 0);_l([q()],Ha.prototype,"profileName",void 0);_l([q()],Ha.prototype,"alt",void 0);_l([q()],Ha.prototype,"imageSrc",void 0);_l([q()],Ha.prototype,"icon",void 0);_l([q()],Ha.prototype,"iconSize",void 0);_l([q({type:Boolean})],Ha.prototype,"enableGreenCircle",void 0);_l([q({type:Boolean})],Ha.prototype,"loading",void 0);_l([q({type:Number})],Ha.prototype,"charsStart",void 0);_l([q({type:Number})],Ha.prototype,"charsEnd",void 0);Ha=_l([ne("wui-wallet-switch")],Ha)});var Kve=b(()=>{l();Wve()});var Zve,Gve=b(()=>{l();he();Zve=Er` + :host { + display: block; + } +`});var ktt,xq,Yve=b(()=>{l();he();Ve();jr();RE();Zn();Gve();ktt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},xq=class extends ie{render(){return V` + + + Pay + + + + + Network Fee + + + + + + + + + + + + + Service Fee + + + + `}};xq.styles=[Zve];xq=ktt([ne("w3m-pay-fees-skeleton")],xq)});var Jve,Qve=b(()=>{l();Ve();Jve=fe` + :host { + display: block; + } + + wui-image { + border-radius: ${({borderRadius:e})=>e.round}; + } +`});var Xve,vN,eEe=b(()=>{l();he();$e();kr();ut();ct();Ve();jr();gN();Zn();Il();Kp();Qve();Xve=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},vN=class extends ie{constructor(){super(),this.unsubscribe=[],this.quote=Pe.state.quote,this.unsubscribe.push(Pe.subscribeKey("quote",t=>this.quote=t))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){let t=ht.formatNumber(this.quote?.origin.amount||"0",{decimals:this.quote?.origin.currency.metadata.decimals??0,round:6}).toString();return V` + + + Pay + + ${t} ${this.quote?.origin.currency.metadata.symbol||"Unknown"} + + + + ${this.quote&&this.quote.fees.length>0?this.quote.fees.map(r=>this.renderFee(r)):null} + + `}renderFee(t){let r=t.id==="network",n=ht.formatNumber(t.amount||"0",{decimals:t.currency.metadata.decimals??0,round:6}).toString();if(r){let s=$.getAllRequestedCaipNetworks().find(i=>an.isLowerCaseMatch(i.caipNetworkId,t.currency.network));return V` + + ${t.label} + + + + ${n} ${t.currency.metadata.symbol||"Unknown"} + + + + + + ${s?.name||"Unknown"} + + + + + `}return V` + + ${t.label} + + ${n} ${t.currency.metadata.symbol||"Unknown"} + + + `}};vN.styles=[Jve];Xve([le()],vN.prototype,"quote",void 0);vN=Xve([ne("w3m-pay-fees")],vN)});var tEe,rEe=b(()=>{l();Ve();tEe=fe` + :host { + display: block; + width: 100%; + } + + .disabled-container { + padding: ${({spacing:e})=>e[2]}; + min-height: 168px; + } + + wui-icon { + width: ${({spacing:e})=>e[8]}; + height: ${({spacing:e})=>e[8]}; + } + + wui-flex > wui-text { + max-width: 273px; + } +`});var nEe,EN,oEe=b(()=>{l();he();$e();Ve();bE();jr();$p();Zn();Kp();rEe();nEe=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},EN=class extends ie{constructor(){super(),this.unsubscribe=[],this.selectedExchange=Pe.state.selectedExchange,this.unsubscribe.push(Pe.subscribeKey("selectedExchange",t=>this.selectedExchange=t))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){let t=!!this.selectedExchange;return V` + + + + + You don't have enough funds to complete this transaction + + + ${t?null:V`Connect other wallet`} + + `}dispatchConnectOtherWalletEvent(){this.dispatchEvent(new CustomEvent("connectOtherWallet",{detail:!0,bubbles:!0,composed:!0}))}};EN.styles=[tEe];nEe([q({type:Array})],EN.prototype,"selectedExchange",void 0);EN=nEe([ne("w3m-pay-options-empty")],EN)});var sEe,iEe=b(()=>{l();Ve();sEe=fe` + :host { + display: block; + width: 100%; + } + + .pay-options-container { + max-height: 196px; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + } + + .pay-options-container::-webkit-scrollbar { + display: none; + } + + .pay-option-container { + border-radius: ${({borderRadius:e})=>e[4]}; + padding: ${({spacing:e})=>e[3]}; + min-height: 60px; + } + + .token-images-container { + position: relative; + justify-content: center; + align-items: center; + } + + .chain-image { + position: absolute; + bottom: -3px; + right: -5px; + border: 2px solid ${({tokens:e})=>e.theme.foregroundSecondary}; + } +`});var Utt,vq,aEe=b(()=>{l();he();Ve();jr();RE();iEe();Utt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},vq=class extends ie{render(){return V` + + ${this.renderOptionEntry()} ${this.renderOptionEntry()} ${this.renderOptionEntry()} + + `}renderOptionEntry(){return V` + + + + + + + + + + + + + + `}};vq.styles=[sEe];vq=Utt([ne("w3m-pay-options-skeleton")],vq)});var cEe,lEe=b(()=>{l();Ve();cEe=fe` + :host { + display: block; + width: 100%; + } + + .pay-options-container { + max-height: 196px; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: none; + mask-image: var(--options-mask-image); + -webkit-mask-image: var(--options-mask-image); + } + + .pay-options-container::-webkit-scrollbar { + display: none; + } + + .pay-option-container { + cursor: pointer; + border-radius: ${({borderRadius:e})=>e[4]}; + padding: ${({spacing:e})=>e[3]}; + transition: background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}; + will-change: background-color; + } + + .token-images-container { + position: relative; + justify-content: center; + align-items: center; + } + + .token-image { + border-radius: ${({borderRadius:e})=>e.round}; + width: 32px; + height: 32px; + } + + .chain-image { + position: absolute; + width: 16px; + height: 16px; + bottom: -3px; + right: -5px; + border-radius: ${({borderRadius:e})=>e.round}; + border: 2px solid ${({tokens:e})=>e.theme.backgroundPrimary}; + } + + @media (hover: hover) and (pointer: fine) { + .pay-option-container:hover { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + } +`});var AN,Dtt,jx,uEe=b(()=>{l();he();$e();kr();ut();ct();Ve();jr();Zn();lEe();AN=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Dtt=300,jx=class extends ie{constructor(){super(),this.unsubscribe=[],this.options=[],this.selectedPaymentAsset=null}disconnectedCallback(){this.unsubscribe.forEach(r=>r()),this.resizeObserver?.disconnect(),this.shadowRoot?.querySelector(".pay-options-container")?.removeEventListener("scroll",this.handleOptionsListScroll.bind(this))}firstUpdated(){let t=this.shadowRoot?.querySelector(".pay-options-container");t&&(requestAnimationFrame(this.handleOptionsListScroll.bind(this)),t?.addEventListener("scroll",this.handleOptionsListScroll.bind(this)),this.resizeObserver=new ResizeObserver(()=>{this.handleOptionsListScroll()}),this.resizeObserver?.observe(t),this.handleOptionsListScroll())}render(){return V` + + ${this.options.map(t=>this.payOptionTemplate(t))} + + `}payOptionTemplate(t){let{network:r,metadata:n,asset:o,amount:s="0"}=t,a=$.getAllRequestedCaipNetworks().find(h=>h.caipNetworkId===r),c=`${r}:${o}`,u=`${this.selectedPaymentAsset?.network}:${this.selectedPaymentAsset?.asset}`,d=c===u,f=ht.bigNumber(s,{safe:!0}),p=f.gt(0);return V` + this.onSelect?.(t)} + class="pay-option-container" + > + + + + + + + + ${n.symbol} + ${p?V` + ${f.round(6).toString()} ${n.symbol} + `:null} + + + + ${d?V``:null} + + `}handleOptionsListScroll(){let t=this.shadowRoot?.querySelector(".pay-options-container");if(!t)return;t.scrollHeight>Dtt?(t.style.setProperty("--options-mask-image",`linear-gradient( + to bottom, + rgba(0, 0, 0, calc(1 - var(--options-scroll--top-opacity))) 0px, + rgba(200, 200, 200, calc(1 - var(--options-scroll--top-opacity))) 1px, + black 50px, + black calc(100% - 50px), + rgba(155, 155, 155, calc(1 - var(--options-scroll--bottom-opacity))) calc(100% - 1px), + rgba(0, 0, 0, calc(1 - var(--options-scroll--bottom-opacity))) 100% + )`),t.style.setProperty("--options-scroll--top-opacity",fP.interpolate([0,50],[0,1],t.scrollTop).toString()),t.style.setProperty("--options-scroll--bottom-opacity",fP.interpolate([0,50],[0,1],t.scrollHeight-t.scrollTop-t.offsetHeight).toString())):(t.style.setProperty("--options-mask-image","none"),t.style.setProperty("--options-scroll--top-opacity","0"),t.style.setProperty("--options-scroll--bottom-opacity","0"))}};jx.styles=[cEe];AN([q({type:Array})],jx.prototype,"options",void 0);AN([q()],jx.prototype,"selectedPaymentAsset",void 0);AN([q()],jx.prototype,"onSelect",void 0);jx=AN([ne("w3m-pay-options")],jx)});var dEe,fEe=b(()=>{l();Ve();dEe=fe` + .payment-methods-container { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border-top-right-radius: ${({borderRadius:e})=>e[5]}; + border-top-left-radius: ${({borderRadius:e})=>e[5]}; + } + + .pay-options-container { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + border-radius: ${({borderRadius:e})=>e[5]}; + padding: ${({spacing:e})=>e[1]}; + } + + w3m-tooltip-trigger { + display: flex; + align-items: center; + justify-content: center; + max-width: fit-content; + } + + wui-image { + border-radius: ${({borderRadius:e})=>e.round}; + } + + w3m-pay-options.disabled { + opacity: 0.5; + pointer-events: none; + } +`});var Oo,CN,Ltt,Yn,pEe=b(()=>{l();he();$e();MP();kr();ut();ct();Ve();jr();Zn();Kve();Il();Kp();Yve();eEe();oEe();aEe();uEe();FE();bN();fEe();Oo=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},CN={eip155:"ethereum",solana:"solana",bip122:"bitcoin",ton:"ton"},Ltt={eip155:{icon:CN.eip155,label:"EVM"},solana:{icon:CN.solana,label:"Solana"},bip122:{icon:CN.bip122,label:"Bitcoin"},ton:{icon:CN.ton,label:"Ton"}},Yn=class extends ie{constructor(){super(),this.unsubscribe=[],this.profileName=null,this.paymentAsset=Pe.state.paymentAsset,this.namespace=void 0,this.caipAddress=void 0,this.amount=Pe.state.amount,this.recipient=Pe.state.recipient,this.activeConnectorIds=re.state.activeConnectorIds,this.selectedPaymentAsset=Pe.state.selectedPaymentAsset,this.selectedExchange=Pe.state.selectedExchange,this.isFetchingQuote=Pe.state.isFetchingQuote,this.quoteError=Pe.state.quoteError,this.quote=Pe.state.quote,this.isFetchingTokenBalances=Pe.state.isFetchingTokenBalances,this.tokenBalances=Pe.state.tokenBalances,this.isPaymentInProgress=Pe.state.isPaymentInProgress,this.exchangeUrlForQuote=Pe.state.exchangeUrlForQuote,this.completedTransactionsCount=0,this.unsubscribe.push(Pe.subscribeKey("paymentAsset",t=>this.paymentAsset=t)),this.unsubscribe.push(Pe.subscribeKey("tokenBalances",t=>this.onTokenBalancesChanged(t))),this.unsubscribe.push(Pe.subscribeKey("isFetchingTokenBalances",t=>this.isFetchingTokenBalances=t)),this.unsubscribe.push(re.subscribeKey("activeConnectorIds",t=>this.activeConnectorIds=t)),this.unsubscribe.push(Pe.subscribeKey("selectedPaymentAsset",t=>this.selectedPaymentAsset=t)),this.unsubscribe.push(Pe.subscribeKey("isFetchingQuote",t=>this.isFetchingQuote=t)),this.unsubscribe.push(Pe.subscribeKey("quoteError",t=>this.quoteError=t)),this.unsubscribe.push(Pe.subscribeKey("quote",t=>this.quote=t)),this.unsubscribe.push(Pe.subscribeKey("amount",t=>this.amount=t)),this.unsubscribe.push(Pe.subscribeKey("recipient",t=>this.recipient=t)),this.unsubscribe.push(Pe.subscribeKey("isPaymentInProgress",t=>this.isPaymentInProgress=t)),this.unsubscribe.push(Pe.subscribeKey("selectedExchange",t=>this.selectedExchange=t)),this.unsubscribe.push(Pe.subscribeKey("exchangeUrlForQuote",t=>this.exchangeUrlForQuote=t)),this.resetQuoteState(),this.initializeNamespace(),this.fetchTokens()}disconnectedCallback(){super.disconnectedCallback(),this.resetAssetsState(),this.unsubscribe.forEach(t=>t())}updated(t){super.updated(t),t.has("selectedPaymentAsset")&&this.fetchQuote()}render(){return V` + + ${this.profileTemplate()} + + + ${this.paymentOptionsViewTemplate()} ${this.amountWithFeeTemplate()} + + + + + + ${this.paymentActionsTemplate()} + + + `}profileTemplate(){if(this.selectedExchange){let i=ht.formatNumber(this.quote?.origin.amount,{decimals:this.quote?.origin.currency.metadata.decimals??0}).toString();return V` + + Paying with + + ${this.quote?V` + ${ht.bigNumber(i,{safe:!0}).round(6).toString()} + ${this.quote.origin.currency.metadata.symbol} + `:V``} + + `}let t=se.getPlainAddress(this.caipAddress)??"",{name:r,image:n}=this.getWalletProperties({namespace:this.namespace}),{icon:o,label:s}=Ltt[this.namespace]??{};return V` + + + + + + `}initializeNamespace(){let t=$.state.activeChain;this.namespace=t,this.caipAddress=$.getAccountData(t)?.caipAddress,this.profileName=$.getAccountData(t)?.profileName??null,this.unsubscribe.push($.subscribeChainProp("accountState",r=>this.onAccountStateChanged(r),t))}async fetchTokens(){if(this.namespace){let t;if(this.caipAddress){let{chainId:r,chainNamespace:n}=lt.parseCaipAddress(this.caipAddress),o=`${n}:${r}`;t=$.getAllRequestedCaipNetworks().find(i=>i.caipNetworkId===o)}await Pe.fetchTokens({caipAddress:this.caipAddress,caipNetwork:t,namespace:this.namespace})}}fetchQuote(){if(this.amount&&this.recipient&&this.selectedPaymentAsset&&this.paymentAsset){let{address:t}=this.caipAddress?lt.parseCaipAddress(this.caipAddress):{};Pe.fetchQuote({amount:this.amount.toString(),address:t,sourceToken:this.selectedPaymentAsset,toToken:this.paymentAsset,recipient:this.recipient})}}getWalletProperties({namespace:t}){if(!t)return{name:void 0,image:void 0};let r=this.activeConnectorIds[t];if(!r)return{name:void 0,image:void 0};let n=re.getConnector({id:r,namespace:t});if(!n)return{name:void 0,image:void 0};let o=St.getConnectorImage(n);return{name:n.name,image:o}}paymentOptionsViewTemplate(){return V` + + CHOOSE PAYMENT OPTION + ${this.paymentOptionsTemplate()} + + `}paymentOptionsTemplate(){let t=this.getPaymentAssetFromTokenBalances();if(this.isFetchingTokenBalances)return V``;if(t.length===0)return V``;let r={disabled:this.isFetchingQuote};return V``}amountWithFeeTemplate(){return this.isFetchingQuote||!this.selectedPaymentAsset||this.quoteError?V``:V``}paymentActionsTemplate(){let t=this.isFetchingQuote||this.isFetchingTokenBalances,r=this.isFetchingQuote||this.isFetchingTokenBalances||!this.selectedPaymentAsset||!!this.quoteError,n=ht.formatNumber(this.quote?.origin.amount??0,{decimals:this.quote?.origin.currency.metadata.decimals??0}).toString();return this.selectedExchange?t||r?V` + + `:V` + ${`Continue in ${this.selectedExchange.name}`} + + + `:V` + + + Order Total + + ${t||r?V``:V` + ${u2(n)} + + + ${this.quote?.origin.currency.metadata.symbol||"Unknown"} + + `} + + + ${this.actionButtonTemplate({isLoading:t,isDisabled:r})} + + `}actionButtonTemplate(t){let r=wN(this.quote),{isLoading:n,isDisabled:o}=t,s="Pay";return r.length>1&&this.completedTransactionsCount===0&&(s="Approve"),V` + {r.length>0?this.onSendTransactions():this.onTransfer()}} + > + ${s} + ${n?null:V``} + + `}getPaymentAssetFromTokenBalances(){return this.namespace?(this.tokenBalances[this.namespace]??[]).map(o=>{try{return Pve(o)}catch{return null}}).filter(o=>!!o).filter(o=>{let{chainId:s}=lt.parseCaipNetworkId(o.network),{chainId:i}=lt.parseCaipNetworkId(this.paymentAsset.network);return an.isLowerCaseMatch(o.asset,this.paymentAsset.asset)?!0:this.selectedExchange?!an.isLowerCaseMatch(s.toString(),i.toString()):!0}):[]}onTokenBalancesChanged(t){this.tokenBalances=t;let[r]=this.getPaymentAssetFromTokenBalances();r&&Pe.setSelectedPaymentAsset(r)}async onConnectOtherWallet(){await re.connect(),await De.open({view:"PayQuote"})}onAccountStateChanged(t){let{address:r}=this.caipAddress?lt.parseCaipAddress(this.caipAddress):{};if(this.caipAddress=t?.caipAddress,this.profileName=t?.profileName??null,r){let{address:n}=this.caipAddress?lt.parseCaipAddress(this.caipAddress):{};n?an.isLowerCaseMatch(n,r)||(this.resetAssetsState(),this.resetQuoteState(),this.fetchTokens()):De.close()}}onSelectedPaymentAssetChanged(t){this.isFetchingQuote||Pe.setSelectedPaymentAsset(t)}async onTransfer(){let t=$E(this.quote);if(t){if(!an.isLowerCaseMatch(this.selectedPaymentAsset?.asset,t.deposit.currency))throw new Error("Quote asset is not the same as the selected payment asset");let n=this.selectedPaymentAsset?.amount??"0",o=ht.formatNumber(t.deposit.amount,{decimals:this.selectedPaymentAsset?.metadata.decimals??0}).toString();if(!ht.bigNumber(n).gte(o)){Je.showError("Insufficient funds");return}if(this.quote&&this.selectedPaymentAsset&&this.caipAddress&&this.namespace){let{address:i}=lt.parseCaipAddress(this.caipAddress);await Pe.onTransfer({chainNamespace:this.namespace,fromAddress:i,toAddress:t.deposit.receiver,amount:o,paymentAsset:this.selectedPaymentAsset}),Pe.setRequestId(t.requestId),J.push("PayLoading")}}}async onSendTransactions(){let t=this.selectedPaymentAsset?.amount??"0",r=ht.formatNumber(this.quote?.origin.amount??0,{decimals:this.selectedPaymentAsset?.metadata.decimals??0}).toString();if(!ht.bigNumber(t).gte(r)){Je.showError("Insufficient funds");return}let o=wN(this.quote),[s]=wN(this.quote,this.completedTransactionsCount);s&&this.namespace&&(await Pe.onSendTransaction({namespace:this.namespace,transactionStep:s}),this.completedTransactionsCount+=1,this.completedTransactionsCount===o.length&&(Pe.setRequestId(s.requestId),J.push("PayLoading")))}onPayWithExchange(){if(this.exchangeUrlForQuote){let t=se.returnOpenHref("","popupWindow","scrollbar=yes,width=480,height=720");if(!t)throw new Error("Could not create popup window");t.location.href=this.exchangeUrlForQuote;let r=$E(this.quote);r&&Pe.setRequestId(r.requestId),Pe.initiatePayment(),J.push("PayLoading")}}resetAssetsState(){Pe.setSelectedPaymentAsset(null)}resetQuoteState(){Pe.resetQuoteState()}};Yn.styles=dEe;Oo([le()],Yn.prototype,"profileName",void 0);Oo([le()],Yn.prototype,"paymentAsset",void 0);Oo([le()],Yn.prototype,"namespace",void 0);Oo([le()],Yn.prototype,"caipAddress",void 0);Oo([le()],Yn.prototype,"amount",void 0);Oo([le()],Yn.prototype,"recipient",void 0);Oo([le()],Yn.prototype,"activeConnectorIds",void 0);Oo([le()],Yn.prototype,"selectedPaymentAsset",void 0);Oo([le()],Yn.prototype,"selectedExchange",void 0);Oo([le()],Yn.prototype,"isFetchingQuote",void 0);Oo([le()],Yn.prototype,"quoteError",void 0);Oo([le()],Yn.prototype,"quote",void 0);Oo([le()],Yn.prototype,"isFetchingTokenBalances",void 0);Oo([le()],Yn.prototype,"tokenBalances",void 0);Oo([le()],Yn.prototype,"isPaymentInProgress",void 0);Oo([le()],Yn.prototype,"exchangeUrlForQuote",void 0);Oo([le()],Yn.prototype,"completedTransactionsCount",void 0);Yn=Oo([ne("w3m-pay-quote-view")],Yn)});var hEe=b(()=>{l();Kp();zx()});var mEe=b(()=>{l()});var gEe=b(()=>{l();Uve();Vve();pEe();hEe();Kp();mEe()});var yEe,wEe=b(()=>{l();Ve();yEe=fe` + wui-image { + border-radius: ${({borderRadius:e})=>e.round}; + } + + .transfers-badge { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + border: 1px solid ${({tokens:e})=>e.theme.foregroundSecondary}; + border-radius: ${({borderRadius:e})=>e[4]}; + } +`});var Eq,zE,bEe=b(()=>{l();he();$e();kr();ct();gEe();Ve();jr();Zn();wEe();Eq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},zE=class extends ie{constructor(){super(),this.unsubscribe=[],this.paymentAsset=Pe.state.paymentAsset,this.amount=Pe.state.amount,this.unsubscribe.push(Pe.subscribeKey("paymentAsset",t=>{this.paymentAsset=t}),Pe.subscribeKey("amount",t=>{this.amount=t}))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){let r=$.getAllRequestedCaipNetworks().find(n=>n.caipNetworkId===this.paymentAsset.network);return V` + + + ${this.amount} ${this.paymentAsset.metadata.symbol} + + + on ${r?.name??"Unknown"} + + `}};zE.styles=[yEe];Eq([q()],zE.prototype,"paymentAsset",void 0);Eq([q()],zE.prototype,"amount",void 0);zE=Eq([ne("w3m-pay-header")],zE)});var xEe,vEe=b(()=>{l();Ve();xEe=fe` + :host { + height: 60px; + } + + :host > wui-flex { + box-sizing: border-box; + background-color: var(--local-header-background-color); + } + + wui-text { + background-color: var(--local-header-background-color); + } + + wui-flex.w3m-header-title { + transform: translateY(0); + opacity: 1; + } + + wui-flex.w3m-header-title[view-direction='prev'] { + animation: + slide-down-out 120ms forwards ${({easings:e})=>e["ease-out-power-2"]}, + slide-down-in 120ms forwards ${({easings:e})=>e["ease-out-power-2"]}; + animation-delay: 0ms, 200ms; + } + + wui-flex.w3m-header-title[view-direction='next'] { + animation: + slide-up-out 120ms forwards ${({easings:e})=>e["ease-out-power-2"]}, + slide-up-in 120ms forwards ${({easings:e})=>e["ease-out-power-2"]}; + animation-delay: 0ms, 200ms; + } + + wui-icon-button[data-hidden='true'] { + opacity: 0 !important; + pointer-events: none; + } + + @keyframes slide-up-out { + from { + transform: translateY(0px); + opacity: 1; + } + to { + transform: translateY(3px); + opacity: 0; + } + } + + @keyframes slide-up-in { + from { + transform: translateY(-3px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } + } + + @keyframes slide-down-out { + from { + transform: translateY(0px); + opacity: 1; + } + to { + transform: translateY(-3px); + opacity: 0; + } + } + + @keyframes slide-down-in { + from { + transform: translateY(3px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } + } +`});function EEe(){let e=J.state.data?.connector?.name,t=J.state.data?.wallet?.name,r=J.state.data?.network?.name,n=t??e,o=re.getConnectors(),s=o.length===1&&o[0]?.id==="w3m-email",i=$.getAccountData()?.socialProvider,a=i?i.charAt(0).toUpperCase()+i.slice(1):"Connect Social";return{Connect:`Connect ${s?"Email":""} Wallet`,Create:"Create Wallet",ChooseAccountName:void 0,Account:void 0,AccountSettings:void 0,AllWallets:"All Wallets",ApproveTransaction:"Approve Transaction",BuyInProgress:"Buy",UsageExceeded:"Usage Exceeded",ConnectingExternal:n??"Connect Wallet",ConnectingWalletConnect:n??"WalletConnect",ConnectingWalletConnectBasic:"WalletConnect",ConnectingSiwe:"Sign In",Convert:"Convert",ConvertSelectToken:"Select token",ConvertPreview:"Preview Convert",Downloads:n?`Get ${n}`:"Downloads",EmailLogin:"Email Login",EmailVerifyOtp:"Confirm Email",EmailVerifyDevice:"Register Device",GetWallet:"Get a Wallet",Networks:"Choose Network",OnRampProviders:"Choose Provider",OnRampActivity:"Activity",OnRampTokenSelect:"Select Token",OnRampFiatSelect:"Select Currency",Pay:"How you pay",ProfileWallets:"Wallets",SwitchNetwork:r??"Switch Network",Transactions:"Activity",UnsupportedChain:"Switch Network",UpgradeEmailWallet:"Upgrade Your Wallet",UpdateEmailWallet:"Edit Email",UpdateEmailPrimaryOtp:"Confirm Current Email",UpdateEmailSecondaryOtp:"Confirm New Email",WhatIsABuy:"What is Buy?",RegisterAccountName:"Choose Name",RegisterAccountNameSuccess:"",WalletReceive:"Receive",WalletCompatibleNetworks:"Compatible Networks",Swap:"Swap",SwapSelectToken:"Select Token",SwapPreview:"Preview Swap",WalletSend:"Send",WalletSendPreview:"Review Send",WalletSendSelectToken:"Select Token",WalletSendConfirmed:"Confirmed",WhatIsANetwork:"What is a network?",WhatIsAWallet:"What is a Wallet?",ConnectWallets:"Connect Wallet",ConnectSocials:"All Socials",ConnectingSocial:a,ConnectingMultiChain:"Select Chain",ConnectingFarcaster:"Farcaster",SwitchActiveChain:"Switch Chain",SmartSessionCreated:void 0,SmartSessionList:"Smart Sessions",SIWXSignMessage:"Sign In",PayLoading:"Processing payment...",PayQuote:"Payment Quote",DataCapture:"Profile",DataCaptureOtpConfirm:"Confirm Email",FundWallet:"Fund Wallet",PayWithExchange:"Deposit from Exchange",PayWithExchangeSelectAsset:"Select Asset",SmartAccountSettings:"Smart Account Settings"}}var o1,Mtt,Htt,Fd,AEe=b(()=>{l();he();$e();kr();ct();Ve();jr();sq();J5e();Q5e();Zn();iq();bEe();vEe();o1=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Mtt=["SmartSessionList"],Htt={PayWithExchange:$t.tokens.theme.foregroundPrimary};Fd=class extends ie{constructor(){super(),this.unsubscribe=[],this.heading=EEe()[J.state.view],this.network=$.state.activeCaipNetwork,this.networkImage=St.getNetworkImage(this.network),this.showBack=!1,this.prevHistoryLength=1,this.view=J.state.view,this.viewDirection="",this.unsubscribe.push(Wn.subscribeNetworkImages(()=>{this.networkImage=St.getNetworkImage(this.network)}),J.subscribeKey("view",t=>{setTimeout(()=>{this.view=t,this.heading=EEe()[t]},jp.ANIMATION_DURATIONS.HeaderText),this.onViewChange(),this.onHistoryChange()}),$.subscribeKey("activeCaipNetwork",t=>{this.network=t,this.networkImage=St.getNetworkImage(this.network)}))}disconnectCallback(){this.unsubscribe.forEach(t=>t())}render(){let t=Htt[J.state.view]??$t.tokens.theme.backgroundPrimary;return this.style.setProperty("--local-header-background-color",t),V` + + ${this.leftHeaderTemplate()} ${this.titleTemplate()} ${this.rightHeaderTemplate()} + + `}onWalletHelp(){Ae.sendEvent({type:"track",event:"CLICK_WALLET_HELP"}),J.push("WhatIsAWallet")}async onClose(){await o5.safeClose()}rightHeaderTemplate(){let t=Y?.state?.features?.smartSessions;return J.state.view!=="Account"||!t?this.closeButtonTemplate():V` + J.push("SmartSessionList")} + data-testid="w3m-header-smart-sessions" + > + ${this.closeButtonTemplate()} + `}closeButtonTemplate(){return V` + + `}titleTemplate(){if(this.view==="PayQuote")return V``;let t=Mtt.includes(this.view);return V` + + + ${this.heading} + + ${t?V`Beta`:null} + + `}leftHeaderTemplate(){let{view:t}=J.state,r=t==="Connect",n=Y.state.enableEmbedded,o=t==="ApproveTransaction",s=t==="ConnectingSiwe",i=t==="Account",a=Y.state.enableNetworkSwitch,c=o||s||r&&n;return i&&a?V``:this.showBack&&!c?V``:V``}onNetworks(){this.isAllowedNetworkSwitch()&&(Ae.sendEvent({type:"track",event:"CLICK_NETWORKS"}),J.push("Networks"))}isAllowedNetworkSwitch(){let t=$.getAllRequestedCaipNetworks(),r=t?t.length>1:!1,n=t?.find(({id:o})=>o===this.network?.id);return r||!n}onViewChange(){let{history:t}=J.state,r=jp.VIEW_DIRECTION.Next;t.length1&&!this.showBack&&r?(await r.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.showBack=!0,r.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"})):t.length<=1&&this.showBack&&r&&(await r.animate([{opacity:1},{opacity:0}],{duration:200,fill:"forwards",easing:"ease"}).finished,this.showBack=!1,r.animate([{opacity:0},{opacity:1}],{duration:200,fill:"forwards",easing:"ease"}))}onGoBack(){J.goBack()}};Fd.styles=xEe;o1([le()],Fd.prototype,"heading",void 0);o1([le()],Fd.prototype,"network",void 0);o1([le()],Fd.prototype,"networkImage",void 0);o1([le()],Fd.prototype,"showBack",void 0);o1([le()],Fd.prototype,"prevHistoryLength",void 0);o1([le()],Fd.prototype,"view",void 0);o1([le()],Fd.prototype,"viewDirection",void 0);Fd=o1([ne("w3m-header")],Fd)});var CEe,SEe=b(()=>{l();Rt();CEe=fe` + :host { + display: flex; + align-items: center; + gap: ${({spacing:e})=>e[1]}; + padding: ${({spacing:e})=>e[2]} ${({spacing:e})=>e[3]} + ${({spacing:e})=>e[2]} ${({spacing:e})=>e[2]}; + border-radius: ${({borderRadius:e})=>e[20]}; + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + box-shadow: + 0px 0px 8px 0px rgba(0, 0, 0, 0.1), + inset 0 0 0 1px ${({tokens:e})=>e.theme.borderPrimary}; + max-width: 320px; + } + + wui-icon-box { + border-radius: ${({borderRadius:e})=>e.round} !important; + overflow: hidden; + } + + wui-loading-spinner { + padding: ${({spacing:e})=>e[1]}; + background-color: ${({tokens:e})=>e.core.foregroundAccent010}; + border-radius: ${({borderRadius:e})=>e.round} !important; + } +`});var Aq,VE,IEe=b(()=>{l();he();$e();wE();Rs();Mt();Bt();Sx();SEe();Aq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},VE=class extends ie{constructor(){super(...arguments),this.message="",this.variant="success"}render(){return V` + ${this.templateIcon()} + ${this.message} + `}templateIcon(){let t={success:"success",error:"error",warning:"warning",info:"default"},r={success:"checkmark",error:"warning",warning:"warningCircle",info:"info"};return this.variant==="loading"?V``:V``}};VE.styles=[Me,CEe];Aq([q()],VE.prototype,"message",void 0);Aq([q()],VE.prototype,"variant",void 0);VE=Aq([ne("wui-snackbar")],VE)});var TEe=b(()=>{l();IEe()});var _Ee,PEe=b(()=>{l();he();_Ee=Er` + :host { + display: block; + position: absolute; + opacity: 0; + pointer-events: none; + top: 11px; + left: 50%; + width: max-content; + } +`});var NEe,SN,REe=b(()=>{l();he();$e();ct();Ve();TEe();PEe();NEe=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},SN=class extends ie{constructor(){super(),this.unsubscribe=[],this.timeout=void 0,this.open=Je.state.open,this.unsubscribe.push(Je.subscribeKey("open",t=>{this.open=t,this.onOpen()}))}disconnectedCallback(){clearTimeout(this.timeout),this.unsubscribe.forEach(t=>t())}render(){let{message:t,variant:r}=Je.state;return V` `}onOpen(){clearTimeout(this.timeout),this.open?(this.animate([{opacity:0,transform:"translateX(-50%) scale(0.85)"},{opacity:1,transform:"translateX(-50%) scale(1)"}],{duration:150,fill:"forwards",easing:"ease"}),this.timeout&&clearTimeout(this.timeout),Je.state.autoClose&&(this.timeout=setTimeout(()=>Je.hide(),2500))):this.animate([{opacity:1,transform:"translateX(-50%) scale(1)"},{opacity:0,transform:"translateX(-50%) scale(0.85)"}],{duration:150,fill:"forwards",easing:"ease"})}};SN.styles=_Ee;NEe([le()],SN.prototype,"open",void 0);SN=NEe([ne("w3m-snackbar")],SN)});var OEe,BEe=b(()=>{l();he();OEe=Er` + :host { + width: 100%; + display: block; + } +`});var Cq,jE,kEe=b(()=>{l();he();$e();ct();Ve();BEe();Cq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},jE=class extends ie{constructor(){super(),this.unsubscribe=[],this.text="",this.open=ci.state.open,this.unsubscribe.push(J.subscribeKey("view",()=>{ci.hide()}),De.subscribeKey("open",t=>{t||ci.hide()}),ci.subscribeKey("open",t=>{this.open=t}))}disconnectedCallback(){this.unsubscribe.forEach(t=>t()),ci.hide()}render(){return V` +
+ ${this.renderChildren()} +
+ `}renderChildren(){return V` `}onMouseEnter(){let t=this.getBoundingClientRect();if(!this.open){let r=document.querySelector("w3m-modal"),n={width:t.width,height:t.height,left:t.left,top:t.top};if(r){let o=r.getBoundingClientRect();n.left=t.left-(window.innerWidth-o.width)/2,n.top=t.top-(window.innerHeight-o.height)/2}ci.showTooltip({message:this.text,triggerRect:n,variant:"shade"})}}onMouseLeave(t){this.contains(t.relatedTarget)||ci.hide()}};jE.styles=[OEe];Cq([q()],jE.prototype,"text",void 0);Cq([le()],jE.prototype,"open",void 0);jE=Cq([ne("w3m-tooltip-trigger")],jE)});var UEe,DEe=b(()=>{l();Ve();UEe=fe` + :host { + pointer-events: none; + } + + :host > wui-flex { + display: var(--w3m-tooltip-display); + opacity: var(--w3m-tooltip-opacity); + padding: 9px ${({spacing:e})=>e[3]} 10px ${({spacing:e})=>e[3]}; + border-radius: ${({borderRadius:e})=>e[3]}; + color: ${({tokens:e})=>e.theme.backgroundPrimary}; + position: absolute; + top: var(--w3m-tooltip-top); + left: var(--w3m-tooltip-left); + transform: translate(calc(-50% + var(--w3m-tooltip-parent-width)), calc(-100% - 8px)); + max-width: calc(var(--apkt-modal-width) - ${({spacing:e})=>e[5]}); + transition: opacity ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: opacity; + opacity: 0; + animation-duration: ${({durations:e})=>e.xl}; + animation-timing-function: ${({easings:e})=>e["ease-out-power-2"]}; + animation-name: fade-in; + animation-fill-mode: forwards; + } + + :host([data-variant='shade']) > wui-flex { + background-color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + :host([data-variant='shade']) > wui-flex > wui-text { + color: ${({tokens:e})=>e.theme.textSecondary}; + } + + :host([data-variant='fill']) > wui-flex { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + border: 1px solid ${({tokens:e})=>e.theme.borderPrimary}; + } + + wui-icon { + position: absolute; + width: 12px !important; + height: 4px !important; + color: ${({tokens:e})=>e.theme.foregroundPrimary}; + } + + wui-icon[data-placement='top'] { + bottom: 0px; + left: 50%; + transform: translate(-50%, 95%); + } + + wui-icon[data-placement='bottom'] { + top: 0; + left: 50%; + transform: translate(-50%, -95%) rotate(180deg); + } + + wui-icon[data-placement='right'] { + top: 50%; + left: 0; + transform: translate(-65%, -50%) rotate(90deg); + } + + wui-icon[data-placement='left'] { + top: 50%; + right: 0%; + transform: translate(65%, -50%) rotate(270deg); + } + + @keyframes fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } + } +`});var qE,d2,LEe=b(()=>{l();he();$e();ct();Ve();jr();$p();Zn();DEe();qE=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},d2=class extends ie{constructor(){super(),this.unsubscribe=[],this.open=ci.state.open,this.message=ci.state.message,this.triggerRect=ci.state.triggerRect,this.variant=ci.state.variant,this.unsubscribe.push(ci.subscribe(t=>{this.open=t.open,this.message=t.message,this.triggerRect=t.triggerRect,this.variant=t.variant}))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){this.dataset.variant=this.variant;let t=this.triggerRect.top,r=this.triggerRect.left;return this.style.cssText=` + --w3m-tooltip-top: ${t}px; + --w3m-tooltip-left: ${r}px; + --w3m-tooltip-parent-width: ${this.triggerRect.width/2}px; + --w3m-tooltip-display: ${this.open?"flex":"none"}; + --w3m-tooltip-opacity: ${this.open?1:0}; + `,V` + + ${this.message} + `}};d2.styles=[UEe];qE([le()],d2.prototype,"open",void 0);qE([le()],d2.prototype,"message",void 0);qE([le()],d2.prototype,"triggerRect",void 0);qE([le()],d2.prototype,"variant",void 0);d2=qE([ne("w3m-tooltip")],d2)});var f2,Sq=b(()=>{l();ut();ct();iq();f2={getTabsByNamespace(e){return!!e&&e===Z.CHAIN.EVM?Y.state.remoteFeatures?.activity===!1?jp.ACCOUNT_TABS.filter(r=>r.label!=="Activity"):jp.ACCOUNT_TABS:[]},isValidReownName(e){return/^[a-zA-Z0-9]+$/gu.test(e)},isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/gu.test(e)},validateReownName(e){return e.replace(/\^/gu,"").toLowerCase().replace(/[^a-zA-Z0-9]/gu,"")},hasFooter(){let e=J.state.view;if(jp.VIEWS_WITH_LEGAL_FOOTER.includes(e)){let{termsConditionsUrl:t,privacyPolicyUrl:r}=Y.state,n=Y.state.features?.legalCheckbox;return!(!t&&!r||n)}return jp.VIEWS_WITH_DEFAULT_FOOTER.includes(e)}}});var MEe,HEe=b(()=>{l();Ve();MEe=fe` + :host wui-ux-by-reown { + padding-top: 0; + } + + :host wui-ux-by-reown.branding-only { + padding-top: ${({spacing:e})=>e[3]}; + } + + a { + text-decoration: none; + color: ${({tokens:e})=>e.core.textAccentPrimary}; + font-weight: 500; + } +`});var $Ee,IN,FEe=b(()=>{l();he();$e();ct();Ve();jr();Zn();Wj();HEe();$Ee=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},IN=class extends ie{constructor(){super(),this.unsubscribe=[],this.remoteFeatures=Y.state.remoteFeatures,this.unsubscribe.push(Y.subscribeKey("remoteFeatures",t=>this.remoteFeatures=t))}disconnectedCallback(){this.unsubscribe.forEach(t=>t())}render(){let{termsConditionsUrl:t,privacyPolicyUrl:r}=Y.state,n=Y.state.features?.legalCheckbox;return!t&&!r||n?V` + ${this.reownBrandingTemplate(!0)} + `:V` + + + + By connecting your wallet, you agree to our
+ ${this.termsTemplate()} ${this.andTemplate()} ${this.privacyTemplate()} +
+
+ ${this.reownBrandingTemplate()} +
+ `}andTemplate(){let{termsConditionsUrl:t,privacyPolicyUrl:r}=Y.state;return t&&r?"and":""}termsTemplate(){let{termsConditionsUrl:t}=Y.state;return t?V`Terms of Service`:null}privacyTemplate(){let{privacyPolicyUrl:t}=Y.state;return t?V`Privacy Policy`:null}reownBrandingTemplate(t=!1){return this.remoteFeatures?.reownBranding?t?V``:V``:null}};IN.styles=[MEe];$Ee([le()],IN.prototype,"remoteFeatures",void 0);IN=$Ee([ne("w3m-legal-footer")],IN)});var zEe,VEe=b(()=>{l();he();zEe=Er``});var $tt,Iq,jEe=b(()=>{l();he();ct();Ve();jr();$p();jP();Zn();mm();VEe();$tt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Iq=class extends ie{render(){let{termsConditionsUrl:t,privacyPolicyUrl:r}=Y.state;return!t&&!r?null:V` + + + We work with the best providers to give you the lowest fees and best support. More options + coming soon! + + + ${this.howDoesItWorkTemplate()} + + `}howDoesItWorkTemplate(){return V` + + How does it work? + `}onWhatIsBuy(){Ae.sendEvent({type:"track",event:"SELECT_WHAT_IS_A_BUY",properties:{isSmartAccount:Fr($.state.activeChain)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),J.push("WhatIsABuy")}};Iq.styles=[zEe];Iq=$tt([ne("w3m-onramp-providers-footer")],Iq)});var qEe,WEe=b(()=>{l();Ve();qEe=fe` + :host { + display: block; + } + + div.container { + position: absolute; + bottom: 0; + left: 0; + right: 0; + overflow: hidden; + height: auto; + display: block; + } + + div.container[status='hide'] { + animation: fade-out; + animation-duration: var(--apkt-duration-dynamic); + animation-timing-function: ${({easings:e})=>e["ease-out-power-2"]}; + animation-fill-mode: both; + animation-delay: 0s; + } + + div.container[status='show'] { + animation: fade-in; + animation-duration: var(--apkt-duration-dynamic); + animation-timing-function: ${({easings:e})=>e["ease-out-power-2"]}; + animation-fill-mode: both; + animation-delay: var(--apkt-duration-dynamic); + } + + @keyframes fade-in { + from { + opacity: 0; + filter: blur(6px); + } + to { + opacity: 1; + filter: blur(0px); + } + } + + @keyframes fade-out { + from { + opacity: 1; + filter: blur(0px); + } + to { + opacity: 0; + filter: blur(6px); + } + } +`});var Tq,WE,_q=b(()=>{l();he();$e();ct();Ve();FEe();jEe();Sq();WEe();Tq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},WE=class extends ie{constructor(){super(...arguments),this.resizeObserver=void 0,this.unsubscribe=[],this.status="hide",this.view=J.state.view}firstUpdated(){this.status=f2.hasFooter()?"show":"hide",this.unsubscribe.push(J.subscribeKey("view",t=>{this.view=t,this.status=f2.hasFooter()?"show":"hide",this.status==="hide"&&document.documentElement.style.setProperty("--apkt-footer-height","0px")})),this.resizeObserver=new ResizeObserver(t=>{for(let r of t)if(r.target===this.getWrapper()){let n=`${r.contentRect.height}px`;document.documentElement.style.setProperty("--apkt-footer-height",n)}}),this.resizeObserver.observe(this.getWrapper())}render(){return V` +
${this.templatePageContainer()}
+ `}templatePageContainer(){return f2.hasFooter()?V` ${this.templateFooter()}`:null}templateFooter(){switch(this.view){case"Networks":return this.templateNetworksFooter();case"Connect":case"ConnectWallets":case"OnRampFiatSelect":case"OnRampTokenSelect":return V``;case"OnRampProviders":return V``;default:return null}}templateNetworksFooter(){return V` + + Your connected wallet may not support some of the networks available for this dApp + + + + What is a network + + `}onNetworkHelp(){Ae.sendEvent({type:"track",event:"CLICK_NETWORK_HELP"}),J.push("WhatIsANetwork")}getWrapper(){return this.shadowRoot?.querySelector("div.container")}};WE.styles=[qEe];Tq([le()],WE.prototype,"status",void 0);Tq([le()],WE.prototype,"view",void 0);WE=Tq([ne("w3m-footer")],WE)});var KEe,ZEe=b(()=>{l();Ve();KEe=fe` + :host { + display: block; + width: inherit; + } +`});var Pq,KE,GEe=b(()=>{l();he();$e();ct();Ve();_q();ZEe();Pq=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},KE=class extends ie{constructor(){super(),this.unsubscribe=[],this.viewState=J.state.view,this.history=J.state.history.join(","),this.unsubscribe.push(J.subscribeKey("view",()=>{this.history=J.state.history.join(","),document.documentElement.style.setProperty("--apkt-duration-dynamic","var(--apkt-durations-lg)")}))}disconnectedCallback(){this.unsubscribe.forEach(t=>t()),document.documentElement.style.setProperty("--apkt-duration-dynamic","0s")}render(){return V`${this.templatePageContainer()}`}templatePageContainer(){return V`{this.viewState=J.state.view}} + > + ${this.viewTemplate(this.viewState)} + `}viewTemplate(t){switch(t){case"AccountSettings":return V``;case"Account":return V``;case"AllWallets":return V``;case"ApproveTransaction":return V``;case"BuyInProgress":return V``;case"ChooseAccountName":return V``;case"Connect":return V``;case"Create":return V``;case"ConnectingWalletConnect":return V``;case"ConnectingWalletConnectBasic":return V``;case"ConnectingExternal":return V``;case"ConnectingSiwe":return V``;case"ConnectWallets":return V``;case"ConnectSocials":return V``;case"ConnectingSocial":return V``;case"DataCapture":return V``;case"DataCaptureOtpConfirm":return V``;case"Downloads":return V``;case"EmailLogin":return V``;case"EmailVerifyOtp":return V``;case"EmailVerifyDevice":return V``;case"GetWallet":return V``;case"Networks":return V``;case"SwitchNetwork":return V``;case"ProfileWallets":return V``;case"Transactions":return V``;case"OnRampProviders":return V``;case"OnRampTokenSelect":return V``;case"OnRampFiatSelect":return V``;case"UpgradeEmailWallet":return V``;case"UpdateEmailWallet":return V``;case"UpdateEmailPrimaryOtp":return V``;case"UpdateEmailSecondaryOtp":return V``;case"UnsupportedChain":return V``;case"Swap":return V``;case"SwapSelectToken":return V``;case"SwapPreview":return V``;case"WalletSend":return V``;case"WalletSendSelectToken":return V``;case"WalletSendPreview":return V``;case"WalletSendConfirmed":return V``;case"WhatIsABuy":return V``;case"WalletReceive":return V``;case"WalletCompatibleNetworks":return V``;case"WhatIsAWallet":return V``;case"ConnectingMultiChain":return V``;case"WhatIsANetwork":return V``;case"ConnectingFarcaster":return V``;case"SwitchActiveChain":return V``;case"RegisterAccountName":return V``;case"RegisterAccountNameSuccess":return V``;case"SmartSessionCreated":return V``;case"SmartSessionList":return V``;case"SIWXSignMessage":return V``;case"Pay":return V``;case"PayLoading":return V``;case"PayQuote":return V``;case"FundWallet":return V``;case"PayWithExchange":return V``;case"PayWithExchangeSelectAsset":return V``;case"UsageExceeded":return V``;case"SmartAccountSettings":return V``;default:return V``}}};KE.styles=[KEe];Pq([le()],KE.prototype,"viewState",void 0);Pq([le()],KE.prototype,"history",void 0);KE=Pq([ne("w3m-router")],KE)});var YEe,JEe=b(()=>{l();Ve();YEe=fe` + :host { + z-index: ${({tokens:e})=>e.core.zIndex}; + display: block; + backface-visibility: hidden; + will-change: opacity; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + pointer-events: none; + opacity: 0; + background-color: ${({tokens:e})=>e.theme.overlay}; + backdrop-filter: blur(0px); + transition: + opacity ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + backdrop-filter ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + will-change: opacity; + } + + :host(.open) { + opacity: 1; + backdrop-filter: blur(8px); + } + + :host(.appkit-modal) { + position: relative; + pointer-events: unset; + background: none; + width: 100%; + opacity: 1; + } + + wui-card { + max-width: var(--apkt-modal-width); + width: 100%; + position: relative; + outline: none; + transform: translateY(4px); + box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.05); + transition: + transform ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}, + border-radius ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}, + background-color ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}, + box-shadow ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-1"]}; + will-change: border-radius, background-color, transform, box-shadow; + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + padding: var(--local-modal-padding); + box-sizing: border-box; + } + + :host(.open) wui-card { + transform: translateY(0px); + } + + wui-card::before { + z-index: 1; + pointer-events: none; + content: ''; + position: absolute; + inset: 0; + border-radius: clamp(0px, var(--apkt-borderRadius-8), 44px); + transition: box-shadow ${({durations:e})=>e.lg} + ${({easings:e})=>e["ease-out-power-2"]}; + transition-delay: ${({durations:e})=>e.md}; + will-change: box-shadow; + } + + :host([data-mobile-fullscreen='true']) wui-card::before { + border-radius: 0px; + } + + :host([data-border='true']) wui-card::before { + box-shadow: inset 0px 0px 0px 4px ${({tokens:e})=>e.theme.foregroundSecondary}; + } + + :host([data-border='false']) wui-card::before { + box-shadow: inset 0px 0px 0px 1px ${({tokens:e})=>e.theme.borderPrimaryDark}; + } + + :host([data-border='true']) wui-card { + animation: + fade-in ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + card-background-border var(--apkt-duration-dynamic) + ${({easings:e})=>e["ease-out-power-2"]}; + animation-fill-mode: backwards, both; + animation-delay: var(--apkt-duration-dynamic); + } + + :host([data-border='false']) wui-card { + animation: + fade-in ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + card-background-default var(--apkt-duration-dynamic) + ${({easings:e})=>e["ease-out-power-2"]}; + animation-fill-mode: backwards, both; + animation-delay: 0s; + } + + :host(.appkit-modal) wui-card { + max-width: var(--apkt-modal-width); + } + + wui-card[shake='true'] { + animation: + fade-in ${({durations:e})=>e.lg} ${({easings:e})=>e["ease-out-power-2"]}, + w3m-shake ${({durations:e})=>e.xl} + ${({easings:e})=>e["ease-out-power-2"]}; + } + + wui-flex { + overflow-x: hidden; + overflow-y: auto; + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + } + + @media (max-height: 700px) and (min-width: 431px) { + wui-flex { + align-items: flex-start; + } + + wui-card { + margin: var(--apkt-spacing-6) 0px; + } + } + + @media (max-width: 430px) { + :host([data-mobile-fullscreen='true']) { + height: 100dvh; + } + :host([data-mobile-fullscreen='true']) wui-flex { + align-items: stretch; + } + :host([data-mobile-fullscreen='true']) wui-card { + max-width: 100%; + height: 100%; + border-radius: 0; + border: none; + } + :host(:not([data-mobile-fullscreen='true'])) wui-flex { + align-items: flex-end; + } + + :host(:not([data-mobile-fullscreen='true'])) wui-card { + max-width: 100%; + border-bottom: none; + } + + :host(:not([data-mobile-fullscreen='true'])) wui-card[data-embedded='true'] { + border-bottom-left-radius: clamp(0px, var(--apkt-borderRadius-8), 44px); + border-bottom-right-radius: clamp(0px, var(--apkt-borderRadius-8), 44px); + } + + :host(:not([data-mobile-fullscreen='true'])) wui-card:not([data-embedded='true']) { + border-bottom-left-radius: 0px; + border-bottom-right-radius: 0px; + } + + wui-card[shake='true'] { + animation: w3m-shake 0.5s ${({easings:e})=>e["ease-out-power-2"]}; + } + } + + @keyframes fade-in { + 0% { + transform: scale(0.99) translateY(4px); + } + 100% { + transform: scale(1) translateY(0); + } + } + + @keyframes w3m-shake { + 0% { + transform: scale(1) rotate(0deg); + } + 20% { + transform: scale(1) rotate(-1deg); + } + 40% { + transform: scale(1) rotate(1.5deg); + } + 60% { + transform: scale(1) rotate(-1.5deg); + } + 80% { + transform: scale(1) rotate(1deg); + } + 100% { + transform: scale(1) rotate(0deg); + } + } + + @keyframes card-background-border { + from { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + } + to { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + } + + @keyframes card-background-default { + from { + background-color: ${({tokens:e})=>e.theme.foregroundSecondary}; + } + to { + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + } + } +`});var zd,QEe,Ftt,ea,Nq,Rq,XEe=b(()=>{l();he();$e();kr();ct();Ve();D5e();jr();j5e();AEe();REe();kEe();LEe();Sq();_q();GEe();JEe();zd=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},QEe="scroll-lock",Ftt={PayWithExchange:"0",PayWithExchangeSelectAsset:"0",Pay:"0",PayQuote:"0",PayLoading:"0"},ea=class extends ie{constructor(){super(),this.unsubscribe=[],this.abortController=void 0,this.hasPrefetched=!1,this.enableEmbedded=Y.state.enableEmbedded,this.open=De.state.open,this.caipAddress=$.state.activeCaipAddress,this.caipNetwork=$.state.activeCaipNetwork,this.shake=De.state.shake,this.filterByNamespace=re.state.filterByNamespace,this.padding=$t.spacing[1],this.mobileFullScreen=Y.state.enableMobileFullScreen,this.initializeTheming(),ge.prefetchAnalyticsConfig(),this.unsubscribe.push(De.subscribeKey("open",t=>t?this.onOpen():this.onClose()),De.subscribeKey("shake",t=>this.shake=t),$.subscribeKey("activeCaipNetwork",t=>this.onNewNetwork(t)),$.subscribeKey("activeCaipAddress",t=>this.onNewAddress(t)),Y.subscribeKey("enableEmbedded",t=>this.enableEmbedded=t),re.subscribeKey("filterByNamespace",t=>{this.filterByNamespace!==t&&!$.getAccountData(t)?.caipAddress&&(ge.fetchRecommendedWallets(),this.filterByNamespace=t)}),J.subscribeKey("view",()=>{this.dataset.border=f2.hasFooter()?"true":"false",this.padding=Ftt[J.state.view]??$t.spacing[1]}))}firstUpdated(){if(this.dataset.border=f2.hasFooter()?"true":"false",this.mobileFullScreen&&this.setAttribute("data-mobile-fullscreen","true"),this.caipAddress){if(this.enableEmbedded){De.close(),this.prefetch();return}this.onNewAddress(this.caipAddress)}this.open&&this.onOpen(),this.enableEmbedded&&this.prefetch()}disconnectedCallback(){this.unsubscribe.forEach(t=>t()),this.onRemoveKeyboardListener()}render(){return this.style.setProperty("--local-modal-padding",this.padding),this.enableEmbedded?V`${this.contentTemplate()} + `:this.open?V` + + ${this.contentTemplate()} + + + `:null}contentTemplate(){return V` + + + + + + `}async onOverlayClick(t){if(t.target===t.currentTarget){if(this.mobileFullScreen)return;await this.handleClose()}}async handleClose(){await o5.safeClose()}initializeTheming(){let{themeVariables:t,themeMode:r}=nn.state,n=hr.getColorTheme(r);ZV(t,n)}onClose(){this.open=!1,this.classList.remove("open"),this.onScrollUnlock(),Je.hide(),this.onRemoveKeyboardListener()}onOpen(){this.open=!0,this.classList.add("open"),this.onScrollLock(),this.onAddKeyboardListener()}onScrollLock(){let t=document.createElement("style");t.dataset.w3m=QEe,t.textContent=` + body { + touch-action: none; + overflow: hidden; + overscroll-behavior: contain; + } + w3m-modal { + pointer-events: auto; + } + `,document.head.appendChild(t)}onScrollUnlock(){let t=document.head.querySelector(`style[data-w3m="${QEe}"]`);t&&t.remove()}onAddKeyboardListener(){this.abortController=new AbortController;let t=this.shadowRoot?.querySelector("wui-card");t?.focus(),window.addEventListener("keydown",r=>{if(r.key==="Escape")this.handleClose();else if(r.key==="Tab"){let{tagName:n}=r.target;n&&!n.includes("W3M-")&&!n.includes("WUI-")&&t?.focus()}},this.abortController)}onRemoveKeyboardListener(){this.abortController?.abort(),this.abortController=void 0}async onNewAddress(t){let r=$.state.isSwitchingNamespace,n=J.state.view==="ProfileWallets";!t&&!r&&!n&&De.close(),await _o.initializeIfEnabled(t),this.caipAddress=t,$.setIsSwitchingNamespace(!1)}onNewNetwork(t){let n=this.caipNetwork?.caipNetworkId?.toString(),o=t?.caipNetworkId?.toString(),s=n!==o,i=J.state.view==="UnsupportedChain",a=De.state.open,c=!1;this.enableEmbedded&&J.state.view==="SwitchNetwork"&&(c=!0),s&&ot.resetState(),a&&i&&(c=!0),c&&J.state.view!=="SIWXSignMessage"&&J.goBack(),this.caipNetwork=t}prefetch(){this.hasPrefetched||(ge.prefetch(),ge.fetchWalletsByPage({page:1}),this.hasPrefetched=!0)}};ea.styles=YEe;zd([q({type:Boolean})],ea.prototype,"enableEmbedded",void 0);zd([le()],ea.prototype,"open",void 0);zd([le()],ea.prototype,"caipAddress",void 0);zd([le()],ea.prototype,"caipNetwork",void 0);zd([le()],ea.prototype,"shake",void 0);zd([le()],ea.prototype,"filterByNamespace",void 0);zd([le()],ea.prototype,"padding",void 0);zd([le()],ea.prototype,"mobileFullScreen",void 0);Nq=class extends ea{};Nq=zd([ne("w3m-modal")],Nq);Rq=class extends ea{};Rq=zd([ne("appkit-modal")],Rq)});var eAe,tAe=b(()=>{l();Ve();eAe=fe` + .icon-box { + width: 64px; + height: 64px; + border-radius: ${({borderRadius:e})=>e[5]}; + background-color: ${({colors:e})=>e.semanticError010}; + } +`});var ztt,TN,rAe=b(()=>{l();he();ct();Ve();bE();jr();$p();Zn();tAe();ztt=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},TN=class extends ie{constructor(){super()}render(){return V` + + + + + + + The app isn't responding as expected + + + Try again or reach out to the app team for help. + + + + + Try Again + + + `}onTryAgainClick(){J.goBack()}};TN.styles=eAe;TN=ztt([ne("w3m-usage-exceeded-view")],TN)});var nAe,oAe=b(()=>{l();Ve();nAe=fe` + :host { + width: 100%; + } +`});var Yo,Jn,sAe=b(()=>{l();he();$e();kr();ct();Ve();mj();oAe();Yo=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Jn=class extends ie{constructor(){super(...arguments),this.hasImpressionSent=!1,this.walletImages=[],this.imageSrc="",this.name="",this.size="md",this.tabIdx=void 0,this.disabled=!1,this.showAllWallets=!1,this.loading=!1,this.loadingSpinnerColor="accent-100",this.rdnsId="",this.displayIndex=void 0,this.walletRank=void 0,this.namespaces=[]}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this.cleanupIntersectionObserver()}updated(t){super.updated(t),(t.has("name")||t.has("imageSrc")||t.has("walletRank"))&&(this.hasImpressionSent=!1),t.has("walletRank")&&this.walletRank&&!this.intersectionObserver&&this.setupIntersectionObserver()}setupIntersectionObserver(){this.intersectionObserver=new IntersectionObserver(t=>{t.forEach(r=>{r.isIntersecting&&!this.loading&&!this.hasImpressionSent&&this.sendImpressionEvent()})},{threshold:.1}),this.intersectionObserver.observe(this)}cleanupIntersectionObserver(){this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=void 0)}sendImpressionEvent(){!this.name||this.hasImpressionSent||!this.walletRank||(this.hasImpressionSent=!0,(this.rdnsId||this.name)&&Ae.sendWalletImpressionEvent({name:this.name,walletRank:this.walletRank,rdnsId:this.rdnsId,view:J.state.view,displayIndex:this.displayIndex}))}handleGetWalletNamespaces(){return Object.keys(iy.state.adapters).length>1?this.namespaces:[]}render(){return V` + + `}};Jn.styles=nAe;Yo([q({type:Array})],Jn.prototype,"walletImages",void 0);Yo([q()],Jn.prototype,"imageSrc",void 0);Yo([q()],Jn.prototype,"name",void 0);Yo([q()],Jn.prototype,"size",void 0);Yo([q()],Jn.prototype,"tagLabel",void 0);Yo([q()],Jn.prototype,"tagVariant",void 0);Yo([q()],Jn.prototype,"walletIcon",void 0);Yo([q()],Jn.prototype,"tabIdx",void 0);Yo([q({type:Boolean})],Jn.prototype,"disabled",void 0);Yo([q({type:Boolean})],Jn.prototype,"showAllWallets",void 0);Yo([q({type:Boolean})],Jn.prototype,"loading",void 0);Yo([q({type:String})],Jn.prototype,"loadingSpinnerColor",void 0);Yo([q()],Jn.prototype,"rdnsId",void 0);Yo([q()],Jn.prototype,"displayIndex",void 0);Yo([q()],Jn.prototype,"walletRank",void 0);Yo([q({type:Array})],Jn.prototype,"namespaces",void 0);Jn=Yo([ne("w3m-list-wallet")],Jn)});var iAe,aAe=b(()=>{l();Ve();iAe=fe` + :host { + --local-duration-height: 0s; + --local-duration: ${({durations:e})=>e.lg}; + --local-transition: ${({easings:e})=>e["ease-out-power-2"]}; + } + + .container { + display: block; + overflow: hidden; + overflow: hidden; + position: relative; + height: var(--local-container-height); + transition: height var(--local-duration-height) var(--local-transition); + will-change: height, padding-bottom; + } + + .container[data-mobile-fullscreen='true'] { + overflow: scroll; + } + + .page { + position: absolute; + top: 0; + left: 0; + right: 0; + width: 100%; + height: auto; + width: inherit; + box-sizing: border-box; + display: flex; + flex-direction: column; + background-color: ${({tokens:e})=>e.theme.backgroundPrimary}; + border-bottom-left-radius: var(--local-border-bottom-radius); + border-bottom-right-radius: var(--local-border-bottom-radius); + transition: border-bottom-left-radius var(--local-duration) var(--local-transition); + } + + .page[data-mobile-fullscreen='true'] { + height: 100%; + } + + .page-content { + display: flex; + flex-direction: column; + min-height: 100%; + } + + .footer { + height: var(--apkt-footer-height); + } + + div.page[view-direction^='prev-'] .page-content { + animation: + slide-left-out var(--local-duration) forwards var(--local-transition), + slide-left-in var(--local-duration) forwards var(--local-transition); + animation-delay: 0ms, var(--local-duration, ${({durations:e})=>e.lg}); + } + + div.page[view-direction^='next-'] .page-content { + animation: + slide-right-out var(--local-duration) forwards var(--local-transition), + slide-right-in var(--local-duration) forwards var(--local-transition); + animation-delay: 0ms, var(--local-duration, ${({durations:e})=>e.lg}); + } + + @keyframes slide-left-out { + from { + transform: translateX(0px) scale(1); + opacity: 1; + filter: blur(0px); + } + to { + transform: translateX(8px) scale(0.99); + opacity: 0; + filter: blur(4px); + } + } + + @keyframes slide-left-in { + from { + transform: translateX(-8px) scale(0.99); + opacity: 0; + filter: blur(4px); + } + to { + transform: translateX(0) translateY(0) scale(1); + opacity: 1; + filter: blur(0px); + } + } + + @keyframes slide-right-out { + from { + transform: translateX(0px) scale(1); + opacity: 1; + filter: blur(0px); + } + to { + transform: translateX(-8px) scale(0.99); + opacity: 0; + filter: blur(4px); + } + } + + @keyframes slide-right-in { + from { + transform: translateX(8px) scale(0.99); + opacity: 0; + filter: blur(4px); + } + to { + transform: translateX(0) translateY(0) scale(1); + opacity: 1; + filter: blur(0px); + } + } +`});var Vd,Vtt,$a,cAe=b(()=>{l();he();$e();kr();ct();Ve();aAe();Vd=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Vtt=60,$a=class extends ie{constructor(){super(...arguments),this.resizeObserver=void 0,this.transitionDuration="0.15s",this.transitionFunction="",this.history="",this.view="",this.setView=void 0,this.viewDirection="",this.historyState="",this.previousHeight="0px",this.mobileFullScreen=Y.state.enableMobileFullScreen,this.onViewportResize=()=>{this.updateContainerHeight()}}updated(t){if(t.has("history")){let r=this.history;this.historyState!==""&&this.historyState!==r&&this.onViewChange(r)}t.has("transitionDuration")&&this.style.setProperty("--local-duration",this.transitionDuration),t.has("transitionFunction")&&this.style.setProperty("--local-transition",this.transitionFunction)}firstUpdated(){this.transitionFunction&&this.style.setProperty("--local-transition",this.transitionFunction),this.style.setProperty("--local-duration",this.transitionDuration),this.historyState=this.history,this.resizeObserver=new ResizeObserver(t=>{for(let r of t)if(r.target===this.getWrapper()){let n=r.contentRect.height,o=parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--apkt-footer-height")||"0");if(this.mobileFullScreen){let s=window.visualViewport?.height||window.innerHeight,i=this.getHeaderHeight();n=s-i-o,this.style.setProperty("--local-border-bottom-radius","0px")}else n=n+o,this.style.setProperty("--local-border-bottom-radius",o?"var(--apkt-borderRadius-5)":"0px");this.style.setProperty("--local-container-height",`${n}px`),this.previousHeight!=="0px"&&this.style.setProperty("--local-duration-height",this.transitionDuration),this.previousHeight=`${n}px`}}),this.resizeObserver.observe(this.getWrapper()),this.updateContainerHeight(),window.addEventListener("resize",this.onViewportResize),window.visualViewport?.addEventListener("resize",this.onViewportResize)}disconnectedCallback(){let t=this.getWrapper();t&&this.resizeObserver&&this.resizeObserver.unobserve(t),window.removeEventListener("resize",this.onViewportResize),window.visualViewport?.removeEventListener("resize",this.onViewportResize)}render(){return V` +
+
+
+ +
+
+
+ `}onViewChange(t){let r=t.split(",").filter(Boolean),n=this.historyState.split(",").filter(Boolean),o=n.length,s=r.length,i=r[r.length-1]||"",a=hr.cssDurationToNumber(this.transitionDuration),c="";s>o?c="next":s{this.historyState=t,this.setView?.(i)},a),setTimeout(()=>{this.viewDirection=""},a*2)}getWrapper(){return this.shadowRoot?.querySelector("div.page")}updateContainerHeight(){let t=this.getWrapper();if(!t)return;let r=parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--apkt-footer-height")||"0"),n=0;if(this.mobileFullScreen){let o=window.visualViewport?.height||window.innerHeight,s=this.getHeaderHeight();n=o-s-r,this.style.setProperty("--local-border-bottom-radius","0px")}else n=t.getBoundingClientRect().height+r,this.style.setProperty("--local-border-bottom-radius",r?"var(--apkt-borderRadius-5)":"0px");this.style.setProperty("--local-container-height",`${n}px`),this.previousHeight!=="0px"&&this.style.setProperty("--local-duration-height",this.transitionDuration),this.previousHeight=`${n}px`}getHeaderHeight(){return Vtt}};$a.styles=[iAe];Vd([q({type:String})],$a.prototype,"transitionDuration",void 0);Vd([q({type:String})],$a.prototype,"transitionFunction",void 0);Vd([q({type:String})],$a.prototype,"history",void 0);Vd([q({type:String})],$a.prototype,"view",void 0);Vd([q({attribute:!1})],$a.prototype,"setView",void 0);Vd([le()],$a.prototype,"viewDirection",void 0);Vd([le()],$a.prototype,"historyState",void 0);Vd([le()],$a.prototype,"previousHeight",void 0);Vd([le()],$a.prototype,"mobileFullScreen",void 0);$a=Vd([ne("w3m-router-container")],$a)});var lAe={};Te(lAe,{AppKitModal:()=>Rq,W3mListWallet:()=>Jn,W3mModal:()=>Nq,W3mModalBase:()=>ea,W3mRouterContainer:()=>$a,W3mUsageExceededView:()=>TN});var uAe=b(()=>{l();XEe();rAe();sAe();cAe()});var dAe,ZE,fAe=b(()=>{l();ct();Iwe();dAe=!1,ZE=class extends RP{async open(t){re.isConnected()||await super.open(t)}async close(){if(await super.close(),this.options.manualWCControl){let t=$.getAccountData(this.activeChainNamespace)?.address;ee.finalizeWcConnection(t)}}async syncIdentity(t){return Promise.resolve()}async syncBalance(t){return Promise.resolve()}async injectModalUi(){if(!dAe&&se.isClient()){if(await Promise.resolve().then(()=>(O5e(),R5e)),await Promise.resolve().then(()=>(uAe(),lAe)),!document.querySelector("w3m-modal")){let r=document.createElement("w3m-modal");!Y.state.disableAppend&&!Y.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",r)}dAe=!0}}}});var pAe,hAe=b(()=>{l();pAe="1.8.17-wc-circular-dependencies-fix.0"});var mAe={};Te(mAe,{AppKit:()=>ZE,createAppKit:()=>jtt});function jtt(e){return new ZE({...e,basic:!0,sdkVersion:`html-core-${pAe}`})}var gAe=b(()=>{l();fAe();hAe()});var EAe=_e((r$r,vAe)=>{l();vAe.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var s1=_e(p2=>{l();var kq,ort=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];p2.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};p2.getSymbolTotalCodewords=function(t){return ort[t]};p2.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t};p2.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');kq=t};p2.isKanjiModeEnabled=function(){return typeof kq<"u"};p2.toSJIS=function(t){return kq(t)}});var NN=_e(Nc=>{l();Nc.L={bit:1};Nc.M={bit:0};Nc.Q={bit:3};Nc.H={bit:2};function srt(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return Nc.L;case"m":case"medium":return Nc.M;case"q":case"quartile":return Nc.Q;case"h":case"high":return Nc.H;default:throw new Error("Unknown EC Level: "+e)}}Nc.isValid=function(t){return t&&typeof t.bit<"u"&&t.bit>=0&&t.bit<4};Nc.from=function(t,r){if(Nc.isValid(t))return t;try{return srt(t)}catch{return r}}});var SAe=_e((c$r,CAe)=>{l();function AAe(){this.buffer=[],this.length=0}AAe.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let r=0;r>>t-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};CAe.exports=AAe});var TAe=_e((u$r,IAe)=>{l();function GE(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}GE.prototype.set=function(e,t,r,n){let o=e*this.size+t;this.data[o]=r,n&&(this.reservedBit[o]=!0)};GE.prototype.get=function(e,t){return this.data[e*this.size+t]};GE.prototype.xor=function(e,t,r){this.data[e*this.size+t]^=r};GE.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};IAe.exports=GE});var _Ae=_e(RN=>{l();var irt=s1().getSymbolSize;RN.getRowColCoords=function(t){if(t===1)return[];let r=Math.floor(t/7)+2,n=irt(t),o=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let i=1;i{l();var art=s1().getSymbolSize,PAe=7;NAe.getPositions=function(t){let r=art(t);return[[0,0],[r-PAe,0],[0,r-PAe]]}});var OAe=_e(Wr=>{l();Wr.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var h2={N1:3,N2:3,N3:40,N4:10};Wr.isValid=function(t){return t!=null&&t!==""&&!isNaN(t)&&t>=0&&t<=7};Wr.from=function(t){return Wr.isValid(t)?parseInt(t,10):void 0};Wr.getPenaltyN1=function(t){let r=t.size,n=0,o=0,s=0,i=null,a=null;for(let c=0;c=5&&(n+=h2.N1+(o-5)),i=d,o=1),d=t.get(u,c),d===a?s++:(s>=5&&(n+=h2.N1+(s-5)),a=d,s=1)}o>=5&&(n+=h2.N1+(o-5)),s>=5&&(n+=h2.N1+(s-5))}return n};Wr.getPenaltyN2=function(t){let r=t.size,n=0;for(let o=0;o=10&&(o===1488||o===93)&&n++,s=s<<1&2047|t.get(a,i),a>=10&&(s===1488||s===93)&&n++}return n*h2.N3};Wr.getPenaltyN4=function(t){let r=0,n=t.data.length;for(let s=0;s{l();var i1=NN(),ON=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],BN=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Uq.getBlocksCount=function(t,r){switch(r){case i1.L:return ON[(t-1)*4+0];case i1.M:return ON[(t-1)*4+1];case i1.Q:return ON[(t-1)*4+2];case i1.H:return ON[(t-1)*4+3];default:return}};Uq.getTotalCodewordsCount=function(t,r){switch(r){case i1.L:return BN[(t-1)*4+0];case i1.M:return BN[(t-1)*4+1];case i1.Q:return BN[(t-1)*4+2];case i1.H:return BN[(t-1)*4+3];default:return}}});var BAe=_e(UN=>{l();var YE=new Uint8Array(512),kN=new Uint8Array(256);(function(){let t=1;for(let r=0;r<255;r++)YE[r]=t,kN[t]=r,t<<=1,t&256&&(t^=285);for(let r=255;r<512;r++)YE[r]=YE[r-255]})();UN.log=function(t){if(t<1)throw new Error("log("+t+")");return kN[t]};UN.exp=function(t){return YE[t]};UN.mul=function(t,r){return t===0||r===0?0:YE[kN[t]+kN[r]]}});var kAe=_e(JE=>{l();var Lq=BAe();JE.mul=function(t,r){let n=new Uint8Array(t.length+r.length-1);for(let o=0;o=0;){let o=n[0];for(let i=0;i{l();var UAe=kAe();function Mq(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Mq.prototype.initialize=function(t){this.degree=t,this.genPoly=UAe.generateECPolynomial(this.degree)};Mq.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(t.length+this.degree);r.set(t);let n=UAe.mod(r,this.genPoly),o=this.degree-n.length;if(o>0){let s=new Uint8Array(this.degree);return s.set(n,o),s}return n};DAe.exports=Mq});var Hq=_e(MAe=>{l();MAe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}});var $q=_e(Zp=>{l();var HAe="[0-9]+",lrt="[A-Z $%*+\\-./:]+",QE="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";QE=QE.replace(/u/g,"\\u");var urt="(?:(?![A-Z0-9 $%*+\\-./:]|"+QE+`)(?:.|[\r +]))+`;Zp.KANJI=new RegExp(QE,"g");Zp.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Zp.BYTE=new RegExp(urt,"g");Zp.NUMERIC=new RegExp(HAe,"g");Zp.ALPHANUMERIC=new RegExp(lrt,"g");var drt=new RegExp("^"+QE+"$"),frt=new RegExp("^"+HAe+"$"),prt=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Zp.testKanji=function(t){return drt.test(t)};Zp.testNumeric=function(t){return frt.test(t)};Zp.testAlphanumeric=function(t){return prt.test(t)}});var a1=_e(Qn=>{l();var hrt=Hq(),Fq=$q();Qn.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};Qn.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};Qn.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};Qn.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};Qn.MIXED={bit:-1};Qn.getCharCountIndicator=function(t,r){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!hrt.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?t.ccBits[0]:r<27?t.ccBits[1]:t.ccBits[2]};Qn.getBestModeForData=function(t){return Fq.testNumeric(t)?Qn.NUMERIC:Fq.testAlphanumeric(t)?Qn.ALPHANUMERIC:Fq.testKanji(t)?Qn.KANJI:Qn.BYTE};Qn.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")};Qn.isValid=function(t){return t&&t.bit&&t.ccBits};function mrt(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"numeric":return Qn.NUMERIC;case"alphanumeric":return Qn.ALPHANUMERIC;case"kanji":return Qn.KANJI;case"byte":return Qn.BYTE;default:throw new Error("Unknown mode: "+e)}}Qn.from=function(t,r){if(Qn.isValid(t))return t;try{return mrt(t)}catch{return r}}});var jAe=_e(m2=>{l();var DN=s1(),grt=Dq(),$Ae=NN(),c1=a1(),zq=Hq(),zAe=7973,FAe=DN.getBCHDigit(zAe);function yrt(e,t,r){for(let n=1;n<=40;n++)if(t<=m2.getCapacity(n,r,e))return n}function VAe(e,t){return c1.getCharCountIndicator(e,t)+4}function wrt(e,t){let r=0;return e.forEach(function(n){let o=VAe(n.mode,t);r+=o+n.getBitsLength()}),r}function brt(e,t){for(let r=1;r<=40;r++)if(wrt(e,r)<=m2.getCapacity(r,t,c1.MIXED))return r}m2.from=function(t,r){return zq.isValid(t)?parseInt(t,10):r};m2.getCapacity=function(t,r,n){if(!zq.isValid(t))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=c1.BYTE);let o=DN.getSymbolTotalCodewords(t),s=grt.getTotalCodewordsCount(t,r),i=(o-s)*8;if(n===c1.MIXED)return i;let a=i-VAe(n,t);switch(n){case c1.NUMERIC:return Math.floor(a/10*3);case c1.ALPHANUMERIC:return Math.floor(a/11*2);case c1.KANJI:return Math.floor(a/13);case c1.BYTE:default:return Math.floor(a/8)}};m2.getBestVersionForData=function(t,r){let n,o=$Ae.from(r,$Ae.M);if(Array.isArray(t)){if(t.length>1)return brt(t,o);if(t.length===0)return 1;n=t[0]}else n=t;return yrt(n.mode,n.getLength(),o)};m2.getEncodedBits=function(t){if(!zq.isValid(t)||t<7)throw new Error("Invalid QR Code version");let r=t<<12;for(;DN.getBCHDigit(r)-FAe>=0;)r^=zAe<{l();var Vq=s1(),WAe=1335,xrt=21522,qAe=Vq.getBCHDigit(WAe);KAe.getEncodedBits=function(t,r){let n=t.bit<<3|r,o=n<<10;for(;Vq.getBCHDigit(o)-qAe>=0;)o^=WAe<{l();var vrt=a1();function qx(e){this.mode=vrt.NUMERIC,this.data=e.toString()}qx.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)};qx.prototype.getLength=function(){return this.data.length};qx.prototype.getBitsLength=function(){return qx.getBitsLength(this.data.length)};qx.prototype.write=function(t){let r,n,o;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),o=parseInt(n,10),t.put(o,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),o=parseInt(n,10),t.put(o,s*3+1))};GAe.exports=qx});var QAe=_e((M$r,JAe)=>{l();var Ert=a1(),jq=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Wx(e){this.mode=Ert.ALPHANUMERIC,this.data=e}Wx.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};Wx.prototype.getLength=function(){return this.data.length};Wx.prototype.getBitsLength=function(){return Wx.getBitsLength(this.data.length)};Wx.prototype.write=function(t){let r;for(r=0;r+2<=this.data.length;r+=2){let n=jq.indexOf(this.data[r])*45;n+=jq.indexOf(this.data[r+1]),t.put(n,11)}this.data.length%2&&t.put(jq.indexOf(this.data[r]),6)};JAe.exports=Wx});var eCe=_e(($$r,XAe)=>{l();var Art=a1();function Kx(e){this.mode=Art.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}Kx.getBitsLength=function(t){return t*8};Kx.prototype.getLength=function(){return this.data.length};Kx.prototype.getBitsLength=function(){return Kx.getBitsLength(this.data.length)};Kx.prototype.write=function(e){for(let t=0,r=this.data.length;t{l();var Crt=a1(),Srt=s1();function Zx(e){this.mode=Crt.KANJI,this.data=e}Zx.getBitsLength=function(t){return t*13};Zx.prototype.getLength=function(){return this.data.length};Zx.prototype.getBitsLength=function(){return Zx.getBitsLength(this.data.length)};Zx.prototype.write=function(e){let t;for(t=0;t=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` +Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),e.put(r,13)}};tCe.exports=Zx});var uCe=_e(Gx=>{l();var gr=a1(),sCe=YAe(),iCe=QAe(),aCe=eCe(),cCe=rCe(),XE=$q(),LN=s1(),Irt=Rj();function nCe(e){return unescape(encodeURIComponent(e)).length}function eA(e,t,r){let n=[],o;for(;(o=e.exec(r))!==null;)n.push({data:o[0],index:o.index,mode:t,length:o[0].length});return n}function lCe(e){let t=eA(XE.NUMERIC,gr.NUMERIC,e),r=eA(XE.ALPHANUMERIC,gr.ALPHANUMERIC,e),n,o;return LN.isKanjiModeEnabled()?(n=eA(XE.BYTE,gr.BYTE,e),o=eA(XE.KANJI,gr.KANJI,e)):(n=eA(XE.BYTE_KANJI,gr.BYTE,e),o=[]),t.concat(r,n,o).sort(function(i,a){return i.index-a.index}).map(function(i){return{data:i.data,mode:i.mode,length:i.length}})}function qq(e,t){switch(t){case gr.NUMERIC:return sCe.getBitsLength(e);case gr.ALPHANUMERIC:return iCe.getBitsLength(e);case gr.KANJI:return cCe.getBitsLength(e);case gr.BYTE:return aCe.getBitsLength(e)}}function Trt(e){return e.reduce(function(t,r){let n=t.length-1>=0?t[t.length-1]:null;return n&&n.mode===r.mode?(t[t.length-1].data+=r.data,t):(t.push(r),t)},[])}function _rt(e){let t=[];for(let r=0;r{l();var HN=s1(),Wq=NN(),Nrt=SAe(),Rrt=TAe(),Ort=_Ae(),Brt=RAe(),Gq=OAe(),Yq=Dq(),krt=LAe(),MN=jAe(),Urt=ZAe(),Drt=a1(),Kq=uCe();function Lrt(e,t){let r=e.size,n=Brt.getPositions(t);for(let o=0;o=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?e.set(s+a,i+c,!0,!0):e.set(s+a,i+c,!1,!0))}}function Mrt(e){let t=e.size;for(let r=8;r>a&1)===1,e.set(o,s,i,!0),e.set(s,o,i,!0)}function Zq(e,t,r){let n=e.size,o=Urt.getEncodedBits(t,r),s,i;for(s=0;s<15;s++)i=(o>>s&1)===1,s<6?e.set(s,8,i,!0):s<8?e.set(s+1,8,i,!0):e.set(n-15+s,8,i,!0),s<8?e.set(8,n-s-1,i,!0):s<9?e.set(8,15-s-1+1,i,!0):e.set(8,15-s-1,i,!0);e.set(n-8,8,1,!0)}function Frt(e,t){let r=e.size,n=-1,o=r-1,s=7,i=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!e.isReserved(o,a-c)){let u=!1;i>>s&1)===1),e.set(o,a-c,u),s--,s===-1&&(i++,s=7)}if(o+=n,o<0||r<=o){o-=n,n=-n;break}}}function zrt(e,t,r){let n=new Nrt;r.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),Drt.getCharCountIndicator(c.mode,e)),c.write(n)});let o=HN.getSymbolTotalCodewords(e),s=Yq.getTotalCodewordsCount(e,t),i=(o-s)*8;for(n.getLengthInBits()+4<=i&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(i-n.getLengthInBits())/8;for(let c=0;c=7&&$rt(c,t),Frt(c,i),isNaN(n)&&(n=Gq.getBestMask(c,Zq.bind(null,c,r))),Gq.applyMask(n,c),Zq(c,r,n),{modules:c,version:t,errorCorrectionLevel:r,maskPattern:n,segments:o}}dCe.create=function(t,r){if(typeof t>"u"||t==="")throw new Error("No input text");let n=Wq.M,o,s;return typeof r<"u"&&(n=Wq.from(r.errorCorrectionLevel,Wq.M),o=MN.from(r.version),s=Gq.from(r.maskPattern),r.toSJISFunc&&HN.setToSJISFunction(r.toSJISFunc)),jrt(t,o,n,s)}});var Jq=_e(g2=>{l();function pCe(e){if(typeof e=="number"&&(e=e.toString()),typeof e!="string")throw new Error("Color should be defined as hex string");let t=e.slice().replace("#","").split("");if(t.length<3||t.length===5||t.length>8)throw new Error("Invalid hex color: "+e);(t.length===3||t.length===4)&&(t=Array.prototype.concat.apply([],t.map(function(n){return[n,n]}))),t.length===6&&t.push("F","F");let r=parseInt(t.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+t.slice(0,6).join("")}}g2.getOptions=function(t){t||(t={}),t.color||(t.color={});let r=typeof t.margin>"u"||t.margin===null||t.margin<0?4:t.margin,n=t.width&&t.width>=21?t.width:void 0,o=t.scale||4;return{width:n,scale:n?4:o,margin:r,color:{dark:pCe(t.color.dark||"#000000ff"),light:pCe(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}};g2.getScale=function(t,r){return r.width&&r.width>=t+r.margin*2?r.width/(t+r.margin*2):r.scale};g2.getImageWidth=function(t,r){let n=g2.getScale(t,r);return Math.floor((t+r.margin*2)*n)};g2.qrToImageData=function(t,r,n){let o=r.modules.size,s=r.modules.data,i=g2.getScale(o,n),a=Math.floor((o+n.margin*2)*i),c=n.margin*i,u=[n.color.light,n.color.dark];for(let d=0;d=c&&f>=c&&d{l();var Qq=Jq();function qrt(e,t,r){e.clearRect(0,0,t.width,t.height),t.style||(t.style={}),t.height=r,t.width=r,t.style.height=r+"px",t.style.width=r+"px"}function Wrt(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}$N.render=function(t,r,n){let o=n,s=r;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),r||(s=Wrt()),o=Qq.getOptions(o);let i=Qq.getImageWidth(t.modules.size,o),a=s.getContext("2d"),c=a.createImageData(i,i);return Qq.qrToImageData(c.data,t,o),qrt(a,s,i),a.putImageData(c,0,0),s};$N.renderToDataURL=function(t,r,n){let o=n;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),o||(o={});let s=$N.render(t,r,o),i=o.type||"image/png",a=o.rendererOpts||{};return s.toDataURL(i,a.quality)}});var yCe=_e(gCe=>{l();var Krt=Jq();function mCe(e,t){let r=e.a/255,n=t+'="'+e.hex+'"';return r<1?n+" "+t+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function Xq(e,t,r){let n=e+t;return typeof r<"u"&&(n+=" "+r),n}function Zrt(e,t,r){let n="",o=0,s=!1,i=0;for(let a=0;a0&&c>0&&e[a-1]||(n+=s?Xq("M",c+r,.5+u+r):Xq("m",o,0),o=0,s=!1),c+1':"",u="',d='viewBox="0 0 '+a+" "+a+'"',p=''+c+u+` +`;return typeof n=="function"&&n(null,p),p}});var bCe=_e(tA=>{l();var Grt=EAe(),eW=fCe(),wCe=hCe(),Yrt=yCe();function tW(e,t,r,n,o){let s=[].slice.call(arguments,1),i=s.length,a=typeof s[i-1]=="function";if(!a&&!Grt())throw new Error("Callback required as last argument");if(a){if(i<2)throw new Error("Too few arguments provided");i===2?(o=r,r=t,t=n=void 0):i===3&&(t.getContext&&typeof o>"u"?(o=n,n=void 0):(o=n,n=r,r=t,t=void 0))}else{if(i<1)throw new Error("Too few arguments provided");return i===1?(r=t,t=n=void 0):i===2&&!t.getContext&&(n=r,r=t,t=void 0),new Promise(function(c,u){try{let d=eW.create(r,n);c(e(d,t,n))}catch(d){u(d)}})}try{let c=eW.create(r,n);o(null,e(c,t,n))}catch(c){o(c)}}tA.create=eW.create;tA.toCanvas=tW.bind(null,wCe.render);tA.toDataURL=tW.bind(null,wCe.renderToDataURL);tA.toString=tW.bind(null,function(e,t,r){return Yrt.render(e,r)})});l();l();var yAe=Ht(ks(),1);l();jN();var mf=Ht(jd(),1),Dc=Ht(C2(),1),eQ=Ht(JN(),1);l();l();var hA=BigInt(4294967295),LW=BigInt(32);function QN(e,t=!1){return t?{h:Number(e&hA),l:Number(e>>LW&hA)}:{h:Number(e>>LW&hA)|0,l:Number(e&hA)|0}}function mA(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;se>>>r,eR=(e,t,r)=>e<<32-r|t>>>r,Nl=(e,t,r)=>e>>>r|t<<32-r,Rl=(e,t,r)=>e<<32-r|t>>>r,u1=(e,t,r)=>e<<64-r|t>>>r-32,d1=(e,t,r)=>e>>>r-32|t<<64-r,MW=(e,t)=>t,HW=(e,t)=>e,$W=(e,t,r)=>e<>>32-r,FW=(e,t,r)=>t<>>32-r,zW=(e,t,r)=>t<>>64-r,VW=(e,t,r)=>e<>>64-r;function ra(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Xx=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),e8=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,jW=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),qW=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,WW=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),KW=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;l();l();var f1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Wd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Jo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Cn(e,...t){if(!Wd(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function p1(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Jo(e.outputLen),Jo(e.blockLen)}function Fa(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function S2(e,t){Cn(e);let r=t.outputLen;if(e.length>>t}var YW=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function JW(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var Bl=YW?e=>e:e=>JW(e);function OSe(e){for(let t=0;te:OSe,QW=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",BSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function za(e){if(Cn(e),QW)return e.toHex();let t="";for(let r=0;r=qd._0&&e<=qd._9)return e-qd._0;if(e>=qd.A&&e<=qd.F)return e-(qd.A-10);if(e>=qd.a&&e<=qd.f)return e-(qd.a-10)}function m1(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(QW)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oe().update(Qo(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function XW(e){let t=(n,o)=>e(o).update(Qo(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Us(e=32){if(f1&&typeof f1.getRandomValues=="function")return f1.getRandomValues(new Uint8Array(e));if(f1&&typeof f1.randomBytes=="function")return Uint8Array.from(f1.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var kSe=BigInt(0),t8=BigInt(1),USe=BigInt(2),DSe=BigInt(7),LSe=BigInt(256),MSe=BigInt(113),rK=[],nK=[],oK=[];for(let e=0,t=t8,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],rK.push(2*(5*n+r)),nK.push((e+1)*(e+2)/2%64);let o=kSe;for(let s=0;s<7;s++)t=(t<>DSe)*MSe)%LSe,t&USe&&(o^=t8<<(t8<r>32?zW(e,t,r):$W(e,t,r),tK=(e,t,r)=>r>32?VW(e,t,r):FW(e,t,r);function FSe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=eK(u,d,1)^r[a],p=tK(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=nK[i],c=eK(o,s,a),u=tK(o,s,a),d=rK[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=HSe[n],e[1]^=$Se[n]}fo(r)}var rR=class e extends Ol{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Jo(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Jo(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(S2(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,fo(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},zSe=(e,t,r)=>g1(()=>new rR(t,e,r));var yA=zSe(1,136,256/8);l();l();l();l();var iK="0.1.1";function aK(){return iK}var nr=class e extends Error{constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=`https://oxlib.sh${o??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0]:[]].filter(c=>typeof c=="string").join(` +`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${aK()}`}),this.cause=r.cause,this.details=n,this.docs=i,this.docsPath=o,this.shortMessage=t}walk(t){return cK(this,t)}};function cK(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?cK(e.cause,t):t?null:e}l();l();function VSe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function lK(e,t,r){return e&t^~e&r}function uK(e,t,r){return e&t^e&r^t&r}var r8=class extends Ol{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=gA(this.buffer)}update(t){Fa(this),t=Qo(t),Cn(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>>3,w=Rc(h,17)^Rc(h,19)^h>>>10;Gp[f]=w+Gp[f-7]+y+Gp[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=Rc(a,6)^Rc(a,11)^Rc(a,25),h=d+p+lK(a,c,u)+jSe[f]+Gp[f]|0,w=(Rc(n,2)^Rc(n,13)^Rc(n,22))+uK(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){fo(Gp)}destroy(){this.set(0,0,0,0,0,0,0,0),fo(this.buffer)}};var dK=mA(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),qSe=dK[0],WSe=dK[1],Yp=new Uint32Array(80),Jp=new Uint32Array(80),n8=class extends r8{constructor(t=64){super(128,t,16,!1),this.Ah=Do[0]|0,this.Al=Do[1]|0,this.Bh=Do[2]|0,this.Bl=Do[3]|0,this.Ch=Do[4]|0,this.Cl=Do[5]|0,this.Dh=Do[6]|0,this.Dl=Do[7]|0,this.Eh=Do[8]|0,this.El=Do[9]|0,this.Fh=Do[10]|0,this.Fl=Do[11]|0,this.Gh=Do[12]|0,this.Gl=Do[13]|0,this.Hh=Do[14]|0,this.Hl=Do[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)Yp[E]=t.getUint32(r),Jp[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Yp[E-15]|0,_=Jp[E-15]|0,O=Nl(S,_,1)^Nl(S,_,8)^XN(S,_,7),D=Rl(S,_,1)^Rl(S,_,8)^eR(S,_,7),M=Yp[E-2]|0,N=Jp[E-2]|0,L=Nl(M,N,19)^u1(M,N,61)^XN(M,N,6),P=Rl(M,N,19)^d1(M,N,61)^eR(M,N,6),R=jW(D,P,Jp[E-7],Jp[E-16]),I=qW(R,O,L,Yp[E-7],Yp[E-16]);Yp[E]=I|0,Jp[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Nl(f,p,14)^Nl(f,p,18)^u1(f,p,41),_=Rl(f,p,14)^Rl(f,p,18)^d1(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=WW(T,_,D,WSe[E],Jp[E]),N=KW(M,v,S,O,qSe[E],Yp[E]),L=M|0,P=Nl(n,o,28)^u1(n,o,34)^u1(n,o,39),R=Rl(n,o,28)^d1(n,o,34)^d1(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=ra(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Xx(L,R,B);n=e8(C,N,P,I),o=C|0}({h:n,l:o}=ra(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ra(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ra(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=ra(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=ra(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=ra(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=ra(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=ra(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){fo(Yp,Jp)}destroy(){fo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},nR=class extends n8{constructor(){super(48),this.Ah=Uo[0]|0,this.Al=Uo[1]|0,this.Bh=Uo[2]|0,this.Bl=Uo[3]|0,this.Ch=Uo[4]|0,this.Cl=Uo[5]|0,this.Dh=Uo[6]|0,this.Dl=Uo[7]|0,this.Eh=Uo[8]|0,this.El=Uo[9]|0,this.Fh=Uo[10]|0,this.Fl=Uo[11]|0,this.Gh=Uo[12]|0,this.Gl=Uo[13]|0,this.Hh=Uo[14]|0,this.Hl=Uo[15]|0}};var Xo=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);var oR=class extends n8{constructor(){super(32),this.Ah=Xo[0]|0,this.Al=Xo[1]|0,this.Bh=Xo[2]|0,this.Bl=Xo[3]|0,this.Ch=Xo[4]|0,this.Cl=Xo[5]|0,this.Dh=Xo[6]|0,this.Dl=Xo[7]|0,this.Eh=Xo[8]|0,this.El=Xo[9]|0,this.Fh=Xo[10]|0,this.Fl=Xo[11]|0,this.Gh=Xo[12]|0,this.Gl=Xo[13]|0,this.Hh=Xo[14]|0,this.Hl=Xo[15]|0}},Zd=g1(()=>new wA);var bA=g1(()=>new n8),fK=g1(()=>new nR),pK=g1(()=>new oR);var o8=Zd;l();l();var cR=BigInt(0),aR=BigInt(1);function T2(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function lR(e){if(!T2(e))throw new Error("Uint8Array expected")}function _2(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function s8(e){let t=e.toString(16);return t.length&1?"0"+t:t}function gK(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?cR:BigInt("0x"+e)}var yK=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",KSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function P2(e){if(lR(e),yK)return e.toHex();let t="";for(let r=0;r=Gd._0&&e<=Gd._9)return e-Gd._0;if(e>=Gd.A&&e<=Gd.F)return e-(Gd.A-10);if(e>=Gd.a&&e<=Gd.f)return e-(Gd.a-10)}function i8(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(yK)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;otypeof e=="bigint"&&cR<=e;function xA(e,t,r){return sR(e)&&sR(t)&&sR(r)&&t<=e&&ecR;e>>=aR,t+=1);return t}var b1=e=>(aR<new Uint8Array(e),mK=e=>Uint8Array.from(e);function bK(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=iR(e),o=iR(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=iR(0))=>{o=a(mK([0]),f),n=a(),f.length!==0&&(o=a(mK([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}var ZSe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||T2(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function x1(e,t,r={}){let n=(o,s,i)=>{let a=ZSe[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function fR(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}l();l();function xK(e,t){if(pR(e)>t)throw new vA({givenSize:pR(e),maxSize:t})}var Jd={zero:48,nine:57,A:65,F:70,a:97,f:102};function hR(e){if(e>=Jd.zero&&e<=Jd.nine)return e-Jd.zero;if(e>=Jd.A&&e<=Jd.F)return e-(Jd.A-10);if(e>=Jd.a&&e<=Jd.f)return e-(Jd.a-10)}function vK(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new EA({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;st)throw new CA({givenSize:Va(e),maxSize:t})}function EK(e,t){if(typeof t=="number"&&t>0&&t>Va(e)-1)throw new c8({offset:t,position:"start",size:Va(e)})}function AK(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Va(e)!==r-t)throw new c8({offset:r,position:"end",size:Va(e)})}function mR(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new SA({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function CK(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;stypeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+YSe:o,r)}var JSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function QSe(e,t={}){let{strict:r=!1}=t;if(!e)throw new IA(e);if(typeof e!="string")throw new IA(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new TA(e);if(!e.startsWith("0x"))throw new TA(e)}function _A(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Ul(e){return e instanceof Uint8Array?na(e):Array.isArray(e)?na(new Uint8Array(e)):e}function na(e,t={}){let r="";for(let o=0;os||othis.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}};var oIe={checksum:new PA(8192)},NA=oIe.checksum;l();function NK(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new RA({prefix:n,cause:new AR});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new RA({prefix:n,cause:new ER});return}throw new vR({publicKey:e})}function SR(e){let t=(()=>{if(bR(e))return RK(e);if(TK(e))return sIe(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return NK(t),t}function sIe(e){return RK(na(e))}function RK(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new CR({publicKey:e});if(e.length===130){let n=BigInt(Oc(e,0,32)),o=BigInt(Oc(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(Oc(e,0,1)),o=BigInt(Oc(e,1,33)),s=BigInt(Oc(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(Oc(e,0,1)),r=BigInt(Oc(e,1,33));return{prefix:t,x:r}}function OK(e,t={}){return u8(d8(e,t))}function d8(e,t={}){NK(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return _A(s?oa(r,{size:1}):"0x",oa(n,{size:32}),typeof o=="bigint"?oa(o,{size:32}):"0x")}var vR=class extends nr{constructor({publicKey:t}){super(`Value \`${Qp(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},RA=class extends nr{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},ER=class extends nr{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},AR=class extends nr{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},CR=class extends nr{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Va(Ul(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};var iIe=/^0x[a-fA-F0-9]{40}$/;function OA(e,t={}){let{strict:r=!0}=t;if(!iIe.test(e))throw new BA({address:e,cause:new TR});if(r){if(e.toLowerCase()===e)return;if(BK(e)!==e)throw new BA({address:e,cause:new _R})}}function BK(e){if(NA.has(e))return NA.get(e);OA(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=xR(IK(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return NA.set(e,o),o}function aIe(e,t={}){let{checksum:r=!1}=t;return OA(e),r?BK(e):e}function kK(e,t={}){let r=xR(`0x${d8(e).slice(4)}`).substring(26);return aIe(`0x${r}`,t)}function UK(e,t){return OA(e,{strict:!1}),OA(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}var BA=class extends nr{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},TR=class extends nr{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},_R=class extends nr{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}};l();var Tot=2n**(8n-1n)-1n,_ot=2n**(16n-1n)-1n,Pot=2n**(24n-1n)-1n,Not=2n**(32n-1n)-1n,Rot=2n**(40n-1n)-1n,Oot=2n**(48n-1n)-1n,Bot=2n**(56n-1n)-1n,kot=2n**(64n-1n)-1n,Uot=2n**(72n-1n)-1n,Dot=2n**(80n-1n)-1n,Lot=2n**(88n-1n)-1n,Mot=2n**(96n-1n)-1n,Hot=2n**(104n-1n)-1n,$ot=2n**(112n-1n)-1n,Fot=2n**(120n-1n)-1n,zot=2n**(128n-1n)-1n,Vot=2n**(136n-1n)-1n,jot=2n**(144n-1n)-1n,qot=2n**(152n-1n)-1n,Wot=2n**(160n-1n)-1n,Kot=2n**(168n-1n)-1n,Zot=2n**(176n-1n)-1n,Got=2n**(184n-1n)-1n,Yot=2n**(192n-1n)-1n,Jot=2n**(200n-1n)-1n,Qot=2n**(208n-1n)-1n,Xot=2n**(216n-1n)-1n,est=2n**(224n-1n)-1n,tst=2n**(232n-1n)-1n,rst=2n**(240n-1n)-1n,nst=2n**(248n-1n)-1n,ost=2n**(256n-1n)-1n,sst=-(2n**(8n-1n)),ist=-(2n**(16n-1n)),ast=-(2n**(24n-1n)),cst=-(2n**(32n-1n)),lst=-(2n**(40n-1n)),ust=-(2n**(48n-1n)),dst=-(2n**(56n-1n)),fst=-(2n**(64n-1n)),pst=-(2n**(72n-1n)),hst=-(2n**(80n-1n)),mst=-(2n**(88n-1n)),gst=-(2n**(96n-1n)),yst=-(2n**(104n-1n)),wst=-(2n**(112n-1n)),bst=-(2n**(120n-1n)),xst=-(2n**(128n-1n)),vst=-(2n**(136n-1n)),Est=-(2n**(144n-1n)),Ast=-(2n**(152n-1n)),Cst=-(2n**(160n-1n)),Sst=-(2n**(168n-1n)),Ist=-(2n**(176n-1n)),Tst=-(2n**(184n-1n)),_st=-(2n**(192n-1n)),Pst=-(2n**(200n-1n)),Nst=-(2n**(208n-1n)),Rst=-(2n**(216n-1n)),Ost=-(2n**(224n-1n)),Bst=-(2n**(232n-1n)),kst=-(2n**(240n-1n)),Ust=-(2n**(248n-1n)),Dst=-(2n**(256n-1n)),Lst=2n**8n-1n,Mst=2n**16n-1n,Hst=2n**24n-1n,$st=2n**32n-1n,Fst=2n**40n-1n,zst=2n**48n-1n,Vst=2n**56n-1n,jst=2n**64n-1n,qst=2n**72n-1n,Wst=2n**80n-1n,Kst=2n**88n-1n,Zst=2n**96n-1n,Gst=2n**104n-1n,Yst=2n**112n-1n,Jst=2n**120n-1n,Qst=2n**128n-1n,Xst=2n**136n-1n,eit=2n**144n-1n,tit=2n**152n-1n,rit=2n**160n-1n,nit=2n**168n-1n,oit=2n**176n-1n,sit=2n**184n-1n,iit=2n**192n-1n,ait=2n**200n-1n,cit=2n**208n-1n,lit=2n**216n-1n,uit=2n**224n-1n,dit=2n**232n-1n,fit=2n**240n-1n,pit=2n**248n-1n,PR=2n**256n-1n;var zA={};Te(zA,{InvalidRError:()=>LA,InvalidSError:()=>MA,InvalidSerializedSizeError:()=>DA,InvalidVError:()=>HA,InvalidYParityError:()=>C1,MissingPropertiesError:()=>O2,assert:()=>$A,extract:()=>CIe,from:()=>WR,fromBytes:()=>nZ,fromDerBytes:()=>SIe,fromDerHex:()=>oZ,fromHex:()=>qR,fromLegacy:()=>sZ,fromRpc:()=>iZ,fromTuple:()=>IIe,toBytes:()=>TIe,toDerBytes:()=>_Ie,toDerHex:()=>PIe,toHex:()=>aZ,toLegacy:()=>NIe,toRpc:()=>RIe,toTuple:()=>OIe,vToYParity:()=>FA,validate:()=>BIe,yParityToV:()=>KR});l();l();l();l();var kA=class extends Ol{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,p1(t);let n=Qo(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew kA(e,t).update(r).digest();Xp.create=(e,t)=>new kA(e,t);l();l();l();var Ds=BigInt(0),ts=BigInt(1),A1=BigInt(2),cIe=BigInt(3),HK=BigInt(4),$K=BigInt(5),FK=BigInt(8);function es(e,t){let r=e%t;return r>=Ds?r:t+r}function sa(e,t,r){let n=e;for(;t-- >Ds;)n*=n,n%=r;return n}function UA(e,t){if(e===Ds)throw new Error("invert: expected non-zero number");if(t<=Ds)throw new Error("invert: expected positive modulus, got "+t);let r=es(e,t),n=t,o=Ds,s=ts,i=ts,a=Ds;for(;r!==Ds;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ts)throw new Error("invert: does not exist");return es(o,t)}function zK(e,t){let r=(e.ORDER+ts)/HK,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function lIe(e,t){let r=(e.ORDER-$K)/FK,n=e.mul(t,A1),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,A1),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function uIe(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return zK;let s=o.pow(n,t),i=(t+ts)/A1;return function(c,u){if(c.is0(u))return u;if(MK(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ts<(n[o]="function",n),t);return x1(e,r)}function pIe(e,t,r){if(rDs;)r&ts&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ts;return n}function RR(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function MK(e,t){let r=(e.ORDER-ts)/A1,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function OR(e,t){t!==void 0&&Jo(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function f8(e,t,r=!1,n={}){if(e<=Ds)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=OR(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:b1(o),ZERO:Ds,ONE:ts,create:c=>es(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ds<=c&&cc===Ds,isOdd:c=>(c&ts)===ts,neg:c=>es(-c,e),eql:(c,u)=>c===u,sqr:c=>es(c*c,e),add:(c,u)=>es(c+u,e),sub:(c,u)=>es(c-u,e),mul:(c,u)=>es(c*u,e),pow:(c,u)=>pIe(a,c,u),div:(c,u)=>es(c*UA(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>UA(c,e),sqrt:n.sqrt||(c=>(i||(i=dIe(e)),i(a,c))),toBytes:c=>r?dR(c,s):y1(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?uR(c):Yd(c)},invertBatch:c=>RR(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function VK(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function BR(e){let t=VK(e);return t+Math.ceil(t/2)}function jK(e,t,r=!1){let n=e.length,o=VK(t),s=BR(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?uR(e):Yd(e),a=es(i,t-ts)+ts;return r?dR(a,o):y1(a,o)}var qK=BigInt(0),MR=BigInt(1);function kR(e,t){let r=t.negate();return e?r:t}function KK(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function UR(e,t){KK(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=b1(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function WK(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=MR);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function hIe(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function mIe(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var DR=new WeakMap,ZK=new WeakMap;function LR(e){return ZK.get(e)||1}function GK(e,t){return{constTimeNegate:kR,hasPrecomputes(r){return LR(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>qK;)n&MR&&(o=o.add(s)),s=s.double(),n>>=MR;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=UR(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=b1(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{let{Err:r}=Qd;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=s8(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?s8(o.length/2|128):"";return s8(e)+s+o+t},decode(e,t){let{Err:r}=Qd,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Qd;if(e{let O=S.toAffine();return a8(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,FR),yIe),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return xA(E,po,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(T2(E)&&(E=P2(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:Yd(mi("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=es(M,D)),w1("private key",M,po,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=fR((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=fR(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=RR(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(mi("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return YK(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,FR),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,FR),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;w1("scalar",S,Xd,O);let D=w.ZERO;if(S===Xd)return D;if(this.is0()||S===po)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>Xd||P>Xd;)N&po&&(R=R.add(B)),P&po&&(I=I.add(B)),B=B.double(),N>>=po,P>>=po;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;w1("scalar",S,po,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===Xd||P===po||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===po)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===po?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return _2("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return _2("isCompressed",S),P2(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=GK(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function bIe(e){let t=HR(e);return x1(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function QK(e){let t=bIe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return es(C,n)}function u(C){return UA(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=wIe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=a8;return _2("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=Yd(H);if(!xA(k,po,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&po)===po;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>po;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>Yd(C.slice(A,U));class v{constructor(A,U,H){w1("r",A,po,n),w1("s",U,po,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=mi("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=Qd.toSig(mi("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(mi("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+$R(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return i8(this.toDERHex())}toDERHex(){return Qd.hexFromSig(this)}toCompactRawBytes(){return i8(this.toCompactHex())}toCompactHex(){let A=o;return $R(this.r,A)+$R(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=BR(t.n);return jK(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=mi("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=Yd(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=b1(s);function N(C){return w1("num < 2^"+s,C,Xd,M),y1(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=mi("msgHash",C),JK(U),j&&(C=mi("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(mi("extraEntropy",ye))}let pe=a8(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===Xd)return;let ur=c(Et*c(me+At*te));if(ur===Xd)return;let _r=(kt.x===At?0:2)|Number(kt.y&po),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return bK(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=mi("msgHash",A),U=mi("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(JK(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||T2(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof Qd.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}function xIe(e){return{hash:e,hmac:(t,...r)=>Xp(e,t,ko(...r)),randomBytes:Us}}function XK(e,t){let r=n=>QK({...e,...xIe(n)});return{...r(t),create:r}}var rZ=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),eZ=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),vIe=BigInt(0),EIe=BigInt(1),VR=BigInt(2),tZ=(e,t)=>(e+t/VR)/t;function AIe(e){let t=rZ,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=sa(d,r,t)*d%t,p=sa(f,r,t)*d%t,h=sa(p,VR,t)*u%t,y=sa(h,o,t)*h%t,w=sa(y,s,t)*y%t,x=sa(w,a,t)*w%t,v=sa(x,c,t)*x%t,T=sa(v,a,t)*w%t,E=sa(T,r,t)*d%t,S=sa(E,i,t)*y%t,_=sa(S,n,t)*u%t,O=sa(_,VR,t);if(!jR.eql(jR.sqr(O),e))throw new Error("Cannot find square root");return O}var jR=f8(rZ,void 0,void 0,{sqrt:AIe}),ia=XK({a:vIe,b:BigInt(7),Fp:jR,n:eZ,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=eZ,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-EIe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=tZ(s*e,t),c=tZ(-n*e,t),u=es(e-a*r-c*o,t),d=es(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},Zd);function $A(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new O2({signature:e});if(typeof e.s>"u")throw new O2({signature:e});if(r&&typeof e.yParity>"u")throw new O2({signature:e});if(e.r<0n||e.r>PR)throw new LA({value:e.r});if(e.s<0n||e.s>PR)throw new MA({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new C1({value:e.yParity})}function nZ(e){return qR(na(e))}function qR(e){if(e.length!==130&&e.length!==132)throw new DA({signature:e});let t=BigInt(Oc(e,0,32)),r=BigInt(Oc(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return FA(o)}catch{throw new C1({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function CIe(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return WR(e)}function WR(e){let t=typeof e=="string"?qR(e):e instanceof Uint8Array?nZ(e):typeof e.r=="string"?iZ(e):e.v?sZ(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return $A(t),t}function SIe(e){return oZ(na(e))}function oZ(e){let{r:t,s:r}=ia.Signature.fromDER(Ul(e).slice(2));return{r:t,s:r}}function sZ(e){return{r:e.r,s:e.s,yParity:FA(e.v)}}function iZ(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=FA(r)),typeof n!="number")throw new C1({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function IIe(e){let[t,r,n]=e;return WR({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function TIe(e){return u8(aZ(e))}function aZ(e){$A(e);let t=e.r,r=e.s;return _A(oa(t,{size:32}),oa(r,{size:32}),typeof e.yParity=="number"?oa(KR(e.yParity),{size:1}):"0x")}function _Ie(e){return new ia.Signature(e.r,e.s).toDERRawBytes()}function PIe(e){return`0x${new ia.Signature(e.r,e.s).toDERHex()}`}function NIe(e){return{r:e.r,s:e.s,v:KR(e.yParity)}}function RIe(e){let{r:t,s:r,yParity:n}=e;return{r:oa(t,{size:32}),s:oa(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function OIe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":wR(oa(t)),r===0n?"0x":wR(oa(r))]}function BIe(e,t={}){try{return $A(e,t),!0}catch{return!1}}function FA(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new HA({value:e})}function KR(e){if(e===0)return 27;if(e===1)return 28;throw new C1({value:e})}var DA=class extends nr{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Va(Ul(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},O2=class extends nr{constructor({signature:t}){super(`Signature \`${Qp(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},LA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},MA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},C1=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},HA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}};l();l();var cZ=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]);var Xn=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Be=new Uint32Array(32);function eh(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=Be[2*e],u=Be[2*e+1],d=Be[2*t],f=Be[2*t+1],p=Be[2*r],h=Be[2*r+1],y=Be[2*n],w=Be[2*n+1],x=Xx(c,d,i);u=e8(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:MW(w,y),Dl:HW(w,y)},{h,l:p}=ra(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:Nl(f,d,24),Bl:Rl(f,d,24)},Be[2*e]=c,Be[2*e+1]=u,Be[2*t]=d,Be[2*t+1]=f,Be[2*r]=p,Be[2*r+1]=h,Be[2*n]=y,Be[2*n+1]=w}function th(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=Be[2*e],u=Be[2*e+1],d=Be[2*t],f=Be[2*t+1],p=Be[2*r],h=Be[2*r+1],y=Be[2*n],w=Be[2*n+1],x=Xx(c,d,i);u=e8(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:Nl(w,y,16),Dl:Rl(w,y,16)},{h,l:p}=ra(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:u1(f,d,63),Bl:d1(f,d,63)},Be[2*e]=c,Be[2*e+1]=u,Be[2*t]=d,Be[2*t+1]=f,Be[2*r]=p,Be[2*r+1]=h,Be[2*n]=y,Be[2*n+1]=w}function kIe(e,t={},r,n,o){if(Jo(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");let{key:s,salt:i,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(i!==void 0&&i.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==o)throw new Error("personalization must be undefined or "+o)}var ZR=class extends Ol{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Jo(t),Jo(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=h1(this.buffer)}update(t){Fa(this),t=Qo(t),Cn(t);let{blockLen:r,buffer:n,buffer32:o}=this,s=t.length,i=t.byteOffset,a=t.buffer;for(let c=0;co[i]=Bl(s))}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){let{buffer:r,length:n,finished:o,destroyed:s,outputLen:i,pos:a}=this;return t||(t=new this.constructor({dkLen:i})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=o,t.length=n,t.pos=a,t.outputLen=i,t}clone(){return this._cloneInto()}},GR=class extends ZR{constructor(t={}){let r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=Xn[0]|0,this.v0h=Xn[1]|0,this.v1l=Xn[2]|0,this.v1h=Xn[3]|0,this.v2l=Xn[4]|0,this.v2h=Xn[5]|0,this.v3l=Xn[6]|0,this.v3h=Xn[7]|0,this.v4l=Xn[8]|0,this.v4h=Xn[9]|0,this.v5l=Xn[10]|0,this.v5h=Xn[11]|0,this.v6l=Xn[12]|0,this.v6h=Xn[13]|0,this.v7l=Xn[14]|0,this.v7h=Xn[15]|0,kIe(r,t,64,16,16);let{key:n,personalization:o,salt:s}=t,i=0;if(n!==void 0&&(n=Qo(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){s=Qo(s);let a=h1(s);this.v4l^=Bl(a[0]),this.v4h^=Bl(a[1]),this.v5l^=Bl(a[2]),this.v5h^=Bl(a[3])}if(o!==void 0){o=Qo(o);let a=h1(o);this.v6l^=Bl(a[0]),this.v6h^=Bl(a[1]),this.v7l^=Bl(a[2]),this.v7h^=Bl(a[3])}if(n!==void 0){let a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:u,v4h:d,v5l:f,v5h:p,v6l:h,v6h:y,v7l:w,v7h:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=d|0,this.v5l=f|0,this.v5h=p|0,this.v6l=h|0,this.v6h=y|0,this.v7l=w|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>Be[u]=c),Be.set(Xn,16);let{h:o,l:s}=QN(BigInt(this.length));Be[24]=Xn[8]^s,Be[25]=Xn[9]^o,n&&(Be[28]=~Be[28],Be[29]=~Be[29]);let i=0,a=cZ;for(let c=0;c<12;c++)eh(0,4,8,12,t,r+2*a[i++]),th(0,4,8,12,t,r+2*a[i++]),eh(1,5,9,13,t,r+2*a[i++]),th(1,5,9,13,t,r+2*a[i++]),eh(2,6,10,14,t,r+2*a[i++]),th(2,6,10,14,t,r+2*a[i++]),eh(3,7,11,15,t,r+2*a[i++]),th(3,7,11,15,t,r+2*a[i++]),eh(0,5,10,15,t,r+2*a[i++]),th(0,5,10,15,t,r+2*a[i++]),eh(1,6,11,12,t,r+2*a[i++]),th(1,6,11,12,t,r+2*a[i++]),eh(2,7,8,13,t,r+2*a[i++]),th(2,7,8,13,t,r+2*a[i++]),eh(3,4,9,14,t,r+2*a[i++]),th(3,4,9,14,t,r+2*a[i++]);this.v0l^=Be[0]^Be[16],this.v0h^=Be[1]^Be[17],this.v1l^=Be[2]^Be[18],this.v1h^=Be[3]^Be[19],this.v2l^=Be[4]^Be[20],this.v2h^=Be[5]^Be[21],this.v3l^=Be[6]^Be[22],this.v3h^=Be[7]^Be[23],this.v4l^=Be[8]^Be[24],this.v4h^=Be[9]^Be[25],this.v5l^=Be[10]^Be[26],this.v5h^=Be[11]^Be[27],this.v6l^=Be[12]^Be[28],this.v6h^=Be[13]^Be[29],this.v7l^=Be[14]^Be[30],this.v7h^=Be[15]^Be[31],fo(Be)}destroy(){this.destroyed=!0,fo(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},lZ=XW(e=>new GR(e));var ZA={};Te(ZA,{createKeyPair:()=>KIe,getPublicKey:()=>CZ,getSharedSecret:()=>ZIe,noble:()=>WIe,randomPrivateKey:()=>SZ,recoverAddress:()=>IZ,recoverPublicKey:()=>TZ,sign:()=>GIe,verify:()=>YIe});l();l();var AZ=!1;var WIe=ia;function KIe(e={}){let{as:t="Hex"}=e,r=SZ({as:t}),n=CZ({privateKey:r});return{privateKey:r,publicKey:n}}function CZ(e){let{privateKey:t}=e,r=ia.ProjectivePoint.fromPrivateKey(Ul(t).slice(2));return SR(r)}function ZIe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,i=ia.ProjectivePoint.fromHex(d8(n).slice(2)).multiply(ia.utils.normPrivateKeyToScalar(Ul(r).slice(2))).toRawBytes(!0);return t==="Hex"?na(i):i}function SZ(e={}){let{as:t="Hex"}=e,r=ia.utils.randomPrivateKey();return t==="Hex"?na(r):r}function IZ(e){return kK(TZ(e))}function TZ(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new ia.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Ul(t).substring(2));return SR(a)}function GIe(e){let{extraEntropy:t=AZ,hash:r,payload:n,privateKey:o}=e,{r:s,s:i,recovery:a}=ia.sign(R2(n),R2(o),{extraEntropy:typeof t=="boolean"?t:Ul(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function YIe(e){let{address:t,hash:r,payload:n,publicKey:o,signature:s}=e;return t?UK(t,IZ({payload:n,signature:s})):ia.verify(s,R2(n),OK(o),...r?[{prehash:!0,lowS:!0}]:[])}l();l();l();l();function HZ(e){let t=e.length,r=0,n=0;for(;n=55296&&o<=56319&&n>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}var o9e=new TextEncoder,s9e=50;function i9e(e,t,r){o9e.encodeInto(e,t.subarray(r))}function $Z(e,t,r){e.length>s9e?i9e(e,t,r):n9e(e,t,r)}var a9e=4096;function rO(e,t,r){let n=t,o=n+r,s=[],i="";for(;n65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=a9e&&(i+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(i+=String.fromCharCode(...s)),i}var c9e=new TextDecoder,l9e=200;function u9e(e,t,r){let n=e.subarray(t,t+r);return c9e.decode(n)}function FZ(e,t,r){return r>l9e?u9e(e,t,r):rO(e,t,r)}l();l();var S1=class{type;data;constructor(t,r){this.type=t,this.data=r}};l();l();var gi=class e extends Error{constructor(t){super(t);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};l();function zZ(e,t,r){let n=r/4294967296,o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function tC(e,t,r){let n=Math.floor(r/4294967296),o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function rC(e,t){let r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function VZ(e,t){let r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}var d9e=-1,f9e=4294967296-1,p9e=17179869184-1;function h9e({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=p9e)if(t===0&&e<=f9e){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|r&3),s.setUint32(4,n),o}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),tC(n,4,e),r}}function m9e(e){let t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,o=Math.floor(n/1e9);return{sec:r+o,nsec:n-o*1e9}}function g9e(e){if(e instanceof Date){let t=m9e(e);return h9e(t)}else return null}function y9e(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let r=t.getUint32(0),n=t.getUint32(4),o=(r&3)*4294967296+n,s=r>>>2;return{sec:o,nsec:s}}case 12:{let r=rC(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new gi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function w9e(e){let t=y9e(e);return new Date(t.sec*1e3+t.nsec/1e6)}var jZ={type:d9e,encode:g9e,decode:w9e};var k2=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(jZ)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{let o=-1-t;this.builtInEncoders[o]=r,this.builtInDecoders[o]=n}}tryToEncode(t,r){for(let n=0;nthis.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){let r=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let n=HZ(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),$Z(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){let n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let n=m8(t);this.writeU8a(n)}encodeArray(t,r){let n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let o of t)this.doEncode(o,r+1)}countWithoutUndefined(t,r){let n=0;for(let o of r)t[o]!==void 0&&n++;return n}encodeMap(t,r){let n=Object.keys(t);this.sortKeys&&n.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of n){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){let n=t.data(this.pos+6),o=n.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(n);return}let r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),zZ(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),tC(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}};function nO(e,t){return new nC(t).encodeSharedRef(e)}l();l();l();function oC(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}l();var E9e=16,A9e=16,sC=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=E9e,r=A9e){this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n0&&t<=this.maxKeyLength}find(t,r,n){let o=this.caches[n-1];e:for(let s of o){let i=s.bytes;for(let a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)}decode(t,r,n){let o=this.find(t,r,n);if(o!=null)return this.hit++,o;this.miss++;let s=rO(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,s),s}};var oO="array",w8="map_key",WZ="map_value",C9e=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new gi("The type of key must be string or number but "+typeof e)},sO=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let r=this.getUninitializedStateFromPool();r.type=oO,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){let r=this.getUninitializedStateFromPool();r.type=w8,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===oO){let n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===w8||t.type===WZ){let n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},y8=-1,iO=new DataView(new ArrayBuffer(0)),S9e=new Uint8Array(iO.buffer);try{iO.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var qZ=new RangeError("Insufficient data"),I9e=new sC,iC=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=iO;bytes=S9e;headByte=y8;stack=new sO;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??k2.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??4294967295,this.maxBinLength=t?.maxBinLength??4294967295,this.maxArrayLength=t?.maxArrayLength??4294967295,this.maxMapLength=t?.maxMapLength??4294967295,this.maxExtLength=t?.maxExtLength??4294967295,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:I9e,this.mapKeyConverter=t?.mapKeyConverter??C9e}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=y8,this.stack.reset()}setBuffer(t){let r=m8(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===y8&&!this.hasRemaining(1))this.setBuffer(t);else{let r=this.bytes.subarray(this.pos),n=m8(t),o=new Uint8Array(r.length+n.length);o.set(r),o.set(n,r.length),this.setBuffer(o)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(let a of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:o,pos:s,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${oC(o)} at ${i} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,o=-1;for await(let s of t){if(r&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){let o=t-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t<160){let o=t-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else{let o=t-160;r=this.decodeString(o,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){let o=this.lookU8();r=this.decodeString(o,1)}else if(t===218){let o=this.lookU16();r=this.decodeString(o,2)}else if(t===219){let o=this.lookU32();r=this.decodeString(o,4)}else if(t===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===196){let o=this.lookU8();r=this.decodeBinary(o,1)}else if(t===197){let o=this.lookU16();r=this.decodeBinary(o,2)}else if(t===198){let o=this.lookU32();r=this.decodeBinary(o,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){let o=this.lookU8();r=this.decodeExtension(o,1)}else if(t===200){let o=this.lookU16();r=this.decodeExtension(o,2)}else if(t===201){let o=this.lookU32();r=this.decodeExtension(o,4)}else throw new gi(`Unrecognized type byte: ${oC(t)}`);this.complete();let n=this.stack;for(;n.length>0;){let o=n.top();if(o.type===oO)if(o.array[o.position]=r,o.position++,o.position===o.size)r=o.array,n.release(o);else continue e;else if(o.type===w8){if(r==="__proto__")throw new gi("The key __proto__ is not allowed");o.key=this.mapKeyConverter(r),o.type=WZ;continue e}else if(o.map[o.key]=r,o.readCount++,o.readCount===o.size)r=o.map,n.release(o);else{o.key=null,o.type=w8;continue e}}return r}}readHeadByte(){return this.headByte===y8&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=y8}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new gi(`Unrecognized array type byte: ${oC(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new gi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new gi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new gi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===w8:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new gi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw qZ;let n=this.pos+r,o=this.bytes.subarray(n,n+t);return this.pos+=r+t,o}decodeExtension(t,r){if(t>this.maxExtLength)throw new gi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+r),o=this.decodeBinary(t,r+1);return this.extensionCodec.decode(o,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){let t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){let t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){let t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){let t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){let t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){let t=VZ(this.view,this.pos);return this.pos+=8,t}readI64(){let t=rC(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){let t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){let t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){let t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){let t=this.view.getFloat64(this.pos);return this.pos+=8,t}};function aO(e,t){return new iC(t).decode(e)}JR();I8();l();l();XA();var DG=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),LTe=DG("expand 16-byte k"),MTe=DG("expand 32-byte k"),HTe=ef(LTe),$Te=ef(MTe);function je(e,t){return e<>>32-t}function kO(e){return e.byteOffset%4===0}var hC=64,FTe=16,LG=2**32-1,UG=new Uint32Array;function zTe(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(hC),d=ef(u),f=kO(o)&&kO(s),p=f?ef(o):UG,h=f?ef(s):UG;for(let y=0;y=LG)throw new Error("arx: counter overflow");let w=Math.min(hC,c-y);if(f&&w===hC){let x=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,T;v{rs(a),rs(c),rs(u);let p=u.length;if(d===void 0&&(d=new Uint8Array(p)),rs(d),YA(f),f<0||f>=LG)throw new Error("arx: counter overflow");if(d.lengthe[t++]&255|(e[t++]&255)<<8,DO=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=JA(t),rs(t,32);let r=Lo(t,0),n=Lo(t,2),o=Lo(t,4),s=Lo(t,6),i=Lo(t,8),a=Lo(t,10),c=Lo(t,12),u=Lo(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Lo(t,16+2*d)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],d=i[3],f=i[4],p=i[5],h=i[6],y=i[7],w=i[8],x=i[9],v=Lo(t,r+0),T=Lo(t,r+2),E=Lo(t,r+4),S=Lo(t,r+6),_=Lo(t,r+8),O=Lo(t,r+10),D=Lo(t,r+12),M=Lo(t,r+14),N=s[0]+(v&8191),L=s[1]+((v>>>13|T<<3)&8191),P=s[2]+((T>>>10|E<<6)&8191),R=s[3]+((E>>>7|S<<9)&8191),I=s[4]+((S>>>4|_<<12)&8191),B=s[5]+(_>>>1&8191),C=s[6]+((_>>>14|O<<2)&8191),A=s[7]+((O>>>11|D<<5)&8191),U=s[8]+((D>>>8|M<<8)&8191),H=s[9]+(M>>>5|o),k=0,F=k+N*a+L*(5*x)+P*(5*w)+R*(5*y)+I*(5*h);k=F>>>13,F&=8191,F+=B*(5*p)+C*(5*f)+A*(5*d)+U*(5*u)+H*(5*c),k+=F>>>13,F&=8191;let j=k+N*c+L*a+P*(5*x)+R*(5*w)+I*(5*y);k=j>>>13,j&=8191,j+=B*(5*h)+C*(5*p)+A*(5*f)+U*(5*d)+H*(5*u),k+=j>>>13,j&=8191;let W=k+N*u+L*c+P*a+R*(5*x)+I*(5*w);k=W>>>13,W&=8191,W+=B*(5*y)+C*(5*h)+A*(5*p)+U*(5*f)+H*(5*d),k+=W>>>13,W&=8191;let ae=k+N*d+L*u+P*c+R*a+I*(5*x);k=ae>>>13,ae&=8191,ae+=B*(5*w)+C*(5*y)+A*(5*h)+U*(5*p)+H*(5*f),k+=ae>>>13,ae&=8191;let te=k+N*f+L*d+P*u+R*c+I*a;k=te>>>13,te&=8191,te+=B*(5*x)+C*(5*w)+A*(5*y)+U*(5*h)+H*(5*p),k+=te>>>13,te&=8191;let X=k+N*p+L*f+P*d+R*u+I*c;k=X>>>13,X&=8191,X+=B*a+C*(5*x)+A*(5*w)+U*(5*y)+H*(5*h),k+=X>>>13,X&=8191;let pe=k+N*h+L*p+P*f+R*d+I*u;k=pe>>>13,pe&=8191,pe+=B*c+C*a+A*(5*x)+U*(5*w)+H*(5*y),k+=pe>>>13,pe&=8191;let me=k+N*y+L*h+P*p+R*f+I*d;k=me>>>13,me&=8191,me+=B*u+C*c+A*a+U*(5*x)+H*(5*w),k+=me>>>13,me&=8191;let Ne=k+N*w+L*y+P*h+R*p+I*f;k=Ne>>>13,Ne&=8191,Ne+=B*d+C*u+A*c+U*a+H*(5*x),k+=Ne>>>13,Ne&=8191;let ye=k+N*x+L*w+P*y+R*h+I*p;k=ye>>>13,ye&=8191,ye+=B*f+C*d+A*u+U*c+H*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+F|0,F=k&8191,k=k>>>13,j+=k,s[0]=F,s[1]=j,s[2]=W,s[3]=ae,s[4]=te,s[5]=X,s[6]=pe,s[7]=me,s[8]=Ne,s[9]=ye}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;tf(n)}update(t){QR(this),t=JA(t),rs(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function VTe(e){let t=(n,o)=>e(o).update(JA(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var MG=VTe(e=>new DO(e));XA();function FG(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],p=t[2],h=t[3],y=t[4],w=t[5],x=t[6],v=t[7],T=o,E=r[0],S=r[1],_=r[2],O=i,D=a,M=c,N=u,L=d,P=f,R=p,I=h,B=y,C=w,A=x,U=v,H=T,k=E,F=S,j=_;for(let ae=0;ae{e.update(t);let r=t.length%16;r&&e.update(KTe.subarray(r))},ZTe=new Uint8Array(32);function $G(e,t,r,n,o){let s=e(t,r,ZTe),i=MG.create(s);o&&HG(i,o),HG(i,n);let a=BZ(n.length,o?o.length:0,!0);i.update(a);let c=i.digest();return tf(s,a),c}var zG=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=eO(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let u=$G(e,t,r,c,n);return i.set(u,a),tf(u),i},decrypt(s,i){i=eO(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=$G(e,t,r,a,n);if(!OZ(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),tf(u),i}}),LO=XR({blockSize:64,nonceLength:12,tagLength:16},zG(qTe)),hdt=XR({blockSize:64,nonceLength:24,tagLength:16},zG(WTe));l();function GTe(e,t,r){return p1(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Xp(e,Qo(r),Qo(t))}var MO=Uint8Array.from([0]),VG=Uint8Array.of();function YTe(e,t,r,n=32){p1(e),Jo(n);let o=e.outputLen;if(n>255*o)throw new Error("Length should be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0&&(r=VG);let i=new Uint8Array(s*o),a=Xp.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;dYTe(e,GTe(e,t,r),n,o);l();l();l();var FO=BigInt(0),$O=BigInt(1);function nf(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function aa(e,t,r=""){let n=Wd(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function T8(e){let t=e.toString(16);return t.length&1?"0"+t:t}function qG(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?FO:BigInt("0x"+e)}function $2(e){return qG(za(e))}function ja(e){return Cn(e),qG(za(Uint8Array.from(e).reverse()))}function mC(e,t){return m1(e.toString(16).padStart(t*2,"0"))}function _8(e,t){return mC(e,t).reverse()}function or(e,t,r){let n;if(typeof t=="string")try{n=m1(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Wd(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function WG(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;ntypeof e=="bigint"&&FO<=e;function KG(e,t,r){return HO(e)&&HO(t)&&HO(r)&&t<=e&&eFO;e>>=$O,t+=1);return t}var sh=e=>($O<new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(e),i=n(e),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...h)=>r(i,s,...h),d=(h=n(0))=>{i=u(o(0),h),s=u(),h.length!==0&&(i=u(o(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,y=[];for(;h{c(),d(h);let w;for(;!(w=y(f()));)d();return c(),w}}function Ll(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var VO=()=>{throw new Error("not implemented")};function F2(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}l();var Hs=BigInt(0),ho=BigInt(1),_1=BigInt(2),JG=BigInt(3),QG=BigInt(4),XG=BigInt(5),JTe=BigInt(7),eY=BigInt(8),QTe=BigInt(9),tY=BigInt(16);function Yr(e,t){let r=e%t;return r>=Hs?r:t+r}function qa(e,t,r){let n=e;for(;t-- >Hs;)n*=n,n%=r;return n}function GG(e,t){if(e===Hs)throw new Error("invert: expected non-zero number");if(t<=Hs)throw new Error("invert: expected positive modulus, got "+t);let r=Yr(e,t),n=t,o=Hs,s=ho,i=ho,a=Hs;for(;r!==Hs;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ho)throw new Error("invert: does not exist");return Yr(o,t)}function jO(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function rY(e,t){let r=(e.ORDER+ho)/QG,n=e.pow(t,r);return jO(e,n,t),n}function XTe(e,t){let r=(e.ORDER-XG)/eY,n=e.mul(t,_1),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,_1),o),a=e.mul(s,e.sub(i,e.ONE));return jO(e,a,t),a}function e_e(e){let t=$s(e),r=nY(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+JTe)/tY;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),h=a.eql(a.sqr(d),c),y=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(p,f,y);let w=a.eql(a.sqr(d),c),x=a.cmov(u,d,w);return jO(a,x,c),x}}function nY(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return rY;let s=o.pow(n,t),i=(t+ho)/_1;return function(c,u){if(c.is0(u))return u;if(YG(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ho<(Yr(e,t)&ho)===ho,r_e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qO(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=r_e.reduce((n,o)=>(n[o]="function",n),t);return Ll(e,r),e}function n_e(e,t,r){if(rHs;)r&ho&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ho;return n}function P8(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function YG(e,t){let r=(e.ORDER-ho)/_1,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function yC(e,t){t!==void 0&&Jo(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function $s(e,t,r=!1,n={}){if(e<=Hs)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(r=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=yC(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:sh(c),ZERO:Hs,ONE:ho,allowedLengths:a,create:p=>Yr(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return Hs<=p&&pp===Hs,isValidNot0:p=>!f.is0(p)&&f.isValid(p),isOdd:p=>(p&ho)===ho,neg:p=>Yr(-p,e),eql:(p,h)=>p===h,sqr:p=>Yr(p*p,e),add:(p,h)=>Yr(p+h,e),sub:(p,h)=>Yr(p-h,e),mul:(p,h)=>Yr(p*h,e),pow:(p,h)=>n_e(f,p,h),div:(p,h)=>Yr(p*GG(h,e),e),sqrN:p=>p*p,addN:(p,h)=>p+h,subN:(p,h)=>p-h,mulN:(p,h)=>p*h,inv:p=>GG(p,e),sqrt:s||(p=>(d||(d=t_e(e)),d(f,p))),toBytes:p=>r?_8(p,u):mC(p,u),fromBytes:(p,h=!0)=>{if(a){if(!a.includes(p.length)||p.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let w=new Uint8Array(u);w.set(p,r?0:w.length-p.length),p=w}if(p.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+p.length);let y=r?ja(p):$2(p);if(i&&(y=Yr(y,e)),!h&&!f.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:p=>P8(f,p),cmov:(p,h,y)=>y?h:p});return Object.freeze(f)}function oY(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function WO(e){let t=oY(e);return t+Math.ceil(t/2)}function sY(e,t,r=!1){let n=e.length,o=oY(t),s=WO(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?ja(e):$2(e),a=Yr(i,t-ho)+ho;return r?_8(a,o):mC(a,o)}var z2=BigInt(0),P1=BigInt(1);function N8(e,t){let r=t.negate();return e?r:t}function sf(e,t){let r=P8(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function lY(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function KO(e,t){lY(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=sh(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function iY(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=P1);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function o_e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function s_e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var ZO=new WeakMap,uY=new WeakMap;function GO(e){return uY.get(e)||1}function aY(e){if(e!==z2)throw new Error("invalid wNAF")}var V2=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>z2;)r&P1&&(n=n.add(o)),o=o.double(),r>>=P1;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=KO(r,this.bits),s=[],i=t,a=i;for(let c=0;cz2||n>z2;)r&P1&&(s=s.add(o)),n&P1&&(i=i.add(o)),o=o.double(),r>>=P1,n>>=P1;return{p1:s,p2:i}}function j2(e,t,r,n){o_e(r,e),s_e(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=gC(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=sh(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;wz2))throw new Error(`CURVE.${c} must be positive bigint`)}let o=cY(t.p,r.Fp,n),s=cY(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}l();var ih=BigInt(0),mo=BigInt(1),YO=BigInt(2),i_e=BigInt(8);function a_e(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function c_e(e,t={}){let r=wC("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Ll(t,{},{uvRatio:"function"});let a=YO<n.create(x),u=t.uvRatio||((x,v)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,v))}}catch{return{isValid:!1,value:ih}}});if(!a_e(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(x,v,T=!1){let E=T?mo:ih;return oh("coordinate "+x,v,E,a),v}function f(x){if(!(x instanceof y))throw new Error("ExtendedPoint expected")}let p=F2((x,v)=>{let{X:T,Y:E,Z:S}=x,_=x.is0();v==null&&(v=_?i_e:n.inv(S));let O=c(T*v),D=c(E*v),M=n.mul(S,v);if(_)return{x:ih,y:mo};if(M!==mo)throw new Error("invZ was invalid");return{x:O,y:D}}),h=F2(x=>{let{a:v,d:T}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:E,Y:S,Z:_,T:O}=x,D=c(E*E),M=c(S*S),N=c(_*_),L=c(N*N),P=c(D*v),R=c(N*c(P+M)),I=c(L+c(T*c(D*M)));if(R!==I)throw new Error("bad point: equation left != right (1)");let B=c(E*S),C=c(_*O);if(B!==C)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,T,E,S){this.X=d("x",v),this.Y=d("y",T),this.Z=d("z",E,!0),this.T=d("t",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:T,y:E}=v||{};return d("x",T),d("y",E),new y(T,E,mo,c(T*E))}static fromBytes(v,T=!1){let E=n.BYTES,{a:S,d:_}=s;v=zO(aa(v,E,"point")),nf(T,"zip215");let O=zO(v),D=v[E-1];O[E-1]=D&-129;let M=ja(O),N=T?a:n.ORDER;oh("point.y",M,ih,N);let L=c(M*M),P=c(L-mo),R=c(_*L-S),{isValid:I,value:B}=u(P,R);if(!I)throw new Error("bad point: invalid y coordinate");let C=(B&mo)===mo,A=(D&128)!==0;if(!T&&B===ih&&A)throw new Error("bad point: x=0 and x_0=1");return A!==C&&(B=c(-B)),y.fromAffine({x:B,y:M})}static fromHex(v,T=!1){return y.fromBytes(or("point",v),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,T=!0){return w.createCache(this,v),T||this.multiply(YO),this}assertValidity(){h(this)}equals(v){f(v);let{X:T,Y:E,Z:S}=this,{X:_,Y:O,Z:D}=v,M=c(T*D),N=c(_*S),L=c(E*D),P=c(O*S);return M===N&&L===P}is0(){return this.equals(y.ZERO)}negate(){return new y(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:v}=s,{X:T,Y:E,Z:S}=this,_=c(T*T),O=c(E*E),D=c(YO*c(S*S)),M=c(v*_),N=T+E,L=c(c(N*N)-_-O),P=M+O,R=P-D,I=M-O,B=c(L*R),C=c(P*I),A=c(L*I),U=c(R*P);return new y(B,C,U,A)}add(v){f(v);let{a:T,d:E}=s,{X:S,Y:_,Z:O,T:D}=this,{X:M,Y:N,Z:L,T:P}=v,R=c(S*M),I=c(_*N),B=c(D*E*P),C=c(O*L),A=c((S+_)*(M+N)-R-I),U=C-B,H=C+B,k=c(I-T*R),F=c(A*U),j=c(H*k),W=c(A*k),ae=c(U*H);return new y(F,j,ae,W)}subtract(v){return this.add(v.negate())}multiply(v){if(!o.isValidNot0(v))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:T,f:E}=w.cached(this,v,S=>sf(y,S));return sf(y,[T,E])[0]}multiplyUnsafe(v,T=y.ZERO){if(!o.isValid(v))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return v===ih?y.ZERO:this.is0()||v===mo?this:w.unsafe(this,v,E=>sf(y,E),T)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,s.n).is0()}toAffine(v){return p(this,v)}clearCofactor(){return i===mo?this:this.multiplyUnsafe(i)}toBytes(){let{x:v,y:T}=this.toAffine(),E=n.toBytes(T);return E[E.length-1]|=v&mo?128:0,E}toHex(){return za(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(v){return sf(y,v)}static msm(v,T){return j2(y,o,v,T)}_setWindowSize(v){this.precompute(v)}toRawBytes(){return this.toBytes()}}y.BASE=new y(s.Gx,s.Gy,mo,c(s.Gx*s.Gy)),y.ZERO=new y(ih,mo,mo,ih),y.Fp=n,y.Fn=o;let w=new V2(y,o.BITS);return y.BASE.precompute(8),y}var bC=class{constructor(t){this.ep=t}static fromBytes(t){VO()}static fromHex(t){VO()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return za(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function l_e(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ll(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||Us,c=r.adjustScalarBytes||(N=>N),u=r.domain||((N,L,P)=>{if(nf(P,"phflag"),L.length||P)throw new Error("Contexts/pre-hash are not supported");return N});function d(N){return i.create(ja(N))}function f(N){let L=E.secretKey;N=or("private key",N,L);let P=or("hashed private key",t(N),2*L),R=c(P.slice(0,L)),I=P.slice(L,2*L),B=d(R);return{head:R,prefix:I,scalar:B}}function p(N){let{head:L,prefix:P,scalar:R}=f(N),I=o.multiply(R),B=I.toBytes();return{head:L,prefix:P,scalar:R,point:I,pointBytes:B}}function h(N){return p(N).pointBytes}function y(N=Uint8Array.of(),...L){let P=ko(...L);return d(t(u(P,or("context",N),!!n)))}function w(N,L,P={}){N=or("message",N),n&&(N=n(N));let{prefix:R,scalar:I,pointBytes:B}=p(L),C=y(P.context,R,N),A=o.multiply(C).toBytes(),U=y(P.context,A,B,N),H=i.create(C+U*I);if(!i.isValid(H))throw new Error("sign failed: invalid s");let k=ko(A,i.toBytes(H));return aa(k,E.signature,"result")}let x={zip215:!0};function v(N,L,P,R=x){let{context:I,zip215:B}=R,C=E.signature;N=or("signature",N,C),L=or("message",L),P=or("publicKey",P,E.publicKey),B!==void 0&&nf(B,"zip215"),n&&(L=n(L));let A=C/2,U=N.subarray(0,A),H=ja(N.subarray(A,C)),k,F,j;try{k=e.fromBytes(P,B),F=e.fromBytes(U,B),j=o.multiplyUnsafe(H)}catch{return!1}if(!B&&k.isSmallOrder())return!1;let W=y(I,F.toBytes(),k.toBytes(),L);return F.add(k.multiplyUnsafe(W)).subtract(j).clearCofactor().is0()}let T=s.BYTES,E={secretKey:T,publicKey:T,signature:2*T,seed:T};function S(N=a(E.seed)){return aa(N,E.seed,"seed")}function _(N){let L=M.randomSecretKey(N);return{secretKey:L,publicKey:h(L)}}function O(N){return Wd(N)&&N.length===i.BYTES}function D(N,L){try{return!!e.fromBytes(N,L)}catch{return!1}}let M={getExtendedPublicKey:p,randomSecretKey:S,isValidSecretKey:O,isValidPublicKey:D,toMontgomery(N){let{y:L}=e.fromBytes(N),P=E.publicKey,R=P===32;if(!R&&P!==57)throw new Error("only defined for 25519 and 448");let I=R?s.div(mo+L,mo-L):s.div(L-mo,L+mo);return s.toBytes(I)},toMontgomerySecret(N){let L=E.secretKey;aa(N,L);let P=t(N.subarray(0,L));return c(P).subarray(0,L)},randomPrivateKey:S,precompute(N=8,L=e.BASE){return L.precompute(N,!1)}};return Object.freeze({keygen:_,getPublicKey:h,sign:w,verify:v,utils:M,Point:e,lengths:E})}function u_e(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=$s(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:s}}function d_e(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function fY(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=u_e(e),s=c_e(t,r),i=l_e(s,n,o);return d_e(e,i)}l();var R8=BigInt(0),q2=BigInt(1),xC=BigInt(2);function f_e(e){return Ll(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function pY(e){let t=f_e(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Us,u=a?255:448,d=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),h=a?xC**BigInt(254):xC**BigInt(447),y=a?BigInt(8)*xC**BigInt(251)-q2:BigInt(4)*xC**BigInt(445)-q2,w=h+y+q2,x=I=>Yr(I,r),v=T(f);function T(I){return _8(x(I),d)}function E(I){let B=or("u coordinate",I,d);return a&&(B[31]&=127),x(ja(B))}function S(I){return ja(o(or("scalar",I,d)))}function _(I,B){let C=M(E(B),S(I));if(C===R8)throw new Error("invalid private or public key received");return T(C)}function O(I){return _(I,v)}function D(I,B,C){let A=x(I*(B-C));return B=x(B-A),C=x(C+A),{x_2:B,x_3:C}}function M(I,B){oh("u",I,R8,r),oh("scalar",B,h,w);let C=B,A=I,U=q2,H=R8,k=I,F=q2,j=R8;for(let ae=BigInt(u-1);ae>=R8;ae--){let te=C>>ae&q2;j^=te,{x_2:U,x_3:k}=D(j,U,k),{x_2:H,x_3:F}=D(j,H,F),j=te;let X=U+H,pe=x(X*X),me=U-H,Ne=x(me*me),ye=pe-Ne,Re=k+F,Et=k-F,kt=x(Et*X),At=x(Re*me),ur=kt+At,_r=kt-At;k=x(ur*ur),F=x(A*x(_r*_r)),U=x(pe*Ne),H=x(ye*(pe+x(p*ye)))}({x_2:U,x_3:k}=D(j,U,k)),{x_2:H,x_3:F}=D(j,H,F);let W=s(H);return x(U*W)}let N={secretKey:d,publicKey:d,seed:d},L=(I=c(d))=>(Cn(I,N.seed),I);function P(I){let B=L(I);return{secretKey:B,publicKey:O(B)}}return{keygen:P,getSharedSecret:(I,B)=>_(I,B),getPublicKey:I=>O(I),scalarMult:_,scalarMultBase:O,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:v.slice(),lengths:N}}var p_e=BigInt(0),cf=BigInt(1),hY=BigInt(2),h_e=BigInt(3),m_e=BigInt(5),g_e=BigInt(8),W2=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),O8={p:W2,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:g_e,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yY(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=W2,a=e*e%s*e%s,c=qa(a,hY,s)*a%s,u=qa(c,cf,s)*e%s,d=qa(u,m_e,s)*u%s,f=qa(d,t,s)*d%s,p=qa(f,r,s)*f%s,h=qa(p,n,s)*p%s,y=qa(h,o,s)*h%s,w=qa(y,o,s)*h%s,x=qa(w,t,s)*d%s;return{pow_p_5_8:qa(x,hY,s)*e%s,b2:a}}function wY(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var JO=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function eB(e,t){let r=W2,n=Yr(t*t*t,r),o=Yr(n*n*t,r),s=yY(e*o).pow_p_5_8,i=Yr(e*n*s,r),a=Yr(t*i*i,r),c=i,u=Yr(i*JO,r),d=a===e,f=a===Yr(-e,r),p=a===Yr(-e*JO,r);return d&&(i=c),(f||p)&&(i=u),of(i,r)&&(i=Yr(-i,r)),{isValid:d||f,value:i}}var af=$s(O8.p,{isLE:!0}),y_e=$s(O8.n,{isLE:!0}),w_e={...O8,Fp:af,hash:bA,adjustScalarBytes:wY,uvRatio:eB},N1=fY(w_e);var vC=(()=>{let e=af.ORDER;return pY({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=yY(t);return Yr(qa(r,h_e,e)*n,e)},adjustScalarBytes:wY})})();var QO=JO,b_e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x_e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),v_e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),E_e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),mY=e=>eB(cf,e),A_e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),XO=e=>N1.Point.Fp.create(ja(e)&A_e);function gY(e){let{d:t}=O8,r=W2,n=v=>af.create(v),o=n(QO*e*e),s=n((o+cf)*v_e),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=eB(s,a),d=n(u*e);of(d,r)||(d=n(-d)),c||(u=d),c||(i=o);let f=n(i*(o-cf)*E_e-a),p=u*u,h=n((u+u)*a),y=n(f*b_e),w=n(cf-p),x=n(cf+p);return new N1.Point(n(h*x),n(w*y),n(y*x),n(h*w))}function C_e(e){Cn(e,64);let t=XO(e.subarray(0,32)),r=gY(t),n=XO(e.subarray(32,64)),o=gY(n);return new lf(r.add(o))}var lf=class e extends bC{constructor(t){super(t)}static fromAffine(t){return new e(N1.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return C_e(or("ristrettoHash",t,64))}static fromBytes(t){Cn(t,32);let{a:r,d:n}=O8,o=W2,s=S=>af.create(S),i=XO(t);if(!WG(af.toBytes(i),t)||of(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(cf+r*a),u=s(cf-r*a),d=s(c*c),f=s(u*u),p=s(r*n*d-f),{isValid:h,value:y}=mY(s(p*f)),w=s(y*u),x=s(y*w*p),v=s((i+i)*w);of(v,o)&&(v=s(-v));let T=s(c*x),E=s(v*T);if(!h||of(E,o)||T===p_e)throw new Error("invalid ristretto255 encoding 2");return new e(new N1.Point(v,T,cf,E))}static fromHex(t){return e.fromBytes(or("ristrettoHex",t,32))}static msm(t,r){return j2(e,N1.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=W2,i=x=>af.create(x),a=i(i(n+r)*i(n-r)),c=i(t*r),u=i(c*c),{value:d}=mY(i(a*u)),f=i(d*a),p=i(d*c),h=i(f*p*o),y;if(of(o*h,s)){let x=i(r*QO),v=i(t*QO);t=x,r=v,y=i(f*x_e)}else y=p;of(t*h,s)&&(r=i(-r));let w=i((n-r)*y);return of(w,s)&&(w=i(-w)),af.toBytes(w)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>af.create(u),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};lf.BASE=new lf(N1.Point.BASE);lf.ZERO=new lf(N1.Point.ZERO);lf.Fp=af;lf.Fn=y_e;l();l();l();l();var bY=(e,t)=>(e+(e>=0?t:-t)/xY)/t;function S_e(e,t,r){let[[n,o],[s,i]]=t,a=bY(i*e,r),c=bY(-o*e,r),u=e-a*n-c*s,d=-a*o-c*i,f=u=h||d=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function rB(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function tB(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return nf(r.lowS,"lowS"),nf(r.prehash,"prehash"),r.format!==void 0&&rB(r.format),r}var nB=class extends Error{constructor(t=""){super(t)}},uf={Err:nB,_tlv:{encode:(e,t)=>{let{Err:r}=uf;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=T8(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?T8(o.length/2|128):"";return T8(e)+s+o+t},decode(e,t){let{Err:r}=uf,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=uf;if(e{let{X:B,Y:C,Z:A}=R;if(n.eql(A,n.ONE))return{x:B,y:C};let U=R.is0();I==null&&(I=U?n.ONE:n.inv(A));let H=n.mul(B,I),k=n.mul(C,I),F=n.mul(A,I);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:k}}),D=F2(R=>{if(R.is0()){if(t.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:B}=R.toAffine();if(!n.isValid(I)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!x(I,B))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,I,B,C,A){return B=new N(n.mul(B.X,R),B.Y,B.Z),I=N8(C,I),B=N8(A,B),I.add(B)}class N{constructor(I,B,C){this.X=E("x",I),this.Y=E("y",B,!0),this.Z=E("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){let{x:B,y:C}=I||{};if(!I||!n.isValid(B)||!n.isValid(C))throw new Error("invalid affine point");if(I instanceof N)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(C)?N.ZERO:new N(B,C,n.ONE)}static fromBytes(I){let B=N.fromAffine(y(aa(I,void 0,"point")));return B.assertValidity(),B}static fromHex(I){return N.fromBytes(or("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,B=!0){return P.createCache(this,I),B||this.multiply(EC),this}assertValidity(){D(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.eql(n.mul(B,k),n.mul(U,A)),j=n.eql(n.mul(C,k),n.mul(H,A));return F&&j}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:B}=s,C=n.mul(B,EC),{X:A,Y:U,Z:H}=this,k=n.ZERO,F=n.ZERO,j=n.ZERO,W=n.mul(A,A),ae=n.mul(U,U),te=n.mul(H,H),X=n.mul(A,U);return X=n.add(X,X),j=n.mul(A,H),j=n.add(j,j),k=n.mul(I,j),F=n.mul(C,te),F=n.add(k,F),k=n.sub(ae,F),F=n.add(ae,F),F=n.mul(k,F),k=n.mul(X,k),j=n.mul(C,j),te=n.mul(I,te),X=n.sub(W,te),X=n.mul(I,X),X=n.add(X,j),j=n.add(W,W),W=n.add(j,W),W=n.add(W,te),W=n.mul(W,X),F=n.add(F,W),te=n.mul(U,H),te=n.add(te,te),W=n.mul(te,X),k=n.sub(k,W),j=n.mul(te,ae),j=n.add(j,j),j=n.add(j,j),new N(k,F,j)}add(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.ZERO,j=n.ZERO,W=n.ZERO,ae=s.a,te=n.mul(s.b,EC),X=n.mul(B,U),pe=n.mul(C,H),me=n.mul(A,k),Ne=n.add(B,C),ye=n.add(U,H);Ne=n.mul(Ne,ye),ye=n.add(X,pe),Ne=n.sub(Ne,ye),ye=n.add(B,A);let Re=n.add(U,k);return ye=n.mul(ye,Re),Re=n.add(X,me),ye=n.sub(ye,Re),Re=n.add(C,A),F=n.add(H,k),Re=n.mul(Re,F),F=n.add(pe,me),Re=n.sub(Re,F),W=n.mul(ae,ye),F=n.mul(te,me),W=n.add(F,W),F=n.sub(pe,W),W=n.add(pe,W),j=n.mul(F,W),pe=n.add(X,X),pe=n.add(pe,X),me=n.mul(ae,me),ye=n.mul(te,ye),pe=n.add(pe,me),me=n.sub(X,me),me=n.mul(ae,me),ye=n.add(ye,me),X=n.mul(pe,ye),j=n.add(j,X),X=n.mul(Re,ye),F=n.mul(Ne,F),F=n.sub(F,X),X=n.mul(Ne,pe),W=n.mul(Re,W),W=n.add(W,X),new N(F,j,W)}subtract(I){return this.add(I.negate())}is0(){return this.equals(N.ZERO)}multiply(I){let{endo:B}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let C,A,U=H=>P.cached(this,H,k=>sf(N,k));if(B){let{k1neg:H,k1:k,k2neg:F,k2:j}=_(I),{p:W,f:ae}=U(k),{p:te,f:X}=U(j);A=ae.add(X),C=M(B.beta,W,te,H,F)}else{let{p:H,f:k}=U(I);C=H,A=k}return sf(N,[C,A])[0]}multiplyUnsafe(I){let{endo:B}=t,C=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===df||C.is0())return N.ZERO;if(I===Z2)return C;if(P.hasCache(this))return this.multiply(I);if(B){let{k1neg:A,k1:U,k2neg:H,k2:k}=_(I),{p1:F,p2:j}=dY(N,C,U,k);return M(B.beta,F,j,A,H)}else return P.unsafe(C,I)}multiplyAndAddUnsafe(I,B,C){let A=this.multiplyUnsafe(B).add(I.multiplyUnsafe(C));return A.is0()?void 0:A}toAffine(I){return O(this,I)}isTorsionFree(){let{isTorsionFree:I}=t;return i===Z2?!0:I?I(N,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=t;return i===Z2?this:I?I(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return nf(I,"isCompressed"),this.assertValidity(),h(N,this,I)}toHex(I=!0){return za(this.toBytes(I))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return sf(N,I)}static msm(I,B){return j2(N,o,I,B)}static fromPrivateKey(I){return N.BASE.multiply(K2(o,I))}}N.BASE=new N(s.Gx,s.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=o;let L=o.BITS,P=new V2(N,t.endo?Math.ceil(L/2):L);return N.BASE.precompute(8),N}function vY(e){return Uint8Array.of(e?2:3)}function EY(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function __e(e,t={}){let{Fn:r}=e,n=t.randomBytes||Us,o=Object.assign(EY(e.Fp,r),{seed:WO(r.ORDER)});function s(h){try{return!!K2(r,h)}catch{return!1}}function i(h,y){let{publicKey:w,publicKeyUncompressed:x}=o;try{let v=h.length;return y===!0&&v!==w||y===!1&&v!==x?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return sY(aa(h,o.seed,"seed"),r.ORDER)}function c(h,y=!0){return e.BASE.multiply(K2(r,h)).toBytes(y)}function u(h){let y=a(h);return{secretKey:y,publicKey:c(y)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;let{secretKey:y,publicKey:w,publicKeyUncompressed:x}=o;if(r.allowedLengths||y===w)return;let v=or("key",h).length;return v===w||v===x}function f(h,y,w=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let x=K2(r,h);return e.fromHex(y).multiply(x).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>K2(r,h),precompute(h=8,y=e.BASE){return y.precompute(h,!1)}},lengths:o})}function P_e(e,t,r={}){p1(t),Ll(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Us,o=r.hmac||((B,...C)=>Xp(t,B,ko(...C))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h}=__e(e,r),y={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function x(B){let C=a>>Z2;return B>C}function v(B,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${B}: out of range 1..Point.Fn.ORDER`);return C}function T(B,C){rB(C);let A=h.signature,U=C==="compact"?A:C==="recovered"?A+1:void 0;return aa(B,U,`${C} signature`)}class E{constructor(C,A,U){this.r=v("r",C),this.s=v("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(C,A=w){T(C,A);let U;if(A==="der"){let{r:j,s:W}=uf.toSig(aa(C));return new E(j,W)}A==="recovered"&&(U=C[0],A="compact",C=C.subarray(1));let H=i.BYTES,k=C.subarray(0,H),F=C.subarray(H,H*2);return new E(i.fromBytes(k),i.fromBytes(F),U)}static fromHex(C,A){return this.fromBytes(m1(C),A)}addRecoveryBit(C){return new E(this.r,this.s,C)}recoverPublicKey(C){let A=s.ORDER,{r:U,s:H,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*xY1)throw new Error("recovery id is ambiguous for h>1 curve");let j=k===2||k===3?U+a:U;if(!s.isValid(j))throw new Error("recovery id 2 or 3 invalid");let W=s.toBytes(j),ae=e.fromBytes(ko(vY((k&1)===0),W)),te=i.inv(j),X=_(or("msgHash",C)),pe=i.create(-X*te),me=i.create(H*te),Ne=e.BASE.multiplyUnsafe(pe).add(ae.multiplyUnsafe(me));if(Ne.is0())throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return x(this.s)}toBytes(C=w){if(rB(C),C==="der")return m1(uf.hexFromSig(this));let A=i.toBytes(this.r),U=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ko(Uint8Array.of(this.recovery),A,U)}return ko(A,U)}toHex(C){return za(this.toBytes(C))}assertValidity(){}static fromCompact(C){return E.fromBytes(or("sig",C),"compact")}static fromDER(C){return E.fromBytes(or("sig",C),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return za(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return za(this.toBytes("compact"))}}let S=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=$2(C),U=C.length*8-c;return U>0?A>>BigInt(U):A},_=r.bits2int_modN||function(C){return i.create(S(C))},O=sh(c);function D(B){return oh("num < 2^"+c,B,df,O),i.toBytes(B)}function M(B,C){return aa(B,void 0,"message"),C?aa(t(B),void 0,"prehashed message"):B}function N(B,C,A){if(["recovered","canonical"].some(pe=>pe in A))throw new Error("sign() legacy options not supported");let{lowS:U,prehash:H,extraEntropy:k}=tB(A,y);B=M(B,H);let F=_(B),j=K2(i,C),W=[D(j),D(F)];if(k!=null&&k!==!1){let pe=k===!0?n(h.secretKey):k;W.push(or("extraEntropy",pe))}let ae=ko(...W),te=F;function X(pe){let me=S(pe);if(!i.isValidNot0(me))return;let Ne=i.inv(me),ye=e.BASE.multiply(me).toAffine(),Re=i.create(ye.x);if(Re===df)return;let Et=i.create(Ne*i.create(te+Re*j));if(Et===df)return;let kt=(ye.x===Re?0:2)|Number(ye.y&Z2),At=Et;return U&&x(Et)&&(At=i.neg(Et),kt^=1),new E(Re,At,kt)}return{seed:ae,k2sig:X}}function L(B,C,A={}){B=or("message",B);let{seed:U,k2sig:H}=N(B,C,A);return ZG(t.outputLen,i.BYTES,o)(U,H)}function P(B){let C,A=typeof B=="string"||Wd(B),U=!A&&B!==null&&typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)C=new E(B.r,B.s);else if(A){try{C=E.fromBytes(or("sig",B),"der")}catch(H){if(!(H instanceof uf.Err))throw H}if(!C)try{C=E.fromBytes(or("sig",B),"compact")}catch{return!1}}return C||!1}function R(B,C,A,U={}){let{lowS:H,prehash:k,format:F}=tB(U,y);if(A=or("publicKey",A),C=M(or("message",C),k),"strict"in U)throw new Error("options.strict was renamed to lowS");let j=F===void 0?P(B):E.fromBytes(or("sig",B),F);if(j===!1)return!1;try{let W=e.fromBytes(A);if(H&&j.hasHighS())return!1;let{r:ae,s:te}=j,X=_(C),pe=i.inv(te),me=i.create(X*pe),Ne=i.create(ae*pe),ye=e.BASE.multiplyUnsafe(me).add(W.multiplyUnsafe(Ne));return ye.is0()?!1:i.create(ye.x)===ae}catch{return!1}}function I(B,C,A={}){let{prehash:U}=tB(A,y);return C=M(C,U),E.fromBytes(B,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h,Point:e,sign:L,verify:R,recoverPublicKey:I,Signature:E,hash:t})}function N_e(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$s(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function R_e(e){let{CURVE:t,curveOpts:r}=N_e(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function O_e(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,yC(r.Fn.ORDER,r.Fn.BITS))})}function AY(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:o}=R_e(e),s=T_e(t,r),i=P_e(s,n,o);return O_e(e,i)}function AC(e,t){let r=n=>AY({...e,hash:n});return{...r(t),create:r}}var CY={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},SY={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},IY={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},B_e=$s(CY.p),k_e=$s(SY.p),U_e=$s(IY.p);var TY=AC({...CY,Fp:B_e,lowS:!1},Zd);var fft=AC({...SY,Fp:k_e,lowS:!1},fK);var pft=AC({...IY,Fp:U_e,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},bA);var _Y=TY;B1();BB();var tQ=Ht(LB(),1);gh();var pRe=":";function Lc(e){let[t,r]=e.split(pRe);return{namespace:t,reference:r}}function GB(e,t=[]){let r=[];return Object.keys(e).forEach(n=>{if(t.length&&!t.includes(n))return;let o=e[n];r.push(...o.accounts)}),r}function rQ(e,t){return e.includes(":")?[e]:t.chains||[]}var hRe={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},mRe={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Se(e,t){let{message:r,code:n}=mRe[e];return{message:t?`${r} ${t}`:r,code:n}}function Sr(e,t){let{message:r,code:n}=hRe[e];return{message:t?`${r} ${t}`:r,code:n}}var gRe="ReactNative",bi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"};var yRe="js";function z8(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function gf(){return!(0,Dc.getDocument)()&&!!(0,Dc.getNavigator)()&&navigator.product===gRe}function nQ(){return gf()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="android"}function oQ(){return gf()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="ios"}function L1(){return!z8()&&!!(0,Dc.getNavigator)()&&!!(0,Dc.getDocument)()}function V8(){return gf()?bi.reactNative:z8()?bi.node:L1()?bi.browser:bi.unknown}function YB(){try{return gf()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function wRe(e,t){let r=new URLSearchParams(e);return Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!=null&&r.set(n,String(o))}),r.toString()}function sQ(e){let t=JB();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter(r=>r!=="")),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(r){return console.warn("Error populating app metadata",r),e||t}}function JB(){return(0,eQ.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function bRe(){if(V8()===bi.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let e=iA();if(e===null)return"unknown";let t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function xRe(){let e=V8();return e===bi.browser?[e,(0,Dc.getLocation)()?.host||"unknown"].join(":"):e}function QB(e,t,r){let n=bRe(),o=xRe();return[[e,t].join("-"),[yRe,r].join("-"),n,o].join("/")}function iQ({protocol:e,version:t,relayUrl:r,sdkVersion:n,auth:o,projectId:s,useOnCloseEvent:i,bundleId:a,packageName:c}){let u=r.split("?"),d=QB(e,t,n),f={auth:o,ua:d,projectId:s,useOnCloseEvent:i||void 0,packageName:c||void 0,bundleId:a||void 0},p=wRe(u[1]||"",f);return u[0]+"?"+p}function U1(e,t){return e.filter(r=>t.includes(r)).length===e.length}function ZC(e){return Object.fromEntries(e.entries())}function GC(e){return new Map(Object.entries(e))}function yf(e=mf.FIVE_MINUTES,t){let r=(0,mf.toMiliseconds)(e||mf.FIVE_MINUTES),n,o,s,i;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),i=Promise.resolve(a))},reject:a=>{s&&o&&(clearTimeout(s),o(a))},done:()=>new Promise((a,c)=>{if(i)return a(i);s=setTimeout(()=>{let u=Se("EXPIRED"),d=new Error(t||u.message);d.code=u.code,c(d)},r),n=a,o=c})}}function Wa(e,t,r){return new Promise(async(n,o)=>{let s=setTimeout(()=>o(new Error(r)),t);try{let i=await e;n(i)}catch(i){o(i)}clearTimeout(s)})}function aQ(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function cQ(e){return aQ("topic",e)}function lQ(e){return aQ("id",e)}function YC(e){let[t,r]=e.split(":"),n={id:void 0,topic:void 0};if(t==="topic"&&typeof r=="string")n.topic=r;else if(t==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);return n}function ln(e,t){return(0,mf.fromMiliseconds)((t||Date.now())+(0,mf.toMiliseconds)(e))}function ca(e){return Date.now()>=(0,mf.toMiliseconds)(e)}function ir(e,t){return`${e}${t?`:${t}`:""}`}function Uc(e=[],t=[]){return[...new Set([...e,...t])]}async function uQ({id:e,topic:t,wcDeepLink:r}){try{if(!r)return;let n=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof n!="string")return;let o=vRe(n,e,t),s=V8();if(s===bi.browser){if(!(0,Dc.getDocument)()?.hasFocus()){console.warn("Document does not have focus, skipping deeplink.");return}ERe(o)}else s===bi.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(o)}catch(n){console.error(n)}}function vRe(e,t,r){let n=`requestId=${t}&sessionTopic=${r}`;e.endsWith("/")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith("https://t.me")){let s=e.includes("?")?"&startapp=":"?startapp=";o=`${o}${s}${SRe(n,!0)}`}else o=`${o}/wc?${n}`;return o}function ERe(e){let t="_self";CRe()?t="_top":(ARe()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function dQ(e,t){let r="";try{if(L1()&&(r=localStorage.getItem(t),r))return r;r=await e.getItem(t)}catch(n){console.error(n)}return r}function XB(e,t){if(!e.includes(t))return null;let r=e.split(/([&,?,=])/),n=r.indexOf(t);return r[n+2]}function ek(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function j8(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function ARe(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function CRe(){try{return window.self!==window.top}catch{return!1}}function SRe(e,t=!1){let r=new TextEncoder().encode(e),n=new Array(r.length);for(let s=0;ssetTimeout(t,e))}var jC=class{constructor({limit:t}){this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){let r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(t)}}has(t){return this.set.has(t)}},IRe="https://rpc.walletconnect.org/v1";function ew(e){let t=e+"=".repeat((4-e.length%4)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o=0x80n;)t.push(Number(r&0x7fn|0x80n)),r>>=7n;return t.push(Number(r)),new Uint8Array(t)}function yQ(e){let t=ew(e.signed.bodyBytes),r=ew(e.signed.authInfoBytes),n=ew(e.signature.signature),o=[];o.push(new Uint8Array([10])),o.push(KB(t.length)),o.push(t),o.push(new Uint8Array([18])),o.push(KB(r.length)),o.push(r),o.push(new Uint8Array([26])),o.push(KB(n.length)),o.push(n);let s=Ms(o),i=Zd(s);return Ut(i,"base16").toUpperCase()}function wQ(e){let t=[];try{if(typeof e=="string")return t.push(e),t;if(typeof e!="object")return t;e?.id&&t.push(e.id);let r=e?.capabilities?.caip345?.transactionHashes;r&&t.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return t}var bQ="did:pkh:",ORe={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},BRe=e=>e?ORe[e]||e:"",JC=e=>e?.split(":"),kRe=e=>{let t=e&&JC(e);if(t)return e.includes(bQ)?t[3]:t[1]},URe=e=>{let t=e&&JC(e);if(t)return e.includes(bQ)?t[2]:t[0]},QC=e=>{let t=e&&JC(e);if(t)return t[2]+":"+t[3]},q8=e=>{let t=e&&JC(e);if(t)return t.pop()};async function nk(e){let{cacao:t,projectId:r}=e,{s:n,p:o}=t,s=ok(o,o.iss),i=q8(o.iss);return await TRe(i,s,n,QC(o.iss),r)}var ok=(e,t)=>{let r=URe(t);if(!r)throw new Error("Invalid issuer: "+t);let n=`${e.domain} wants you to sign in with your ${BRe(r)} account:`,o=q8(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0,i=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${kRe(t)}`,u=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,f=e.exp?`Expiration Time: ${e.exp}`:void 0,p=e.nbf?`Not Before: ${e.nbf}`:void 0,h=e.requestId?`Request ID: ${e.requestId}`:void 0,y=e.resources?`Resources:${e.resources.map(x=>` +- ${x}`).join("")}`:void 0,w=W8(e.resources);if(w){let x=F8(w);s=zRe(s,x)}return[n,o,"",s,"",i,a,c,u,d,f,p,h,y].filter(x=>x!=null).join(` +`)};function DRe(e){let t=JSON.stringify(e),r=new TextEncoder().encode(t),n=new Array(r.length);for(let o=0;o{let n=e.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(o=>{let s=n[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!="object")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function MRe(e,t,r,n={}){return r?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:HRe(t,r,n)}}}function HRe(e,t,r={}){t=t?.sort((o,s)=>o.localeCompare(s));let n=t.map(o=>({[`${e}/${o}`]:[r]}));return Object.assign({},...n)}function xQ(e){return D1(e),`urn:recap:${DRe(e).replace(/=/g,"")}`}function F8(e){let t=LRe(e.replace("urn:recap:",""));return D1(t),t}function vQ(e,t,r){let n=MRe(e,t,r);return xQ(n)}function $Re(e){return e&&e.includes("urn:recap:")}function EQ(e,t){let r=F8(e),n=F8(t),o=FRe(r,n);return xQ(o)}function FRe(e,t){D1(e),D1(t);let r=Object.keys(e.att).concat(Object.keys(t.att)).sort((o,s)=>o.localeCompare(s)),n={att:{}};return r.forEach(o=>{Object.keys(e.att?.[o]||{}).concat(Object.keys(t.att?.[o]||{})).sort((s,i)=>s.localeCompare(i)).forEach(s=>{n.att[o]={...n.att[o],[s]:e.att[o]?.[s]||t.att[o]?.[s]}})}),n}function zRe(e="",t){D1(t);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(r))return e;let n=[],o=0;Object.keys(t.att).forEach(a=>{let c=Object.keys(t.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,p)=>f.action.localeCompare(p.action));let u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});let d=Object.keys(u).map(f=>(o++,`(${o}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});let s=n.join(" "),i=`${r}${s}`;return`${e?e+" ":""}${i}`}function sk(e){let t=F8(e);D1(t);let r=t.att?.eip155;return r?Object.keys(r).map(n=>n.split("/")[1]):[]}function ik(e){let t=F8(e);D1(t);let r=[];return Object.values(t.att).forEach(n=>{Object.values(n).forEach(o=>{o?.[0]?.chains&&r.push(o[0].chains)})}),[...new Set(r.flat())]}function W8(e){if(!e)return;let t=e?.[e.length-1];return $Re(t)?t:void 0}var AQ="base10",is="base16",to="base64pad",wf="base64url",K8="utf8",CQ=0,Mc=1,tw=2,VRe=0,YJ=1,$8=12,ak=32;function SQ(){let e=vC.utils.randomPrivateKey(),t=vC.getPublicKey(e);return{privateKey:Ut(e,is),publicKey:Ut(t,is)}}function XC(){let e=Us(ak);return Ut(e,is)}function IQ(e,t){let r=vC.getSharedSecret(Qt(e,is),Qt(t,is)),n=jG(o8,r,void 0,void 0,ak);return Ut(n,is)}function rw(e){let t=o8(Qt(e,is));return Ut(t,is)}function xi(e){let t=o8(Qt(e,K8));return Ut(t,is)}function TQ(e){return Qt(`${e}`,AQ)}function yh(e){return Number(Ut(e,AQ))}function _Q(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qC(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}function PQ(e){let t=TQ(typeof e.type<"u"?e.type:CQ);if(yh(t)===Mc&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof e.senderPublicKey<"u"?Qt(e.senderPublicKey,is):void 0,n=typeof e.iv<"u"?Qt(e.iv,is):Us($8),o=Qt(e.symKey,is),s=LO(o,n).encrypt(Qt(e.message,K8)),i=BQ({type:t,sealed:s,iv:n,senderPublicKey:r});return e.encoding===wf?_Q(i):i}function NQ(e){let t=Qt(e.symKey,is),{sealed:r,iv:n}=nw({encoded:e.encoded,encoding:e.encoding}),o=LO(t,n).decrypt(r);if(o===null)throw new Error("Failed to decrypt");return Ut(o,K8)}function RQ(e,t){let r=TQ(tw),n=Us($8),o=Qt(e,K8),s=BQ({type:r,sealed:o,iv:n});return t===wf?_Q(s):s}function OQ(e,t){let{sealed:r}=nw({encoded:e,encoding:t});return Ut(r,K8)}function BQ(e){if(yh(e.type)===tw)return Ut(Ms([e.type,e.sealed]),to);if(yh(e.type)===Mc){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ut(Ms([e.type,e.senderPublicKey,e.iv,e.sealed]),to)}return Ut(Ms([e.type,e.iv,e.sealed]),to)}function nw(e){let t=(e.encoding||to)===wf?qC(e.encoded):e.encoded,r=Qt(t,to),n=r.slice(VRe,YJ),o=YJ;if(yh(n)===Mc){let c=o+ak,u=c+$8,d=r.slice(o,c),f=r.slice(c,u),p=r.slice(u);return{type:n,sealed:p,iv:f,senderPublicKey:d}}if(yh(n)===tw){let c=r.slice(o),u=Us($8);return{type:n,sealed:c,iv:u}}let s=o+$8,i=r.slice(o,s),a=r.slice(s);return{type:n,sealed:a,iv:i}}function kQ(e,t){let r=nw({encoded:e,encoding:t?.encoding});return ck({type:yh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ut(r.senderPublicKey,is):void 0,receiverPublicKey:t?.receiverPublicKey})}function ck(e){let t=e?.type||CQ;if(t===Mc){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function lk(e){return e.type===Mc&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function uk(e){return e.type===tw}function jRe(e){let t=Qt(qC(e.x),to),r=Qt(qC(e.y),to);return Ms([new Uint8Array([4]),t,r])}function UQ(e,t){let[r,n,o]=e.split("."),s=Qt(qC(o),to);if(s.length!==64)throw new Error("Invalid signature length");let i=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=o8(c),d=jRe(t);if(!_Y.verify(Ms([i,a]),u,d))throw new Error("Invalid signature");return Hl(e).payload}var qRe="irn";function Z8(e){return e?.relay||{protocol:qRe}}function M1(e){let t=kC[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function WRe(e,t="-"){let r={},n="relay"+t;return Object.keys(e).forEach(o=>{if(o.startsWith(n)){let s=o.replace(n,""),i=e[o];r[s]=i}}),r}function dk(e){if(!e.includes("wc:")){let u=fQ(e);u?.includes("wc:")&&(e=u)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;let t=e.indexOf(":"),r=e.indexOf("?")!==-1?e.indexOf("?"):void 0,n=e.substring(0,t),o=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",i=new URLSearchParams(s),a=Object.fromEntries(i.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:KRe(o[0]),version:parseInt(o[1],10),symKey:a.symKey,relay:WRe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function KRe(e){return e.startsWith("//")?e.substring(2):e}function ZRe(e,t="-"){let r="relay",n={};return Object.keys(e).forEach(o=>{let s=o,i=r+t+s;e[s]&&(n[i]=e[s])}),n}function fk(e){let t=new URLSearchParams,r={...ZRe(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(r).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!==void 0&&t.append(n,String(o))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function G8(e,t,r){return`${e}?wc_ev=${r}&topic=${t}`}function ow(e){let t=[];return e.forEach(r=>{let[n,o]=r.split(":");t.push(`${n}:${o}`)}),t}function pk(e){let t=[];return Object.values(e).forEach(r=>{t.push(...ow(r.accounts))}),[...new Set(t)]}function DQ(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.methods)}),[...new Set(t)]}function LQ(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.events)}),[...new Set(t)]}function GRe(e,t){let r=[];return Object.values(e).forEach(n=>{ow(n.accounts).includes(t)&&r.push(...n.methods)}),r}function YRe(e,t){let r=[];return Object.values(e).forEach(n=>{ow(n.accounts).includes(t)&&r.push(...n.events)}),r}function Y8(e){return e.includes(":")}function H1(e){return Y8(e)?e.split(":")[0]:e}function JJ(e){let t={};if(!Ka(e))return t;for(let[r,n]of Object.entries(e)){let o=Y8(r)?[r]:n.chains,s=n.methods||[],i=n.events||[],a=H1(r);t[a]={...t[a],chains:Uc(o,t[a]?.chains),methods:Uc(s,t[a]?.methods),events:Uc(i,t[a]?.events)}}return t}function JRe(e){let t={};return e?.forEach(r=>{let[n,o]=r.split(":");t[n]||(t[n]={accounts:[],chains:[],events:[],methods:[]}),t[n].accounts.push(r),t[n].chains?.push(`${n}:${o}`)}),t}function hk(e,t){t=t.map(n=>n.replace("did:pkh:",""));let r=JRe(t);for(let[n,o]of Object.entries(r))o.methods?o.methods=Uc(o.methods,e):o.methods=e,o.events=["chainChanged","accountsChanged"];return r}function MQ(e,t){let r=JJ(e),n=JJ(t),o={},s=Object.keys(r).concat(Object.keys(n));for(let i of s)o[i]={chains:Uc(r[i]?.chains,n[i]?.chains),methods:Uc(r[i]?.methods,n[i]?.methods),events:Uc(r[i]?.events,n[i]?.events)};return o}function zs(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function Ka(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function In(e){return typeof e>"u"}function gn(e,t){return t&&In(e)?!0:typeof e=="string"&&!!e.trim().length}function mk(e,t){return t&&In(e)?!0:typeof e=="number"&&!isNaN(e)}function HQ(e,t){let{requiredNamespaces:r}=t,n=Object.keys(e.namespaces),o=Object.keys(r),s=!0;return U1(o,n)?(n.forEach(i=>{let{accounts:a,methods:c,events:u}=e.namespaces[i],d=ow(a),f=r[i];(!U1(rQ(i,f),d)||!U1(f.methods,c)||!U1(f.events,u))&&(s=!1)}),s):!1}function WC(e){return gn(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function QRe(e){if(gn(e,!1)&&e.includes(":")){let t=e.split(":");if(t.length===3){let r=t[0]+":"+t[1];return!!t[2]&&WC(r)}}return!1}function $Q(e){function t(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(gn(e,!1)){if(t(e))return!0;let r=fQ(e);return t(r)}}catch{}return!1}function FQ(e){return e?.proposer?.publicKey}function zQ(e){return e?.topic}function VQ(e,t){let r=null;return gn(e?.publicKey,!1)||(r=Se("MISSING_OR_INVALID",`${t} controller public key should be a string`)),r}function QJ(e){let t=!0;return zs(e)?e.length&&(t=e.every(r=>gn(r,!1))):t=!1,t}function XRe(e,t,r){let n=null;return zs(t)&&t.length?t.forEach(o=>{n||WC(o)||(n=Sr("UNSUPPORTED_CHAINS",`${r}, chain ${o} should be a string and conform to "namespace:chainId" format`))}):WC(e)||(n=Sr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function eOe(e,t,r){let n=null;return Object.entries(e).forEach(([o,s])=>{if(n)return;let i=XRe(o,rQ(o,s),`${t} ${r}`);i&&(n=i)}),n}function tOe(e,t){let r=null;return zs(e)?e.forEach(n=>{r||QRe(n)||(r=Sr("UNSUPPORTED_ACCOUNTS",`${t}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=Sr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function rOe(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=tOe(n?.accounts,`${t} namespace`);o&&(r=o)}),r}function nOe(e,t){let r=null;return QJ(e?.methods)?QJ(e?.events)||(r=Sr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Sr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}function jQ(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=nOe(n,`${t}, namespace`);o&&(r=o)}),r}function qQ(e,t,r){let n=null;if(e&&Ka(e)){let o=jQ(e,t);o&&(n=o);let s=eOe(e,t,r);s&&(n=s)}else n=Se("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return n}function eS(e,t){let r=null;if(e&&Ka(e)){let n=jQ(e,t);n&&(r=n);let o=rOe(e,t);o&&(r=o)}else r=Se("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function gk(e){return gn(e.protocol,!0)}function WQ(e,t){let r=!1;return t&&!e?r=!0:e&&zs(e)&&e.length&&e.forEach(n=>{r=gk(n)}),r}function KQ(e){return typeof e=="number"}function as(e){return typeof e<"u"&&typeof e!==null}function ZQ(e){return!(!e||typeof e!="object"||!e.code||!mk(e.code,!1)||!e.message||!gn(e.message,!1))}function GQ(e){return!(In(e)||!gn(e.method,!1))}function YQ(e){return!(In(e)||In(e.result)&&In(e.error)||!mk(e.id,!1)||!gn(e.jsonrpc,!1))}function JQ(e){return!(In(e)||!gn(e.name,!1))}function yk(e,t){return!(!WC(t)||!pk(e).includes(t))}function QQ(e,t,r){return gn(r,!1)?GRe(e,t).includes(r):!1}function XQ(e,t,r){return gn(r,!1)?YRe(e,t).includes(r):!1}function wk(e,t,r){let n=null,o=oOe(e),s=sOe(t),i=Object.keys(o),a=Object.keys(s),c=XJ(Object.keys(e)),u=XJ(Object.keys(t)),d=c.filter(f=>!u.includes(f));return d.length&&(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. + Required: ${d.toString()} + Received: ${Object.keys(t).toString()}`)),U1(i,a)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. + Required: ${i.toString()} + Approved: ${a.toString()}`)),Object.keys(t).forEach(f=>{if(!f.includes(":")||n)return;let p=ow(t[f].accounts);p.includes(f)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${f} + Required: ${f} + Approved: ${p.toString()}`))}),i.forEach(f=>{n||(U1(o[f].methods,s[f].methods)?U1(o[f].events,s[f].events)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function oOe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:e[r].chains?.forEach(n=>{t[n]={methods:e[r].methods,events:e[r].events}})}),t}function XJ(e){return[...new Set(e.map(t=>t.includes(":")?t.split(":")[0]:t))]}function sOe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:ow(e[r].accounts)?.forEach(n=>{t[n]={accounts:e[r].accounts.filter(o=>o.includes(`${n}:`)),methods:e[r].methods,events:e[r].events}})}),t}function eX(e,t){return mk(e,!1)&&e<=t.max&&e>=t.min}function bk(){let e=V8();return new Promise(t=>{switch(e){case bi.browser:t(iOe());break;case bi.reactNative:t(aOe());break;case bi.node:t(cOe());break;default:t(!0)}})}function iOe(){return L1()&&navigator?.onLine}async function aOe(){return gf()&&typeof global<"u"&&global?.NetInfo?(await global?.NetInfo.fetch())?.isConnected:!0}function cOe(){return!0}function tX(e){switch(V8()){case bi.browser:lOe(e);break;case bi.reactNative:uOe(e);break;case bi.node:break}}function lOe(e){!gf()&&L1()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}function uOe(e){gf()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener(t=>e(t?.isConnected))}function rX(){return L1()&&(0,Dc.getDocument)()?(0,Dc.getDocument)()?.visibilityState==="visible":!0}var ZB={},wh=class{static get(t){return ZB[t]}static set(t,r){ZB[t]=r}static delete(t){delete ZB[t]}};function dOe(e){let t=B2.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}function fOe({publicKey:e,signature:t,payload:r}){let n=KC(r.method),o=128|parseInt(r.version?.toString()||"4"),s=mOe(r.address),i=r.era==="00"?new Uint8Array([0]):KC(r.era);if(i.length!==1&&i.length!==2)throw new Error("Invalid era length");let a=parseInt(r.nonce,16),c=new Uint8Array([a&255,a>>8&255]),u=BigInt(`0x${hOe(r.tip)}`),d=yOe(u),f=new Uint8Array([0,...e,s,...t,...i,...c,...d,...n]),p=gOe(f.length+1);return new Uint8Array([...p,o,...f])}function pOe(e){let t=KC(e),r=(0,tQ.blake2b)(t,void 0,32);return"0x"+Ut(r,"base16")}function KC(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(t=>parseInt(t,16)))}function hOe(e){return e.startsWith("0x")?e.slice(2):e}function mOe(e){let t=B2.decode(e)[0];return t===42?0:t===60?2:1}function gOe(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([t&255,t>>8&255])}else if(e<1<<30){let t=e<<2|2;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function yOe(e){if(e<1n<<6n)return new Uint8Array([Number(e<<2n)]);if(e<1n<<14n){let t=e<<2n|0x01n;return new Uint8Array([Number(t&0xffn),Number(t>>8n&0xffn)])}else if(e<1n<<30n){let t=e<<2n|0x02n;return new Uint8Array([Number(t&0xffn),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}else throw new Error("BigInt compact encoding not supported > 2^30")}function nX(e){let t=KC(e.signature),r=dOe(e.transaction.address),n=fOe({publicKey:r,signature:t,payload:e.transaction}),o=Ut(n,"base16");return pOe(o)}function sw({logger:e,name:t}){let r=typeof e=="string"?Fl({opts:{level:e,name:t}}).logger:e;return r.level=typeof e=="string"?e:e.level,r}l();l();var QS=Ht(ks(),1);l();var xf=Ht(ks(),1);vk();Rk();gh();l();tS();var CX=Ht(ks()),oS=class extends yo{constructor(t){super(),this.opts=t,this.protocol="wc",this.version=2}};var sS=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r,this.records=new Map}},iS=class{constructor(t,r){this.logger=t,this.core=r}},aS=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},cS=class extends yo{constructor(t){super()}},lS=class{constructor(t,r,n,o){this.core=t,this.logger=r,this.name=n}};var uS=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}};var dS=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r}};var fS=class{constructor(t,r,n){this.core=t,this.logger=r,this.store=n}},pS=class{constructor(t,r){this.projectId=t,this.logger=r}},hS=class{constructor(t,r,n){this.core=t,this.logger=r,this.telemetryEnabled=n}};var mS=class{constructor(t){this.opts=t,this.protocol="wc",this.version=2}};var gS=class{constructor(t){this.client=t}};var Ge=Ht(jd(),1);R1();B1();B1();BO();I8();cw();$c();Hk();l();l();l();function XX(e){return Number.isSafeInteger(e)&&e>=0}function eee(e){return e!=null&&typeof e!="function"&&XX(e.length)}l();function tee(e){return e==="__proto__"}l();function uw(e){return e==null||typeof e!="object"&&typeof e!="function"}l();function ree(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}l();l();function F1(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}l();function bf(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}l();var PS="[object RegExp]",dw="[object String]",fw="[object Number]",pw="[object Boolean]",z1="[object Arguments]",NS="[object Symbol]",RS="[object Date]",OS="[object Map]",BS="[object Set]",kS="[object Array]",nee="[object Function]",US="[object ArrayBuffer]",Ah="[object Object]",oee="[object Error]",DS="[object DataView]",LS="[object Uint8Array]",MS="[object Uint8ClampedArray]",HS="[object Uint16Array]",$S="[object Uint32Array]",see="[object BigUint64Array]",FS="[object Int8Array]",zS="[object Int16Array]",VS="[object Int32Array]",iee="[object BigInt64Array]",jS="[object Float32Array]",qS="[object Float64Array]";l();function hw(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function aee(e,t){return mw(e,void 0,e,new Map,t)}function mw(e,t,r,n=new Map,o=void 0){let s=o?.(e,t,r,n);if(s!==void 0)return s;if(uw(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){let i=new Array(e.length);n.set(e,i);for(let a=0;a{let i=t?.(r,n,o,s);if(i!==void 0)return i;if(typeof e=="object"){if(bf(e)===Ah&&typeof e.constructor!="function"){let a={};return s.set(e,a),Za(a,e,o,s),a}switch(Object.prototype.toString.call(e)){case fw:case dw:case pw:{let a=new e.constructor(e?.valueOf());return Za(a,e),a}case z1:{let a={};return Za(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}}})}function $k(e){return cee(e)}l();function Fk(e){return e!==null&&typeof e=="object"&&bf(e)==="[object Arguments]"}l();l();function s4(e){return typeof e=="object"&&e!==null}function lee(e){return s4(e)&&eee(e)}l();l();l();function zk(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function uee(e,t,r){return i4(e,t,void 0,void 0,void 0,void 0,r)}function i4(e,t,r,n,o,s,i){let a=i(e,t,r,n,o,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return a4(e,t,s,i)}return a4(e,t,s,i)}function a4(e,t,r,n){if(Object.is(e,t))return!0;let o=bf(e),s=bf(t);if(o===z1&&(o=Ah),s===z1&&(s=Ah),o!==s)return!1;switch(o){case dw:return e.toString()===t.toString();case fw:{let c=e.valueOf(),u=t.valueOf();return ree(c,u)}case pw:case RS:case NS:return Object.is(e.valueOf(),t.valueOf());case PS:return e.source===t.source&&e.flags===t.flags;case nee:return e===t}r=r??new Map;let i=r.get(e),a=r.get(t);if(i!=null&&a!=null)return i===t;r.set(e,t),r.set(t,e);try{switch(o){case OS:{if(e.size!==t.size)return!1;for(let[c,u]of e.entries())if(!t.has(c)||!i4(u,t.get(c),c,e,t,r,n))return!1;return!0}case BS:{if(e.size!==t.size)return!1;let c=Array.from(e.values()),u=Array.from(t.values());for(let d=0;di4(f,h,void 0,e,t,r,n));if(p===-1)return!1;u.splice(p,1)}return!0}case kS:case LS:case MS:case HS:case $S:case see:case FS:case zS:case VS:case iee:case jS:case qS:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,o)=>{this.isInitialized(),this.keychain.set(n,o),await this.persist()},this.get=n=>{this.isInitialized();let o=this.keychain.get(n);if(typeof o>"u"){let{message:s}=Se("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return o},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=t,this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,ZC(t))}async getKeyChain(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?GC(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Kk=class{constructor(t,r,n){this.core=t,this.logger=r,this.name=rBe,this.randomSessionIdentifier=XC(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=o=>(this.isInitialized(),this.keychain.has(o)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;let o=await this.getClientSeed(),s=J2(o),i=U8(s.publicKey);return this.clientId=i,i},this.generateKeyPair=()=>{this.isInitialized();let o=SQ();return this.setPrivateKey(o.publicKey,o.privateKey)},this.signJWT=async o=>{this.isInitialized();let s=await this.getClientSeed(),i=J2(s),a=this.randomSessionIdentifier;return await BC(a,o,nBe,i)},this.generateSharedKey=(o,s,i)=>{this.isInitialized();let a=this.getPrivateKey(o),c=IQ(a,s);return this.setSymKey(c,i)},this.setSymKey=async(o,s)=>{this.isInitialized();let i=s||rw(o);return await this.keychain.set(i,o),i},this.deleteKeyPair=async o=>{this.isInitialized(),await this.keychain.del(o)},this.deleteSymKey=async o=>{this.isInitialized(),await this.keychain.del(o)},this.encode=async(o,s,i)=>{this.isInitialized();let a=ck(i),c=yi(s);if(uk(a))return RQ(c,i?.encoding);if(lk(a)){let p=a.senderPublicKey,h=a.receiverPublicKey;o=await this.generateSharedKey(p,h)}let u=this.getSymKey(o),{type:d,senderPublicKey:f}=a;return PQ({type:d,symKey:u,message:c,senderPublicKey:f,encoding:i?.encoding})},this.decode=async(o,s,i)=>{this.isInitialized();let a=kQ(s,i);if(uk(a)){let c=OQ(s,i?.encoding);return Fs(c)}if(lk(a)){let c=a.receiverPublicKey,u=a.senderPublicKey;o=await this.generateSharedKey(c,u)}try{let c=this.getSymKey(o),u=NQ({symKey:c,encoded:s,encoding:i?.encoding});return Fs(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(o,s=to)=>{let i=nw({encoded:o,encoding:s});return yh(i.type)},this.getPayloadSenderPublicKey=(o,s=to)=>{let i=nw({encoded:o,encoding:s});return i.senderPublicKey?Ut(i.senderPublicKey,is):void 0},this.core=t,this.logger=Cr(r,this.name),this.keychain=n||new Wk(this.core,this.logger)}get context(){return sr(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(pee)}catch{t=XC(),await this.keychain.set(pee,t)}return Qt(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Zk=class extends iS{constructor(t,r){super(t,r),this.logger=t,this.core=r,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name=iBe,this.version=aBe,this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);let o=await this.getRelayerMessagesWithoutClientAck();typeof o<"u"&&(this.messagesWithoutClientAck=o),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,o,s)=>{this.isInitialized();let i=xi(o),a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[i]<"u")return i;if(a[i]=o,this.messages.set(n,a),s===YS.inbound){let c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,{...c,[i]:o})}return await this.persist(),i},this.get=n=>{this.isInitialized();let o=this.messages.get(n);return typeof o>"u"&&(o={}),o},this.getWithoutAck=n=>{this.isInitialized();let o={};for(let s of n){let i=this.messagesWithoutClientAck.get(s)||{};o[s]=Object.values(i)}return o},this.has=(n,o)=>{this.isInitialized();let s=this.get(n),i=xi(o);return typeof s[i]<"u"},this.ack=async(n,o)=>{this.isInitialized();let s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;let i=xi(o);delete s[i],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()},this.del=async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()},this.logger=Cr(t,this.name),this.core=r}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,ZC(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,ZC(t))}async getRelayerMessages(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?GC(t):void 0}async getRelayerMessagesWithoutClientAck(){let t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?GC(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Gk=class extends aS{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.events=new xf.EventEmitter,this.name=lBe,this.queue=new Map,this.publishTimeout=(0,Ge.toMiliseconds)(Ge.ONE_MINUTE),this.initialPublishTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(n,o,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:o,opts:s}});let i=s?.ttl||cBe,a=s?.prompt||!1,c=s?.tag||0,u=s?.id||_n().toString(),d=M1(Z8().protocol),f={id:u,method:s?.publishMethod||d.publish,params:{topic:n,message:o,ttl:i,prompt:a,tag:c,attestation:s?.attestation,...s?.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${c}`;try{In(f.params?.prompt)&&delete f.params?.prompt,In(f.params?.tag)&&delete f.params?.tag;let h=new Promise(async y=>{let w=({id:v})=>{f.id?.toString()===v.toString()&&(this.removeRequestFromQueue(v),this.relayer.events.removeListener(yn.publish,w),y())};this.relayer.events.on(yn.publish,w);let x=Wa(new Promise((v,T)=>{this.rpcPublish(f,s).then(v).catch(E=>{this.logger.warn(E,E?.message),T(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${c}`);try{await x,this.events.removeListener(yn.publish,w)}catch(v){this.queue.set(u,{request:f,opts:s,attempt:1}),this.logger.warn(v,v?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:n,message:o,opts:s}}),await Wa(h,this.publishTimeout,p)}catch(h){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(h),s?.internal?.throwOnFailedPublish)throw h}finally{this.queue.delete(u)}},this.publishCustom=async n=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});let{payload:o,opts:s={}}=n,{attestation:i,tvf:a,publishMethod:c,prompt:u,tag:d,ttl:f=Ge.FIVE_MINUTES}=s,p=s.id||_n().toString(),h=M1(Z8().protocol),y=c||h.publish,w={id:p,method:y,params:{...o,ttl:f,prompt:u,tag:d,attestation:i,...a}},x=`Failed to publish custom payload, please try again. id:${p} tag:${d}`;try{In(w.params?.prompt)&&delete w.params?.prompt,In(w.params?.tag)&&delete w.params?.tag;let v=new Promise(async T=>{let E=({id:_})=>{w.id?.toString()===_.toString()&&(this.removeRequestFromQueue(_),this.relayer.events.removeListener(yn.publish,E),T())};this.relayer.events.on(yn.publish,E);let S=Wa(new Promise((_,O)=>{this.rpcPublish(w,s).then(_).catch(D=>{this.logger.warn(D,D?.message),O(D)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${p} tag:${d}`);try{await S,this.events.removeListener(yn.publish,E)}catch(_){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(_,_?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,payload:o,opts:s}}),await Wa(v,this.publishTimeout,x)}catch(v){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(v),s?.internal?.throwOnFailedPublish)throw v}finally{this.queue.delete(p)}},this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.relayer=t,this.logger=Cr(r,this.name),this.registerEventListeners()}get context(){return sr(this.logger)}async rpcPublish(t,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});let n=await this.relayer.request(t);return this.relayer.events.emit(yn.publish,{...t,...r}),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,r)=>{let n=t.attempt+1;this.queue.set(r,{...t,attempt:n}),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${t.request.params?.tag}, attempt: ${n}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(yn.connection_stalled);return}this.checkQueue()}),this.relayer.on(yn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}},Yk=class{constructor(){this.map=new Map,this.set=(t,r)=>{let n=this.get(t);this.exists(t,r)||this.map.set(t,[...n,r])},this.get=t=>this.map.get(t)||[],this.exists=(t,r)=>this.get(t).includes(r),this.delete=(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;let n=this.get(t);if(!this.exists(t,r))return;let o=n.filter(s=>s!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Jk=class extends uS{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.subscriptions=new Map,this.topicMap=new Yk,this.events=new xf.EventEmitter,this.name=gBe,this.version=yBe,this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.subscribeTimeout=(0,Ge.toMiliseconds)(Ge.ONE_MINUTE),this.initialSubscribeTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(n,o)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}});try{let s=Z8(o),i={topic:n,relay:s,transportType:o?.transportType};o?.internal?.skipSubscribe||this.pending.set(n,i);let a=await this.rpcSubscribe(n,s,o);return typeof a=="string"&&(this.onSubscribe(a,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,o)=>{this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(n,o.id,o):await this.unsubscribeByTopic(n,o)},this.isSubscribed=n=>new Promise(o=>{o(this.topicMap.topics.includes(n))}),this.isKnownTopic=n=>new Promise(o=>{o(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))}),this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;let n=[];this.pending.forEach(o=>{n.push(o)}),await this.batchSubscribe(n)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(Vs.pulse,async()=>{await this.checkPending()}),this.events.on(fa.created,async n=>{let o=fa.created;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()}),this.events.on(fa.deleted,async n=>{let o=fa.deleted;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()})},this.relayer=t,this.logger=Cr(r,this.name),this.clientId=""}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,r){let n=!1;try{n=this.getSubscription(t).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){let n=this.topicMap.get(t);await Promise.all(n.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}});try{let o=Sr("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,o);let s=Z8(n);await this.restartToComplete({topic:t,id:r,relay:s}),await this.rpcUnsubscribe(t,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r,n){let o=await this.getSubscriptionId(t);if(n?.internal?.skipSubscribe)return o;(!n||n?.transportType===Dr.relay)&&await this.restartToComplete({topic:t,id:t,relay:r});let s={method:M1(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let i=n?.internal?.throwOnFailedPublish;try{if(n?.transportType===Dr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},(0,Ge.toMiliseconds)(Ge.ONE_SECOND)),o;let a=new Promise(async u=>{let d=f=>{f.topic===t&&(this.events.removeListener(fa.created,d),u(f.id))};this.events.on(fa.created,d);try{let f=await Wa(new Promise((p,h)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),h(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(fa.created,d),u(f)}catch{}}),c=await Wa(a,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!c&&i)throw new Error(`Subscribing to ${t} failed, please try again`);return c?o:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(yn.connection_stalled),i)throw a}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;let r=t[0].relay,n={method:M1(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await Wa(new Promise((o,s)=>{this.relayer.request(n).then(o).catch(i=>{this.logger.warn(i),s(i)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(yn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;let r=t[0].relay,n={method:M1(r.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let o;try{o=await await Wa(new Promise((s,i)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),i(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(yn.connection_stalled)}return o}rpcUnsubscribe(t,r,n){let o={method:M1(n.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,{...r,id:t}),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,{...r}),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,n),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r)}addSubscription(t,r){this.subscriptions.set(t,{...r}),this.topicMap.set(r.topic,t),this.events.emit(fa.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});let r=this.subscriptions.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});let n=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(n.topic,t),this.events.emit(fa.deleted,{...n,reason:r})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(fa.sync)}async onRestart(){if(this.cached.length){let t=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n"u"||!t.length)return;if(this.subscriptions.size&&!t.every(r=>r.topic===this.subscriptions.get(r.id)?.topic)){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(r=>{this.pending.set(r.topic,r)});return}this.onBatchSubscribe(await Promise.all(t.map(async r=>({...r,id:await this.getSubscriptionId(r.topic)}))))}}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);let r=await this.rpcBatchFetchMessages(t);r&&r.messages&&(await pQ((0,Ge.toMiliseconds)(Ge.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return xi(t+await this.getClientId())}},Qk=class extends cS{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new xf.EventEmitter,this.name=dBe,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=(0,Ge.toMiliseconds)(Ge.THIRTY_SECONDS+Ge.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*2),this.stalledRestartMaxInterval=(0,Ge.toMiliseconds)(Ge.THIRTY_SECONDS),this.request=async r=>{this.logger.debug("Publishing Request Payload");let n=r.id||_n().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:r.method,topic:r.params?.topic},"relayer.request - publishing...");let o=`${n}:${r.params?.tag||""}`;this.requestsInFlight.push(o);let s=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(i=>i!==o),s}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}},this.resetPingTimeout=()=>{z8()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(r){this.logger.warn(r,r?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(yn.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(yn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(n=>this.logger.warn(n))},this.registerProviderListeners=()=>{this.provider.on(Ga.payload,this.onPayloadHandler),this.provider.on(Ga.connect,this.onConnectHandler),this.provider.on(Ga.disconnect,this.onDisconnectHandler),this.provider.on(Ga.error,this.onProviderErrorHandler)},this.core=t.core,this.logger=sw({logger:t.logger??uBe,name:this.name}),this.messages=new Zk(this.logger,t.core),this.subscriber=new Jk(this,this.logger),this.publisher=new Gk(this,this.logger),this.projectId=t.projectId,this.relayUrl=t.relayUrl||wee,nQ()?this.packageName=YB():oQ()&&(this.bundleId=YB()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return sr(this.logger)}get connected(){return this.provider?.connection?.socket?.readyState===1}get connecting(){return this.provider?.connection?.socket?.readyState===0||this.connectPromise!==void 0}async publish(t,r,n){this.isInitialized(),await this.publisher.publish(t,r,n),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now(),transportType:Dr.relay},YS.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,r){this.isInitialized(),(!r?.transportType||r?.transportType==="relay")&&await this.toEstablishConnection();let n=r?.internal?.throwOnFailedPublish??!0,o=this.subscriber.topicMap.get(t)?.[0]||"",s,i=a=>{a.topic===t&&(this.subscriber.off(fa.created,i),s())};return await Promise.all([new Promise(a=>{s=a,this.subscriber.on(fa.created,i)}),new Promise((a,c)=>{this.subscriber.subscribe(t,{internal:{throwOnFailedPublish:n},...r}).then(u=>{o=u||o,a()}).catch(u=>{n?c(u):a()})})]),o}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Wa(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=this.connect(t).finally(()=>{this.connectPromise=void 0}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await bk())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}let r=t.sort((n,o)=>n.publishedAt-o.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(let n of r)try{await this.onMessageEvent(n)}catch(o){this.logger.warn(o,"Error while processing batch message event: "+o?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(t,r){let{topic:n}=t;if(!r.sessionExists){let o=ln(Ge.FIVE_MINUTES),s={topic:n,expiry:o,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(yn.message,t),await this.recordMessageEvent(t,YS.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let r=1;try{for(;r<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise((n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ga.disconnect,s),Wa(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>n()).catch(o).finally(()=>{this.provider.off(Ga.disconnect,s),clearTimeout(this.reconnectTimeout)})}),await new Promise((n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ga.disconnect,s),this.subscriber.start().then(n).catch(o).finally(()=>{this.provider.off(Ga.disconnect,s)})}),this.hasExperiencedNetworkDisruption=!1}catch(n){await this.subscriber.stop();let o=n;this.logger.warn({},o.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,(0,Ge.toMiliseconds)(r*1))),r++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(z8())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(t){this.logger.warn(t,t?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await Wa(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}let t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new da(new lw(iQ({sdkVersion:qk,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,r){let{topic:n,message:o}=t;await this.messages.set(n,o,r)}async shouldIgnoreMessageEvent(t){let{topic:r,message:n}=t;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;let o=this.messages.has(r,n);return o&&this.logger.warn(`Ignoring duplicate message: ${n}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Hc(t)){if(!t.method.endsWith(fBe))return;let r=t.params,{topic:n,message:o,publishedAt:s,attestation:i}=r.data,a={topic:n,message:o,publishedAt:s,transportType:Dr.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:r.id,...a}),this.events.emit(r.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else ua(t)&&this.events.emit(yn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,YS.inbound),this.events.emit(yn.message,t))}async acknowledgePayload(t){let r=bo(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Ga.payload,this.onPayloadHandler),this.provider.off(Ga.connect,this.onConnectHandler),this.provider.off(Ga.disconnect,this.onDisconnectHandler),this.provider.off(Ga.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await bk();tX(async r=>{t!==r&&(t=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vs.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&rX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}}),this.events.on(yn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;let r=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${r?` in ${r}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(n){this.logger.error(n,n?.message)}finally{this.stalledRestartInProgress=!1}},r)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(yn.disconnect),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(t){this.logger.warn(t,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed){this.reconnectInProgress=!1;return}this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,Ge.toMiliseconds)(pBe))}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}},jl=class extends lS{constructor(t,r,n,o=Vl,s=void 0){super(t,r,n,o),this.core=t,this.logger=r,this.name=n,this.map=new Map,this.version=hBe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>{this.getKey&&i!==null&&!In(i)?this.map.set(this.getKey(i),i):FQ(i)?this.map.set(i.id,i):zQ(i)&&this.map.set(i.topic,i)}),this.cached=[],this.initialized=!0)},this.set=async(i,a)=>{this.isInitialized(),this.map.has(i)?await this.update(i,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:i,value:a}),this.map.set(i,a),await this.persist())},this.get=i=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:i}),this.getData(i)),this.getAll=i=>(this.isInitialized(),i?this.values.filter(a=>Object.keys(i).every(c=>Vk(a[c],i[c]))):this.values),this.update=async(i,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:i,update:a});let c={...this.getData(i),...a};this.map.set(i,c),await this.persist()},this.delete=async(i,a)=>{this.isInitialized(),this.map.has(i)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:i,reason:a}),this.map.delete(i),this.addToRecentlyDeleted(i),await this.persist())},this.logger=Cr(r,this.name),this.storagePrefix=o,this.getKey=s}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){let r=this.map.get(t);if(!r){if(this.recentlyDeleted.includes(t)){let{message:o}=Se("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(o),new Error(o)}let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Xk=class{constructor(t,r){this.core=t,this.logger=r,this.name=wBe,this.version=bBe,this.events=new xf.default,this.initialized=!1,this.storagePrefix=Vl,this.ignoredPayloadTypes=[Mc],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let o=XC(),s=await this.core.crypto.setSymKey(o),i=ln(Ge.FIVE_MINUTES),a={protocol:sU},c={topic:s,expiry:i,relay:a,active:!1,methods:n?.methods},u=fk({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:o,relay:a,expiryTimestamp:i,methods:n?.methods});return this.events.emit(Ch.create,c),this.core.expirer.set(s,i),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}},this.pair=async n=>{this.isInitialized();let o=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[zc.pairing_started]}});this.isValidPair(n,o);let{topic:s,symKey:i,relay:a,expiryTimestamp:c,methods:u}=dk(n.uri);o.props.properties.topic=s,o.addTrace(zc.pairing_uri_validation_success),o.addTrace(zc.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(s)){if(d=this.pairings.get(s),o.addTrace(zc.existing_pairing),d.active)throw o.setError(zl.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);o.addTrace(zc.pairing_not_expired)}let f=c||ln(Ge.FIVE_MINUTES),p={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,p),o.addTrace(zc.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Ch.create,p),o.addTrace(zc.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),o.addTrace(zc.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{o.setError(zl.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw o.setError(zl.subscribe_pairing_topic_failure),h}return o.addTrace(zc.subscribe_pairing_topic_success),p},this.activate=async({topic:n})=>{this.isInitialized();let o=ln(Ge.FIVE_MINUTES);this.core.expirer.set(n,o),await this.pairings.update(n,{active:!0,expiry:o})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:o}=n;if(this.pairings.keys.includes(o)){let s=await this.sendRequest(o,"wc_pairingPing",{}),{done:i,resolve:a,reject:c}=yf();this.events.once(ir("pairing_ping",s),({error:u})=>{u?c(u):a()}),await i()}},this.updateExpiry=async({topic:n,expiry:o})=>{this.isInitialized(),await this.pairings.update(n,{expiry:o})},this.updateMetadata=async({topic:n,metadata:o})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:o})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:o}=n;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",Sr("USER_DISCONNECTED")),await this.deletePairing(o))},this.formatUriFromPairing=n=>{this.isInitialized();let{topic:o,relay:s,expiry:i,methods:a}=n,c=this.core.crypto.keychain.get(o);return fk({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:c,relay:s,expiryTimestamp:i,methods:a})},this.sendRequest=async(n,o,s)=>{let i=dr(o,s),a=await this.core.crypto.encode(n,i),c=c4[o].req;return this.core.history.set(n,i),this.core.relayer.publish(n,a,c),i.id},this.sendResult=async(n,o,s)=>{let i=bo(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=c4[c].res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)},this.sendError=async(n,o,s)=>{let i=la(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=c4[c]?c4[c].res:c4.unregistered_method.res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)},this.deletePairing=async(n,o)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Sr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),o?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(o=>ca(o.expiry));await Promise.all(n.map(o=>this.deletePairing(o.topic)))},this.onRelayEventRequest=async n=>{let{topic:o,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(o,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(o,s);default:return await this.onUnknownRpcMethodRequest(o,s)}},this.onRelayEventResponse=async n=>{let{topic:o,payload:s}=n,i=(await this.core.history.get(o,s.id)).request.method;return i==="wc_pairingPing"?this.onPairingPingResponse(o,s):this.onUnknownRpcMethodResponse(i)},this.onPairingPingRequest=async(n,o)=>{let{id:s}=o;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Ch.ping,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}},this.onPairingPingResponse=(n,o)=>{let{id:s}=o;setTimeout(()=>{Jr(o)?this.events.emit(ir("pairing_ping",s),{}):Ir(o)&&this.events.emit(ir("pairing_ping",s),{error:o.error})},500)},this.onPairingDeleteRequest=async(n,o)=>{let{id:s}=o;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Ch.delete,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}},this.onUnknownRpcMethodRequest=async(n,o)=>{let{id:s,method:i}=o;try{if(this.registeredMethods.includes(i))return;let a=Sr("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Sr("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=(n,o)=>{if(!as(n)){let{message:i}=Se("MISSING_OR_INVALID",`pair() params: ${n}`);throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(!$Q(n.uri)){let{message:i}=Se("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw o.setError(zl.malformed_pairing_uri),new Error(i)}let s=dk(n?.uri);if(!s?.relay?.protocol){let{message:i}=Se("MISSING_OR_INVALID","pair() uri#relay-protocol");throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(!s?.symKey){let{message:i}=Se("MISSING_OR_INVALID","pair() uri#symKey");throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(s?.expiryTimestamp&&(0,Ge.toMiliseconds)(s?.expiryTimestamp){if(!as(n)){let{message:s}=Se("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)},this.isValidDisconnect=async n=>{if(!as(n)){let{message:s}=Se("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)},this.isValidPairingTopic=async n=>{if(!gn(n,!1)){let{message:o}=Se("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(o)}if(!this.pairings.keys.includes(n)){let{message:o}=Se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(o)}if(ca(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:o}=Se("EXPIRED",`pairing topic: ${n}`);throw new Error(o)}},this.core=t,this.logger=Cr(r,this.name),this.pairings=new jl(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sr(this.logger)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(yn.message,async t=>{let{topic:r,message:n,transportType:o}=t;if(this.pairings.keys.includes(r)&&o!==Dr.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{let s=await this.core.crypto.decode(r,n);Hc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ua(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(pa.expired,async t=>{let{topic:r}=YC(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ch.expire,{topic:r}))})}},eU=class extends sS{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.records=new Map,this.events=new xf.EventEmitter,this.name=xBe,this.version=vBe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,o,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:o,chainId:s}),this.records.has(o.id))return;let i={id:o.id,topic:n,request:{method:o.method,params:o.params||null},chainId:s,expiry:ln(Ge.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Fc.created,i)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let o=await this.getRecord(n.id);typeof o.response<"u"||(o.response=Ir(n)?{error:n.error}:{result:n.result},this.records.set(o.id,o),this.persist(),this.events.emit(Fc.updated,o))},this.get=async(n,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:o}),await this.getRecord(o)),this.delete=(n,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(s=>{if(s.topic===n){if(typeof o<"u"&&s.id!==o)return;this.records.delete(s.id),this.events.emit(Fc.deleted,s)}}),this.persist()},this.exists=async(n,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===n:!1),this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(n)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();let r=this.records.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fc.sync)}async restore(){try{let t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(Fc.created,t=>{let r=Fc.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Fc.updated,t=>{let r=Fc.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Fc.deleted,t=>{let r=Fc.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.core.heartbeat.on(Vs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(r=>{(0,Ge.toMiliseconds)(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Fc.deleted,r,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},tU=class extends dS{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.expirations=new Map,this.events=new xf.EventEmitter,this.name=EBe,this.version=ABe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let o=this.formatTarget(n);return typeof this.getExpiration(o)<"u"}catch{return!1}},this.set=(n,o)=>{this.isInitialized();let s=this.formatTarget(n),i={target:s,expiry:o};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(pa.created,{target:s,expiration:i})},this.get=n=>{this.isInitialized();let o=this.formatTarget(n);return this.getExpiration(o)},this.del=n=>{if(this.isInitialized(),this.has(n)){let o=this.formatTarget(n),s=this.getExpiration(o);this.expirations.delete(o),this.events.emit(pa.deleted,{target:o,expiration:s})}},this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(t){if(typeof t=="string")return cQ(t);if(typeof t=="number")return lQ(t);let{message:r}=Se("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(pa.sync)}async restore(){try{let t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){let r=this.expirations.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(t,r){let{expiry:n}=r;(0,Ge.toMiliseconds)(n)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(pa.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Vs.pulse,()=>this.checkExpirations()),this.events.on(pa.created,t=>{let r=pa.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(pa.expired,t=>{let r=pa.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(pa.deleted,t=>{let r=pa.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},rU=class extends fS{constructor(t,r,n){super(t,r,n),this.core=t,this.logger=r,this.store=n,this.name=CBe,this.verifyUrlV3=IBe,this.storagePrefix=Vl,this.version=yee,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,Ge.toMiliseconds)(this.publicKey?.expiresAt){if(!L1()||this.isDevEnv)return;let s=window.location.origin,{id:i,decryptedId:a}=o,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${i}&decryptedId=${a}`;try{let u=(0,mee.getDocument)(),d=this.startAbortTimer(Ge.ONE_SECOND*5),f=await new Promise((p,h)=>{let y=()=>{window.removeEventListener("message",x),u.body.removeChild(w),h("attestation aborted")};this.abortController.signal.addEventListener("abort",y);let w=u.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});let x=v=>{if(v.data&&typeof v.data=="string")try{let T=JSON.parse(v.data);if(T.type==="verify_attestation"){if(Hl(T.attestation).payload.id!==i)return;clearInterval(d),u.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",x),p(T.attestation===null?"":T.attestation)}}catch(T){this.logger.warn(T)}};u.body.appendChild(w),window.addEventListener("message",x,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""},this.resolve=async o=>{if(this.isDevEnv)return"";let{attestationId:s,hash:i,encryptedId:a}=o;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Hl(s).payload.id!==a)return;let u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!i)return;let c=this.getVerifyUrl(o?.verifyUrl);return this.fetchAttestation(i,c)},this.fetchAttestation=async(o,s)=>{this.logger.debug(`resolving attestation: ${o} from url: ${s}`);let i=this.startAbortTimer(Ge.ONE_SECOND*5),a=await fetch(`${s}/attestation/${o}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),a.status===200?await a.json():void 0},this.getVerifyUrl=o=>{let s=o||gw;return TBe.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gw}`),s=gw),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let o=this.startAbortTimer(Ge.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(o),await s.json()}catch(o){this.logger.warn(o)}},this.persistPublicKey=async o=>{this.logger.debug(o,"persisting public key to local storage"),await this.store.setItem(this.storeKey,o),this.publicKey=o},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async o=>{let s=await this.getPublicKey();try{if(s)return this.validateAttestation(o,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(o,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{let i=await this.fetchPublicKey();i&&(await this.persistPublicKey(i),s(i))});let o=await this.fetchPromise;return this.fetchPromise=void 0,o},this.validateAttestation=(o,s)=>{let i=UQ(o,s.publicKey),a={hasExpired:(0,Ge.toMiliseconds)(i.exp)this.abortController.abort(),(0,Ge.toMiliseconds)(t))}},nU=class extends pS{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,this.context=_Be,this.registerDeviceToken=async n=>{let{clientId:o,token:s,notificationType:i,enableEncrypted:a=!1}=n,c=`${PBe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:i,token:s,always_raw:a})})},this.logger=Cr(r,this.context)}},oU=class extends hS{constructor(t,r,n=!0){super(t,r,n),this.core=t,this.logger=r,this.context=RBe,this.storagePrefix=Vl,this.storageVersion=NBe,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!j8())try{let o={eventId:ek(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:QB(this.core.relayer.protocol,this.core.relayer.version,qk)}}};await this.sendEvent([o])}catch(o){this.logger.warn(o)}},this.createEvent=o=>{let{event:s="ERROR",type:i="",properties:{topic:a,trace:c}}=o,u=ek(),d=this.core.projectId||"",f=Date.now(),p={eventId:u,timestamp:f,props:{event:s,type:i,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain(),...this.setMethods(u)};return this.telemetryEnabled&&(this.events.set(u,p),this.shouldPersist=!0),p},this.getEvent=o=>{let{eventId:s,topic:i}=o;if(s)return this.events.get(s);let a=Array.from(this.events.values()).find(c=>c.props.properties.topic===i);if(a)return{...a,...this.setMethods(a.eventId)}},this.deleteEvent=o=>{let{eventId:s}=o;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Vs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(o=>{(0,Ge.fromMiliseconds)(Date.now())-(0,Ge.fromMiliseconds)(o.timestamp)>OBe&&(this.events.delete(o.eventId),this.shouldPersist=!0)})})},this.setMethods=o=>({addTrace:s=>this.addTrace(o,s),setError:s=>this.setError(o,s)}),this.addTrace=(o,s)=>{let i=this.events.get(o);i&&(i.props.properties.trace.push(s),this.events.set(o,i),this.shouldPersist=!0)},this.setError=(o,s)=>{let i=this.events.get(o);i&&(i.props.type=s,i.timestamp=Date.now(),this.events.set(o,i),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{let o=await this.core.storage.getItem(this.storageKey)||[];if(!o.length)return;o.forEach(s=>{this.events.set(s.eventId,{...s,...this.setMethods(s.eventId)})})}catch(o){this.logger.warn(o)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;let o=[];for(let[s,i]of this.events)i.props.type&&o.push(i);if(o.length!==0)try{if((await this.sendEvent(o)).ok)for(let s of o)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async o=>{let s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${BBe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${qk}${s}`,{method:"POST",body:JSON.stringify(o)})},this.getAppDomain=()=>JB().url,this.logger=Cr(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},kBe=class xee extends oS{constructor(t){super(t),this.protocol=gee,this.version=yee,this.name=JS,this.events=new xf.EventEmitter,this.initialized=!1,this.on=(i,a)=>this.events.on(i,a),this.once=(i,a)=>this.events.once(i,a),this.off=(i,a)=>this.events.off(i,a),this.removeListener=(i,a)=>this.events.removeListener(i,a),this.dispatchEnvelope=({topic:i,message:a,sessionExists:c})=>{if(!i||!a)return;let u={topic:i,message:a,publishedAt:Date.now(),transportType:Dr.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:c})};let r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(i){console.warn("Failed to copy global core",i)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||wee,this.customStoragePrefix=t?.customStoragePrefix?`:${t.customStoragePrefix}`:"";let n=X2({level:typeof t?.logger=="string"&&t.logger?t.logger:eBe.logger,name:JS}),{logger:o,chunkLoggerController:s}=Fl({opts:n,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=s,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Cr(o,this.name),this.heartbeat=new iw,this.crypto=new Kk(this,this.logger,t?.keychain),this.history=new eU(this,this.logger),this.expirer=new tU(this,this.logger),this.storage=t?.storage?t.storage:new aw({...tBe,...t?.storageOptions}),this.relayer=new Qk({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Xk(this,this.logger),this.verify=new rU(this,this.logger,this.storage),this.echoClient=new nU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new oU(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){let r=new xee(t);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(mBe,n),r}get context(){return sr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(hee,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(hee)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(t){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t.opts?.customStoragePrefix||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},vee=kBe;gh();var It=Ht(jd(),1);$c();var Cee="wc",See=2,Iee="client",gU=`${Cee}@${See}:${Iee}:`,iU={name:Iee,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"};var Eee="WALLETCONNECT_DEEPLINK_CHOICE";var UBe="proposal";var Aee="Proposal expired",DBe="session",ww=It.SEVEN_DAYS,LBe="engine",$o={wc_sessionPropose:{req:{ttl:It.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1104},res:{ttl:It.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1106},res:{ttl:It.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:It.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:It.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:It.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1112},res:{ttl:It.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1114},res:{ttl:It.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:It.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:It.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1119}}},aU={min:It.FIVE_MINUTES,max:It.SEVEN_DAYS},ql={idle:"IDLE",active:"ACTIVE"},MBe={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},HBe="request",$Be=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],FBe="wc";var zBe="auth",VBe="authKeys",jBe="pairingTopics",qBe="requests",XS=`${FBe}@${1.5}:${zBe}:`,Th=`${XS}:PUB_KEY`,cU=class extends gS{constructor(t){super(t),this.name=LBe,this.events=new QS.default,this.initialized=!1,this.requestQueue={state:ql.idle,queue:[]},this.sessionRequestQueue={state:ql.idle,queue:[]},this.emittedSessionRequests=new jC({limit:500}),this.requestQueueDelay=It.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys($o)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,It.toMiliseconds)(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();let n={...r,requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}};await this.isValidConnect(n),n.optionalNamespaces=MQ(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};let{pairingTopic:o,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:a,scopedProperties:c,relays:u,authentication:d,walletPay:f}=n,p=d?.[0]?.ttl||$o.wc_sessionPropose.req.ttl||It.FIVE_MINUTES;this.validateRequestExpiry(p);let h=o,y,w=!1;try{if(h){let M=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=M.active}}catch(M){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),M}if(!h||!w){let{topic:M,uri:N}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});h=M,y=N}if(!h){let{message:M}=Se("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(M)}let x=await this.client.core.crypto.generateKeyPair(),v=ln(p),T={requiredNamespaces:s,optionalNamespaces:i,relays:u??[{protocol:sU}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:v,pairingTopic:h,...a&&{sessionProperties:a},...c&&{scopedProperties:c},id:Tn(),...(d||f)&&{requests:{authentication:d?.map(M=>{let{domain:N,chains:L,nonce:P,uri:R,exp:I,nbf:B,type:C,statement:A,requestId:U,resources:H,signatureTypes:k}=M;return{domain:N,chains:L,nonce:P,type:C??"caip122",aud:R,version:"1",iat:new Date().toISOString(),exp:I,nbf:B,statement:A,requestId:U,resources:H,signatureTypes:k}}),walletPay:f}}},E=ir("session_connect",T.id),{reject:S,resolve:_,done:O}=yf(p,Aee),D=({id:M})=>{if(M===T.id){this.client.events.off("proposal_expire",D);let N=this.pendingSessions.get(T.id);if(N){let{sessionTopic:L,publicKey:P}=N;Promise.all([this.client.core.relayer.unsubscribe(L),this.client.core.crypto.keychain.has(L)?this.client.core.crypto.deleteSymKey(L):Promise.resolve(),this.client.core.crypto.keychain.has(P)?this.client.core.crypto.deleteKeyPair(P):Promise.resolve()]).catch(R=>this.client.logger.warn(R))}this.pendingSessions.delete(T.id),this.events.emit(E,{error:{message:Aee,code:0}})}};return this.client.events.on("proposal_expire",D),this.events.once(E,({error:M,session:N})=>{this.client.events.off("proposal_expire",D),M?S(M):N&&_(N)}),await this.setProposal(T.id,T),await this.sendProposeSession({proposal:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:T.id}}}).catch(M=>{throw this.deleteProposal(T.id),M}),{uri:y,approval:O}},this.pair=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{let n=this.client.core.eventClient.createEvent({properties:{topic:r?.id?.toString(),trace:[Ya.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(D){throw n.setError(Sh.no_internet_connection),D}try{await this.isValidProposalId(r?.id)}catch(D){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),n.setError(Sh.proposal_not_found),D}try{await this.isValidApprove(r)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),n.setError(Sh.session_approve_namespace_validation_failure),D}let{id:o,relayProtocol:s,namespaces:i,sessionProperties:a,scopedProperties:c,sessionConfig:u,proposalRequestsResponses:d}=r,f=this.client.proposal.get(o);this.client.core.eventClient.deleteEvent({eventId:n.eventId});let{pairingTopic:p,proposer:h,requiredNamespaces:y,optionalNamespaces:w}=f,x=this.client.core.eventClient?.getEvent({topic:p});x||(x=this.client.core.eventClient?.createEvent({type:Ya.session_approve_started,properties:{topic:p,trace:[Ya.session_approve_started,Ya.session_namespaces_validation_success]}}));let v=await this.client.core.crypto.generateKeyPair(),T=h.publicKey,E=await this.client.core.crypto.generateSharedKey(v,T),S={relay:{protocol:s??"irn"},namespaces:i,controller:{publicKey:v,metadata:this.client.metadata},expiry:ln(ww),...a&&{sessionProperties:a},...c&&{scopedProperties:c},...u&&{sessionConfig:u},proposalRequestsResponses:d},_=Dr.relay;x.addTrace(Ya.subscribing_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:_,internal:{skipSubscribe:!0}})}catch(D){throw x.setError(Sh.subscribe_session_topic_failure),D}x.addTrace(Ya.subscribe_session_topic_success);let O={...S,topic:E,requiredNamespaces:y,optionalNamespaces:w,pairingTopic:p,acknowledged:!1,self:S.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:v,transportType:Dr.relay,authentication:d?.authentication,walletPayResult:d?.walletPay};await this.client.session.set(E,O),x.addTrace(Ya.store_session);try{await this.sendApproveSession({sessionTopic:E,proposal:f,pairingProposalResponse:{relay:{protocol:s??"irn"},responderPublicKey:v},sessionSettleRequest:S,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:o,...this.getTVFApproveParams(O)}}}),x.addTrace(Ya.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(E,Sr("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(E),D}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:h.metadata}),await this.deleteProposal(o),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(E,ln(ww)),{topic:E,acknowledged:()=>Promise.resolve(this.client.session.get(E))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(i){throw this.client.logger.error("reject() -> isValidReject() failed"),i}let{id:n,reason:o}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(i){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),i}s&&await this.sendError({id:n,topic:s,error:o,rpcOpts:$o.wc_sessionPropose.reject}),await this.deleteProposal(n)},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}let{topic:n,namespaces:o}=r,{done:s,resolve:i,reject:a}=yf(It.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tn(),u=_n().toString(),d=this.client.session.get(n).namespaces;return this.events.once(ir("session_update",c),({error:f})=>{f?a(f):i()}),await this.client.session.update(n,{namespaces:o}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:o},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:d}),a(f)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}let{topic:n}=r,o=Tn(),{done:s,resolve:i,reject:a}=yf(It.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ir("session_extend",o),({error:c})=>{c?a(c):i()}),await this.setExpiry(n,ln(ww)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:o,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}let{chainId:n,request:o,topic:s,expiry:i=$o.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=Tn(),u=_n().toString(),{done:d,resolve:f,reject:p}=yf(i,"Request expired. Please try again.");this.events.once(ir("session_request",c),({error:x,result:v})=>{x?p(x):f(v)});let h="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:{...o,expiryTimestamp:ln(i)},chainId:n},expiry:i,throwOnFailedPublish:!0,appLink:y}).catch(x=>p(x)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),await d();let w={request:{...o,expiryTimestamp:ln(i)},chainId:n};return await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:w,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),x()}),new Promise(async x=>{if(!a.sessionConfig?.disableDeepLink){let v=await dQ(this.client.core.storage,Eee);await uQ({id:c,topic:s,wcDeepLink:v})}x()}),d()]).then(x=>x[2])},this.respond=async r=>{this.isInitialized();let n=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||r?.response?.id?.toString(),trace:[Ya.session_request_response_started]}});try{await this.isValidRespond(r)}catch(u){throw n.addTrace(u?.message),n.setError(Sh.session_request_response_validation_failure),u}n.addTrace(Ya.session_request_response_validation_success);let{topic:o,response:s}=r,{id:i}=s,a=this.client.session.get(o);a.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{n.addTrace(Ya.session_request_response_publish_started),Jr(s)?await this.sendResult({id:i,topic:o,result:s.result,throwOnFailedPublish:!0,appLink:c}):Ir(s)&&await this.sendError({id:i,topic:o,error:s.error,appLink:c}),this.cleanupAfterResponse(r)}catch(u){throw n.addTrace(u?.message),n.setError(Sh.session_request_response_publish_failure),u}},this.ping=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(o){throw this.client.logger.error("ping() -> isValidPing() failed"),o}let{topic:n}=r;if(this.client.session.keys.includes(n)){let o=Tn(),s=_n().toString(),{done:i,resolve:a,reject:c}=yf(It.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ir("session_ping",o),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);let{topic:n,event:o,chainId:s}=r,i=_n().toString(),a=Tn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:o,chainId:s},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:a})},this.disconnect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Sr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:o}=Se("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(o)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>HQ(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(r,n)=>{this.isInitialized(),this.isValidAuthenticate(r);let o=n&&this.client.core.linkModeSupportedApps.includes(n)&&this.client.metadata.redirect?.linkMode,s=o?Dr.link_mode:Dr.relay;s===Dr.relay&&await this.confirmOnlineStateOrThrow();let{chains:i,statement:a="",uri:c,domain:u,nonce:d,type:f,exp:p,nbf:h,methods:y=[],expiry:w}=r,x=[...r.resources||[]],{topic:v,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:s});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:T}}),this.client.auth.authKeys.keys.includes(Th)){let{responseTopic:H,publicKey:k}=this.client.auth.authKeys.get(Th);H&&(await this.client.core.relayer.unsubscribe(H).catch(F=>this.client.logger.warn(F)),await this.client.auth.pairingTopics.delete(H,{message:"replaced",code:0}).catch(F=>this.client.logger.warn(F))),k&&this.client.core.crypto.keychain.has(k)&&await this.client.core.crypto.deleteKeyPair(k)}let E=await this.client.core.crypto.generateKeyPair(),S=rw(E);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:S,publicKey:E}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:v})]),await this.client.core.relayer.subscribe(S,{transportType:s}),this.client.logger.info(`sending request to new pairing topic: ${v}`),y.length>0){let{namespace:H}=Lc(i[0]),k=vQ(H,"request",y);W8(x)&&(k=EQ(k,x.pop())),x.push(k)}let _=w&&w>$o.wc_sessionAuthenticate.req.ttl?w:$o.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:f??"caip122",chains:i,statement:a,aud:c,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:p,nbf:h,resources:x},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:ln(_)},D={eip155:{chains:i,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},M={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:ln($o.wc_sessionPropose.req.ttl),id:Tn()},{done:N,resolve:L,reject:P}=yf(_,"Request expired"),R=Tn(),I=ir("session_connect",M.id),B=ir("session_request",R),C=async({error:H,session:k})=>{this.events.off(B,A),H?P(H):k&&L({session:k})},A=async H=>{if(await this.deletePendingAuthRequest(R,{message:"fulfilled",code:0}),H.error){let X=Sr("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return H.error.code===X.code?void 0:(this.events.off(I,C),P(H.error.message))}await this.deleteProposal(M.id),this.events.off(I,C);let{cacaos:k,responder:F}=H.result,j=[],W=[];for(let X of k){await nk({cacao:X,projectId:this.client.core.projectId})||(this.client.logger.error(X,"Signature verification failed"),P(Sr("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:pe}=X,me=W8(pe.resources),Ne=[QC(pe.iss)],ye=q8(pe.iss);if(me){let Re=sk(me),Et=ik(me);j.push(...Re),Ne.push(...Et)}for(let Re of Ne)W.push(`${Re}:${ye}`)}let ae=await this.client.core.crypto.generateSharedKey(E,F.publicKey),te;j.length>0&&(te={topic:ae,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:F,controller:F.publicKey,expiry:ln(ww),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:hk([...new Set(j)],[...new Set(W)]),transportType:s},await this.client.core.relayer.subscribe(ae,{transportType:s}),await this.client.session.set(ae,te),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:F.metadata}),te=this.client.session.get(ae)),this.client.metadata.redirect?.linkMode&&F.metadata.redirect?.linkMode&&F.metadata.redirect?.universal&&n&&(this.client.core.addLinkModeSupportedApp(F.metadata.redirect.universal),this.client.session.update(ae,{transportType:Dr.link_mode})),L({auths:k,session:te})};this.events.once(I,C),this.events.once(B,A);let U;try{if(o){let H=dr("wc_sessionAuthenticate",O,R);this.client.core.history.set(v,H);let k=await this.client.core.crypto.encode("",H,{type:tw,encoding:wf});U=G8(n,v,k)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:O,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:R}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:M,expiry:$o.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:M.id})])}catch(H){throw this.events.off(I,C),this.events.off(B,A),H}return await this.setProposal(M.id,M),await this.setAuthRequest(R,{request:{...O,verifyContext:{}},pairingTopic:v,transportType:s}),{uri:U??T,response:N}},this.approveSessionAuthenticate=async r=>{let{id:n,auths:o}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ih.authenticated_session_approve_started]}});try{this.isInitialized()}catch(x){throw s.setError(yw.no_internet_connection),x}let i=this.getPendingAuthRequest(n);if(!i)throw s.setError(yw.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);let a=i.transportType||Dr.relay;a===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=i.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=rw(c),f={type:Mc,receiverPublicKey:c,senderPublicKey:u},p=[],h=[];for(let x of o){if(!await nk({cacao:x,projectId:this.client.core.projectId})){s.setError(yw.invalid_cacao);let _=Sr("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:_,encodeOpts:f}),new Error(_.message)}s.addTrace(Ih.cacaos_verified);let{p:v}=x,T=W8(v.resources),E=[QC(v.iss)],S=q8(v.iss);if(T){let _=sk(T),O=ik(T);p.push(..._),E.push(...O)}for(let _ of E)h.push(`${_}:${S}`)}let y=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Ih.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:i.requester.metadata},controller:c,expiry:ln(ww),authentication:o,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:hk([...new Set(p)],[...new Set(h)]),transportType:a},s.addTrace(Ih.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(x){throw s.setError(yw.subscribe_authenticated_session_topic_failure),x}s.addTrace(Ih.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),s.addTrace(Ih.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}s.addTrace(Ih.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:o,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,a)})}catch(x){throw s.setError(yw.authenticated_session_approve_publish_failure),x}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}},this.rejectSessionAuthenticate=async r=>{this.isInitialized();let{id:n,reason:o}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let i=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=rw(i),u={type:Mc,receiverPublicKey:i,senderPublicKey:a};await this.sendError({id:n,topic:c,error:o,encodeOpts:u,rpcOpts:$o.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:o}=r;return ok(n,o)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{let r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(s=>s.peerMetadata?.url&&s.peerMetadata?.url===r.peer.metadata.url&&s.topic&&s.topic!==n.topic);if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:o=!1,emitEvent:s=!0,id:i=0}=r,{self:a}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Sr("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),o||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Eee).catch(c=>this.client.logger.warn(c)),n===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=ql.idle),await Promise.all(this.getPendingSessionRequests().filter(c=>c.topic===n).map(c=>this.deletePendingSessionRequest(c.id,Sr("USER_DISCONNECTED")))),s&&this.client.events.emit("session_delete",{id:i,topic:n})},this.deleteProposal=async(r,n)=>{if(n)try{let o=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:o.pairingTopic})?.setError(Sh.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Sr("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),o&&(this.sessionRequestQueue.state=ql.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,n,o=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))},this.setProposal=async(r,n)=>{this.client.core.expirer.set(r,ln($o.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)},this.setAuthRequest=async(r,n)=>{let{request:o,pairingTopic:s,transportType:i=Dr.relay}=n;this.client.core.expirer.set(r,o.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:o.authPayload,requester:o.requester,expiryTimestamp:o.expiryTimestamp,id:r,pairingTopic:s,verifyContext:o.verifyContext,transportType:i})},this.setPendingSessionRequest=async r=>{let{id:n,topic:o,params:s,verifyContext:i}=r,a=s.request.expiryTimestamp||ln($o.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:o,params:s,verifyContext:i})},this.sendRequest=async r=>{let{topic:n,method:o,params:s,expiry:i,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:d,tvf:f,publishOpts:p={}}=r,h=dr(o,s,c),y,w=!!d;try{let T=w?wf:to;y=await this.client.core.crypto.encode(n,h,{encoding:T})}catch(T){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),T}let x;if($Be.includes(o)){let T=xi(JSON.stringify(h)),E=xi(y);x=await this.client.core.verify.register({id:E,decryptedId:T})}let v={...$o[o].req,...p};if(v.attestation=x,i&&(v.ttl=i),a&&(v.id=a),this.client.core.history.set(n,h),w){let T=G8(d,n,y);await global.Linking.openURL(T,this.client.name)}else v.tvf={...f,correlationId:h.id},u?(v.internal={...v.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(n,y,v)):this.client.core.relayer.publish(n,y,v).catch(T=>this.client.logger.error(T));return h.id},this.sendProposeSession=async r=>{let{proposal:n,publishOpts:o}=r,s=dr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);let i=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:to}),a=xi(JSON.stringify(s)),c=xi(i),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:i},opts:{...o,publishMethod:"wc_proposeSession",attestation:u}})},this.sendApproveSession=async r=>{let{sessionTopic:n,pairingProposalResponse:o,proposal:s,sessionSettleRequest:i,publishOpts:a}=r,c=bo(s.id,o),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:to}),d=dr("wc_sessionSettle",i,a?.id),f=await this.client.core.crypto.encode(n,d,{encoding:to});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:{...a,publishMethod:"wc_approveSession"}})},this.sendResult=async r=>{let{id:n,topic:o,result:s,throwOnFailedPublish:i,encodeOpts:a,appLink:c}=r,u=bo(n,s),d,f=c&&typeof global?.Linking<"u";try{let y=f?wf:to;d=await this.client.core.crypto.encode(o,u,{...a||{},encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${o} failed`),y}let p,h;try{p=await this.client.core.history.get(o,n);let y=p.request;try{h=this.getTVFParams(n,y.params,s)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${o}, ${n}) failed`),y}if(f){let y=G8(c,o,d);await global.Linking.openURL(y,this.client.name)}else{let y=p.request.method,w=$o[y].res;w.tvf={...h,correlationId:n},i?(w.internal={...w.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(o,d,w)):this.client.core.relayer.publish(o,d,w).catch(x=>this.client.logger.error(x))}await this.client.core.history.resolve(u)},this.sendError=async r=>{let{id:n,topic:o,error:s,encodeOpts:i,rpcOpts:a,appLink:c}=r,u=la(n,s),d,f=c&&typeof global?.Linking<"u";try{let h=f?wf:to;d=await this.client.core.crypto.encode(o,u,{...i||{},encoding:h})}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${o} failed`),h}let p;try{p=await this.client.core.history.get(o,n)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${o}, ${n}) failed`),h}if(f){let h=G8(c,o,d);await global.Linking.openURL(h,this.client.name)}else{let h=p.request.method,y=a||$o[h].res;this.client.core.relayer.publish(o,d,y)}await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(o=>{let s=!1;ca(o.expiry)&&(s=!0),this.client.core.crypto.keychain.has(o.topic)||(s=!0),s&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{ca(o.expiryTimestamp)&&n.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession({topic:o})),...n.map(o=>this.deleteProposal(o))])},this.onProviderMessageEvent=async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ql.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=ql.active;let r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=ql.idle},this.processRequest=async r=>{let{topic:n,payload:o,attestation:s,transportType:i,encryptedId:a}=r,c=o.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:o,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,o);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,o);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,o);case"wc_sessionPing":return await this.onSessionPingRequest(n,o);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,o);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(n,o);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});default:return this.client.logger.info(`Unsupported request method ${c}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:o,transportType:s}=r,i=(await this.client.core.history.get(n,o.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(n,o,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,o);case"wc_sessionExtend":return this.onSessionExtendResponse(n,o);case"wc_sessionPing":return this.onSessionPingResponse(n,o);case"wc_sessionRequest":return this.onSessionRequestResponse(n,o);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,o);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:o}=Se("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:o}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(o)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i}=r,{params:a,id:c}=o;try{let u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(zl.proposal_listener_not_found)),this.isValidConnect({...o.params});let d=a.expiryTimestamp||ln($o.wc_sessionPropose.req.ttl),f={id:c,pairingTopic:n,expiryTimestamp:d,attestation:s,encryptedId:i,...a};await this.setProposal(c,f);let p=await this.getVerifyContext({attestationId:s,hash:xi(JSON.stringify(o)),encryptedId:i,metadata:f.proposer.metadata});u?.addTrace(zc.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:p})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:$o.wc_sessionPropose.autoReject}),this.client.logger.error(u)}},this.onSessionProposeResponse=async(r,n,o)=>{let{id:s}=n;if(Jr(n)){let{result:i}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});let a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});let c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});let u=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let d=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:d,pairingTopic:r,proposalId:s,publicKey:c});let f=await this.client.core.relayer.subscribe(d,{transportType:o});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(Ir(n)){await this.deleteProposal(s);let i=ir("session_connect",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners, 954`);this.events.emit(i,{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:o,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:i,controller:a,expiry:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=n.params,y=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!y)return this.client.logger.error(`Pending session not found for topic ${r}`);let w=this.client.proposal.get(y.proposalId),x={topic:r,relay:i,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata},...d&&{sessionProperties:d},...f&&{scopedProperties:f},...p&&{sessionConfig:p},transportType:Dr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay};await this.client.session.set(x.topic,x),await this.setExpiry(x.topic,x.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:x.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(x),await this.sendResult({id:n.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:x}),this.events.emit(ir("session_connect",y.proposalId),{session:x})}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}},this.onSessionSettleResponse=async(r,n)=>{let{id:o}=n;Jr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ir("session_approve",o),{})):Ir(n)&&(await this.deleteSession({topic:r,emitEvent:!1}),this.events.emit(ir("session_approve",o),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:o,id:s}=n;try{let i=`${r}_session_update`,a=wh.get(i);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Sr("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate({topic:r,...o});try{wh.set(i,s),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw wh.delete(i),c}this.client.events.emit("session_update",{id:s,topic:r,params:o})}catch(i){await this.sendError({id:s,topic:r,error:i}),this.client.logger.error(i)}},this.isRequestOutOfSync=(r,n)=>n.toString().slice(0,-3){let{id:o}=n,s=ir("session_update",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_update",o),{}):Ir(n)&&this.events.emit(ir("session_update",o),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:o}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ln(ww)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:o}=n,s=ir("session_extend",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_extend",o),{}):Ir(n)&&this.events.emit(ir("session_extend",o),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:o}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:o}=n,s=ir("session_ping",o);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Jr(n)?this.events.emit(ir("session_ping",o),{}):Ir(n)&&this.events.emit(ir("session_ping",o),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:o}=n;try{await this.isValidDisconnect({topic:r,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Sr("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:o})}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i,transportType:a}=r,{id:c,params:u}=o;try{await this.isValidRequest({topic:n,...u});let d=this.client.session.get(n),f=await this.getVerifyContext({attestationId:s,hash:xi(JSON.stringify(dr("wc_sessionRequest",u,c))),encryptedId:i,metadata:d.peer.metadata,transportType:a}),p={id:c,topic:n,params:u,verifyContext:f};await this.setPendingSessionRequest(p),a===Dr.link_mode&&d.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(d.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(p):(this.addSessionRequestToSessionRequestQueue(p),this.processSessionRequestQueue())}catch(d){await this.sendError({id:c,topic:n,error:d}),this.client.logger.error(d)}},this.onSessionRequestResponse=(r,n)=>{let{id:o}=n,s=ir("session_request",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(ir("session_request",o),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:o,params:s}=n;try{let i=`${r}_session_event_${s.event.name}`,a=wh.get(i);if(a&&this.isRequestOutOfSync(a,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit({topic:r,...s}),this.client.events.emit("session_event",{id:o,topic:r,params:s}),wh.set(i,o)}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:o}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Jr(n)?this.events.emit(ir("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(ir("session_request",o),{error:n.error})},this.onSessionAuthenticateRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i,transportType:a}=r;try{let{requester:c,authPayload:u,expiryTimestamp:d}=o.params,f=await this.getVerifyContext({attestationId:s,hash:xi(JSON.stringify(o)),encryptedId:i,metadata:c.metadata,transportType:a}),p={requester:c,pairingTopic:n,id:o.id,authPayload:u,verifyContext:f,expiryTimestamp:d};await this.setAuthRequest(o.id,{request:p,pairingTopic:n,transportType:a}),a===Dr.link_mode&&c.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:o.params,id:o.id,verifyContext:f})}catch(c){this.client.logger.error(c);let u=o.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(o.params.requester.metadata,a),p={type:Mc,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:o.id,topic:n,error:c,encodeOpts:p,rpcOpts:$o.wc_sessionAuthenticate.autoReject,appLink:f})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ql.idle,this.processSessionRequestQueue()},(0,It.toMiliseconds)(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let o=this.client.core.history.pending;o.length>0&&o.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ir("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ql.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}},this.emitSessionRequest=r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=ql.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{let r=this.client.core.relayer.subscriber.topics;if(r.length===0)return;let n=new Set(this.client.session.keys),o=new Set(this.client.core.pairing.pairings.keys),s=new Set([...this.pendingSessions.values()].map(a=>a.sessionTopic)),i;if(this.client.auth.authKeys.keys.includes(Th)){let{responseTopic:a}=this.client.auth.authKeys.get(Th);i=a}for(let a of r)if(!n.has(a)&&!o.has(a)&&!s.has(a)&&a!==i){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${a}`);try{await this.client.core.relayer.subscriber.unsubscribe(a)}catch(c){this.client.logger.warn(c,`Failed to clean up orphaned subscription: ${a}`)}}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:dr("wc_sessionPropose",{...n,requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties},n.id),attestation:n.attestation,encryptedId:n.encryptedId})},this.isValidConnect=async r=>{if(!as(r)){let{message:u}=Se("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:s,sessionProperties:i,scopedProperties:a,relays:c}=r;if(In(n)||await this.isValidPairingTopic(n),!WQ(c,!0)){let{message:u}=Se("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(o&&!In(o)&&Ka(o)!==0){let u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(o,"requiredNamespaces")}if(s&&!In(s)&&Ka(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),i&&!In(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!In(a)){this.validateSessionProps(a,"scopedProperties");let u=Object.keys(o||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(d=>u.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}},this.validateNamespaces=(r,n)=>{let o=qQ(r,"connect()",n);if(o)throw new Error(o.message)},this.isValidApprove=async r=>{if(!as(r))throw new Error(Se("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:o,relayProtocol:s,sessionProperties:i,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let c=this.client.proposal.get(n),u=eS(o,"approve()");if(u)throw new Error(u.message);let d=wk(c.requiredNamespaces,o,"approve()");if(d)throw new Error(d.message);if(!gn(s,!0)){let{message:f}=Se("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(i&&!In(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!In(a)){this.validateSessionProps(a,"scopedProperties");let f=new Set(Object.keys(o));if(!Object.keys(a).every(p=>f.has(p.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}},this.isValidReject=async r=>{if(!as(r)){let{message:s}=Se("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:o}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!ZQ(o)){let{message:s}=Se("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!as(r)){let{message:u}=Se("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}let{relay:n,controller:o,namespaces:s,expiry:i}=r;if(!gk(n)){let{message:u}=Se("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}let a=VQ(o,"onSessionSettleRequest()");if(a)throw new Error(a.message);let c=eS(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ca(i)){let{message:u}=Se("EXPIRED","onSessionSettleRequest()");throw new Error(u)}},this.isValidUpdate=async r=>{if(!as(r)){let{message:c}=Se("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}let{topic:n,namespaces:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),i=eS(o,"update()");if(i)throw new Error(i.message);let a=wk(s.requiredNamespaces,o,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!as(r)){let{message:c}=Se("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}let{topic:n,request:o,chainId:s,expiry:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!yk(a,s)){let{message:c}=Se("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!GQ(o)){let{message:c}=Se("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(c)}if(!QQ(a,s,o.method)){let{message:c}=Se("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(c)}this.validateRequestExpiry(i)},this.isValidRespond=async r=>{if(!as(r)){let{message:i}=Se("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(i)}let{topic:n,response:o}=r;try{await this.isValidSessionTopic(n)}catch(i){throw r?.response?.id&&this.cleanupAfterResponse(r),i}if(!YQ(o)){let{message:i}=Se("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(i)}let s=this.client.pendingRequest.get(o.id);if(s.topic!==n){let{message:i}=Se("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${o.id}, expected topic: ${s.topic}, received topic: ${n}`);throw new Error(i)}},this.isValidPing=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!as(r)){let{message:a}=Se("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:o,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:i}=this.client.session.get(n);if(!yk(i,s)){let{message:a}=Se("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!JQ(o)){let{message:a}=Se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}if(!XQ(i,s,o.name)){let{message:a}=Se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:o,domain:s,nonce:i}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!gn(o,!1))throw new Error("uri is required parameter");if(!gn(s,!1))throw new Error("domain is required parameter");if(!gn(i,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Lc(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:a}=Lc(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{let{attestationId:n,hash:o,encryptedId:s,metadata:i,transportType:a}=r,c={verified:{verifyUrl:i.verifyUrl||gw,validation:"UNKNOWN",origin:i.url||""}};try{if(a===Dr.link_mode){let d=this.getAppLinkIfEnabled(i,a);return c.verified.validation=d&&new URL(d).origin===new URL(i.url).origin?"VALID":"INVALID",c}let u=await this.client.core.verify.resolve({attestationId:n,hash:o,encryptedId:s,verifyUrl:i.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c},this.validateSessionProps=(r,n)=>{Object.values(r).forEach((o,s)=>{if(o==null){let{message:i}=Se("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${o} for key ${Object.keys(r)[s]}`);throw new Error(i)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let o=0,s=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(o++>=s)break;this.recentlyDeletedMap.delete(i)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:o}=Se("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(o)}},this.isLinkModeEnabled=(r,n)=>!r||n!==Dr.link_mode?!1:this.client.metadata?.redirect?.linkMode===!0&&this.client.metadata?.redirect?.universal!==void 0&&this.client.metadata?.redirect?.universal!==""&&r?.redirect?.universal!==void 0&&r?.redirect?.universal!==""&&r?.redirect?.linkMode===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof global?.Linking<"u",this.getAppLinkIfEnabled=(r,n)=>this.isLinkModeEnabled(r,n)?r?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;let n=XB(r,"topic")||"",o=decodeURIComponent(XB(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:Dr.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:o,sessionExists:s})},this.registerLinkModeListeners=async()=>{if(j8()||gf()&&this.client.metadata.redirect?.linkMode){let r=global?.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);let n=await r.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}},this.getTVFApproveParams=r=>{try{let n=pk(r.namespaces),o=DQ(r.namespaces),s=LQ(r.namespaces),i=r.sessionProperties,a=r.scopedProperties;return{approvedChains:n,approvedMethods:o,approvedEvents:s,sessionProperties:i,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}},this.getTVFParams=(r,n,o)=>{if(!n.request?.method)return{};let s={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{let i=this.extractTxHashesFromResult(n.request,o);s.txHashes=i,s.contractAddresses=this.isValidContractData(n.request.params)?[n.request.params?.[0]?.to]:[]}catch(i){this.client.logger.warn(i,"Error getting TVF params")}return s},this.isValidContractData=r=>{if(!r)return!1;try{let n=r?.data||r?.[0]?.data;if(!n.startsWith("0x"))return!1;let o=n.slice(2);return/^[0-9a-fA-F]*$/.test(o)?o.length%2===0:!1}catch{}return!1},this.extractTxHashesFromResult=(r,n)=>{try{if(!n)return[];let o=r.method,s=MBe[o];if(o==="sui_signTransaction")return[gQ(n.transactionBytes)];if(o==="near_signTransaction")return[tk(n)];if(o==="near_signTransactions")return n.map(a=>tk(a));if(o==="xrpl_signTransactionFor"||o==="xrpl_signTransaction")return[n.tx_json?.hash];if(o==="polkadot_signTransaction")return[nX({transaction:r.params.transactionPayload,signature:n.signature})];if(o==="algo_signTxn")return zs(n)?n.map(a=>rk(a)):[rk(n)];if(o==="cosmos_signDirect")return[yQ(n)];if(o==="wallet_sendCalls")return wQ(n);if(typeof n=="string")return[n];let i=n[s.key];if(zs(i))return o==="solana_signAllTransactions"?i.map(a=>mQ(a)):i;if(typeof i=="string")return[i]}catch(o){this.client.logger.warn(o,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{let t=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(t);for(let[n,o]of Object.entries(r))for(let s of o)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(yn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){let{topic:r,message:n,attestation:o,transportType:s}=t,{publicKey:i}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{publicKey:void 0};try{let a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i,encoding:s===Dr.link_mode?wf:to});Hc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:o,transportType:s,encryptedId:xi(n)})):ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(pa.expired,async t=>{let{topic:r,id:n}=YC(t.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Se("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Se("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(t){this.client.logger.warn(t)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Ch.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(Ch.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!gn(t,!1)){let{message:r}=Se("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.core.pairing.pairings.get(t).expiry)){let{message:r}=Se("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!gn(t,!1)){let{message:r}=Se("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});let{message:r}=Se("EXPIRED",`session topic: ${t}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(t)){let{message:r}=Se("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(gn(t,!1)){let{message:r}=Se("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{let{message:r}=Se("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!KQ(t)){let{message:r}=Se("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);let{message:r}=Se("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}validateRequestExpiry(t){if(t&&!eX(t,aU)){let{message:r}=Se("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${aU.min} and ${aU.max}`);throw new Error(r)}}},lU=class extends jl{constructor(t,r){super(t,r,UBe,gU),this.core=t,this.logger=r}},uU=class extends jl{constructor(t,r){super(t,r,DBe,gU),this.core=t,this.logger=r}},dU=class extends jl{constructor(t,r){super(t,r,HBe,gU,n=>n.id),this.core=t,this.logger=r}},fU=class extends jl{constructor(t,r){super(t,r,VBe,XS,()=>Th),this.core=t,this.logger=r}},pU=class extends jl{constructor(t,r){super(t,r,jBe,XS),this.core=t,this.logger=r}},hU=class extends jl{constructor(t,r){super(t,r,qBe,XS,n=>n.id),this.core=t,this.logger=r}},mU=class{constructor(t,r){this.core=t,this.logger=r,this.authKeys=new fU(this.core,this.logger),this.pairingTopics=new pU(this.core,this.logger),this.requests=new hU(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},WBe=class Tee extends mS{constructor(t){super(t),this.protocol=Cee,this.version=See,this.name=iU.name,this.events=new QS.EventEmitter,this.on=(n,o)=>this.events.on(n,o),this.once=(n,o)=>this.events.once(n,o),this.off=(n,o)=>this.events.off(n,o),this.removeListener=(n,o)=>this.events.removeListener(n,o),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(o){throw this.logger.error(o.message),o}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(o){throw this.logger.error(o.message),o}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(o){throw this.logger.error(o.message),o}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(o){throw this.logger.error(o.message),o}},this.update=async n=>{try{return await this.engine.update(n)}catch(o){throw this.logger.error(o.message),o}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(o){throw this.logger.error(o.message),o}},this.request=async n=>{try{return await this.engine.request(n)}catch(o){throw this.logger.error(o.message),o}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(o){throw this.logger.error(o.message),o}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(o){throw this.logger.error(o.message),o}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(o){throw this.logger.error(o.message),o}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(o){throw this.logger.error(o.message),o}},this.find=n=>{try{return this.engine.find(n)}catch(o){throw this.logger.error(o.message),o}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async(n,o)=>{try{return await this.engine.authenticate(n,o)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(o){throw this.logger.error(o.message),o}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}},this.name=t?.name||iU.name,this.metadata=sQ(t?.metadata),this.signConfig=t?.signConfig;let r=sw({logger:t?.logger||iU.logger,name:this.name});this.logger=r,this.core=t?.core||new vee(t),this.session=new uU(this.core,this.logger),this.proposal=new lU(this.core,this.logger),this.pendingRequest=new dU(this.core,this.logger),this.engine=new cU(this),this.auth=new mU(this.core,this.logger)}static async init(t){let r=new Tee(t);return await r.initialize(),r}get context(){return sr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}};var _ee=WBe;$c();cw();rI();var qee=Ht(ks(),1),Mee="error",eke="wss://relay.walletconnect.org",tke="wc",Wee="universal_provider",nI=`${tke}@2:${Wee}:`,Kee="https://rpc.walletconnect.org/v1/",Zee="generic",rke=`${Kee}bundler`,xw="call_status",nke=86400,SU={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Gee(e,t,r){let n=Lc(e);return t.rpcMap?.[n.reference]||`${Kee}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function oke(e){return e.includes(":")?e.split(":")[1]:e}function Yee(e){return e.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function ske(e,t){let r=Object.keys(t.namespaces).filter(o=>o.includes(e));if(!r.length)return[];let n=[];return r.forEach(o=>{let s=t.namespaces[o].accounts;n.push(...s)}),n}function Hee(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r?.chains?.length&&r?.chains?.length>0))}function oI(e={},t={}){let r=Hee($ee(e)),n=Hee($ee(t));return jk(r,n)}function $ee(e){let t={};if(!Ka(e))return t;for(let[r,n]of Object.entries(e)){let o=Y8(r)?[r]:n.chains,s=n.methods||[],i=n.events||[],a=n.rpcMap||{},c=H1(r);t[c]={...t[c],...n,chains:Uc(o,t[c]?.chains),methods:Uc(s,t[c]?.methods),events:Uc(i,t[c]?.events)},(Ka(a)||Ka(t[c]?.rpcMap||{}))&&(t[c].rpcMap={...a,...t[c]?.rpcMap})}return t}function Fee(e){return e.includes(":")?e.split(":")[2]:e}function zee(e){let t={};for(let[r,n]of Object.entries(e)){let o=n.methods||[],s=n.events||[],i=n.accounts||[],a=Y8(r)?[r]:n.chains?n.chains:Yee(n.accounts);t[r]={chains:a,methods:o,events:s,accounts:i}}return t}function wU(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function ike(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}var Jee={},vw=e=>Jee[e],bU=(e,t)=>{Jee[e]=t},Vee="eip155",ake=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],cke=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,xU=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,jee=e=>Object.keys(e).filter(t=>ake.includes(t)).reduce((t,r)=>(t[r]=lke(e[r]),t),{}),lke=e=>typeof e=="string"&&ike(e)?JSON.parse(e):e,uke=(e,t,r)=>{let{sessionProperties:n={},scopedProperties:o={}}=e,s={};if(!Ka(o)&&!Ka(n))return;let i=jee(n);for(let a of r){let c=cke(a);if(!c)continue;s[xU(c)]=i;let u=o?.[`${Vee}:${c}`];if(u){let d=u?.[`${Vee}:${c}:${t}`];s[xU(c)]={...s[xU(c)],...jee(d||u)}}}for(let[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0},vU,EU=class e{constructor(t){this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,r){return await this.storage.setItem(t,r)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return vU||(vU=new e(t)),vU}};async function dke(e,t){let r=Lc(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,o=await Promise.allSettled(n.map(f=>fke(r.reference,f,t))),s=o.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);o.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));let i=!s.length||s.some(f=>!f),a=s.every(f=>f?.status==="0x1"),c=s.every(f=>f?.status==="0x0"),u=s.some(f=>f?.status==="0x0"),d;return i?d=100:a?d=200:c?d=500:u&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function fke(e,t,r){return await r(parseInt(e)).request(dr("eth_getTransactionReceipt",[t]))}async function pke({sendCalls:e,storage:t}){let r=await t.getItem(xw);await t.setItem(xw,{...r,[e.result.id]:{request:e.request,result:e.result,expiry:ln(nke)}})}async function hke({resultId:e,storage:t}){let r=await t.getItem(xw);if(r){delete r[e],await t.setItem(xw,r);for(let n in r)ca(r[n].expiry)&&delete r[n];await t.setItem(xw,r)}}async function mke({resultId:e,storage:t}){let r=(await t.getItem(xw))?.[e];if(r&&!ca(r.expiry))return r;await hke({resultId:e,storage:t})}var AU=class{constructor(t){this.name="eip155",this.namespace=t.namespace,this.events=vw("events"),this.client=vw("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=EU.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r);let n=this.chainId;this.chainId=parseInt(t),this.events.emit(SU.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){let n=r||Gee(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,vw("disableProviderPing")))}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProviders(){let t={};return this.namespace.chains.forEach(r=>{let n=parseInt(oke(r));t[n]=this.createHttpProvider(n,this.namespace.rpcMap?.[r])}),t}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(t){let r=t||this.chainId;return this.httpProviders[r]||(this.httpProviders={...this.httpProviders,[r]:this.createHttpProvider(r)},this.httpProviders[r])}async handleSwitchChain(t){let r=t.request.params?t.request.params[0]?.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;let n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:r}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){let r=t.request?.params?.[0],n=t.request?.params?.[1]||[];if(!r)throw new Error("Missing address parameter in `wallet_getCapabilities` request");let o=this.client.session.get(t.topic),s=o?.sessionProperties?.capabilities||{},i=n.length>0?n.join(","):`0x${this.chainId.toString(16)}`,a=`${r}${i}`,c=s?.[a];if(c)return c;let u;try{u=uke(o,r,n)}catch(f){console.warn("Failed to extract capabilities from session",f)}if(u)return u;let d=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:{...o.sessionProperties||{},capabilities:{...s||{},[a]:d}}})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(t){let r=this.client.session.get(t.topic),n=r.sessionProperties?.bundler_name;if(n){let i=this.getBundlerUrl(t.chainId,n);try{return await this.getUserOperationReceipt(i,t)}catch(a){console.warn("Failed to fetch call status from bundler",a,i)}}let o=r.sessionProperties?.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,t)}catch(i){console.warn("Failed to fetch call status from custom bundler",i,o)}let s=await mke({resultId:t.request.params?.[0],storage:this.storage});if(s)try{return await dke(s,this.getHttpProvider.bind(this))}catch(i){console.warn("Failed to fetch call status from stored send calls",i,s)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,r){let n=new URL(t),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dr("eth_getUserOperationReceipt",[r.request.params?.[0]]))});if(!o.ok)throw new Error(`Failed to fetch user operation receipt - ${o.status}`);return await o.json()}getBundlerUrl(t,r){return`${rke}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${r}`}async sendCalls(t){let r=await this.client.request(t),n=t.request.params?.[0],o=r?.id,s=r?.capabilities||{},i=s?.caip345?.caip2,a=s?.caip345?.transactionHashes;return!o||!i||!a?.length||await pke({sendCalls:{request:n,result:r},storage:this.storage}),r}},CU=class{constructor(t){this.name=Zee,this.namespace=t.namespace,this.events=vw("events"),this.client=vw("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r);let n=this.chainId;this.chainId=t,this.events.emit(SU.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return Lc(t).namespace}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){let t={};return this.namespace?.accounts?.forEach(r=>{let n=Lc(r),o=this.namespace?.rpcMap?.[`${n.namespace}:${n.reference}`];t[n.reference]=this.createHttpProvider(r,o)}),t}getHttpProvider(t){let r=Lc(t).reference,n=this.httpProviders[r];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return n}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProvider(t,r){let n=r||Gee(t,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,vw("disableProviderPing")))}},gke=class Qee{constructor(t){this.events=new qee.default,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=t,this.logger=sw({logger:t.logger??Mee,name:this.providerOpts.name??Wee}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){let r=new Qee(t);return await r.initialize(),r}async request(t,r,n){let[o,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(o).request({request:{...t},chainId:`${o}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(t,r,n,o){let s=new Date().getTime();this.request(t,n,o).then(i=>r(null,bo(s,i))).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Sr("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();let{uri:n,response:o}=await this.client.authenticate(t,r);n&&(this.uri=n,this.events.emit("display_uri",n));let s=await o();if(this.session=s.session,this.session){let i=zee(this.session.namespaces);this.namespaces=oI(this.namespaces,i),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){let{uri:r,approval:n}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});r&&(this.uri=r,this.events.emit("display_uri",r));let o=await n();this.session=o;let s=zee(o.namespaces);return this.namespaces=oI(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;let[n,o]=this.validateChain(t),s=this.getProvider(n);s?s.setDefaultChain(o,r):this.session&&this.logger.warn(`Provider for namespace '${n}' not found in setDefaultChain`)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");let r=this.client.pairing.getAll();if(!zs(r))return;for(let n of r)t.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){if(this.client=this.providerOpts.client||await _ee.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Mee,relayUrl:this.providerOpts.relayUrl||eke,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(t){throw this.logger.error(t,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{let t=this.client.session.getAll();this.session=t[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");let t=[...new Set(Object.keys(this.session.namespaces).map(r=>H1(r)))];bU("client",this.client),bU("events",this.events),bU("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;let n=ske(r,this.session);if(n?.length===0)return;let o=Yee(n),s={...oI(this.namespaces,this.optionalNamespaces)[r],accounts:n,chains:o};r==="eip155"?this.rpcProviders[r]=new AU({namespace:s}):this.rpcProviders[r]=new CU({namespace:s})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{let{topic:r}=t;r===this.session?.topic&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{let{params:r,topic:n}=t;if(n!==this.session?.topic)return;let{event:o}=r;if(o.name==="accountsChanged"){let s=o.data;s&&zs(s)&&this.events.emit("accountsChanged",s.map(Fee))}else if(o.name==="chainChanged"){let s=r.chainId,i=r.event.data,a=H1(s),c=wU(s)!==wU(i)?`${a}:${wU(i)}`:s;this.onChainChanged({currentCaipChainId:c})}else this.events.emit(o.name,o.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{if(t!==this.session?.topic)return;let{namespaces:n}=r,o=this.client?.session.get(t);this.session={...o,namespaces:n},this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{t.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",{...Sr("USER_DISCONNECTED"),data:t.topic}))}),this.on(SU.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged({...t,internal:!0})})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[Zee]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{this.getProvider(t).updateNamespace(this.session?.namespaces[t])})}setNamespaces(t){let{namespaces:r={},optionalNamespaces:n={},sessionProperties:o,scopedProperties:s}=t;this.optionalNamespaces=oI(r,n),this.sessionProperties=o,this.scopedProperties=s}validateChain(t){let[r,n]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(i=>H1(i)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];let o=H1(Object.keys(this.namespaces)[0]),s=this.rpcProviders[o].getDefaultChain();return[o,s]}async requestAccounts(){let[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:r,internal:n=!1}){if(!this.namespaces)return;let[o,s]=this.validateChain(t);if(s){if(this.updateNamespaceChain(o,s),n)this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:o,currentCaipChainId:t,previousCaipChainId:r});else{let i=this.getProvider(o);i?i.setDefaultChain(s):this.session&&this.logger.warn(`Provider for namespace '${o}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:r,previousCaipChainId:n}){try{if(n===r)return;let o=this.session?.namespaces[t]?.accounts;if(!o)return;let s=o.filter(i=>i.includes(`${r}:`)).map(Fee);if(!zs(s))return;this.events.emit("accountsChanged",s)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,r){if(!this.namespaces)return;let n=this.namespaces[t]?t:`${t}:${r}`,o={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=o}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,r){let n=this.session?.topic||"";await this.client.core.storage.setItem(`${nI}/${t}${n}`,r)}async getFromStore(t){let r=this.session?.topic||"";return await this.client.core.storage.getItem(`${nI}/${t}${r}`)}async deleteFromStore(t){let r=this.session?.topic||"";await this.client.core.storage.removeItem(`${nI}/${t}${r}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;let t=await this.client.core.storage.getKeys();for(let r of t)r.startsWith(nI)&&await this.client.core.storage.removeItem(r)}catch(t){this.logger.warn(t,"Failed to cleanup storage")}}},Xee=gke;var qtt="wc",Wtt="ethereum_provider",Ktt=`${qtt}@2:${Wtt}:`,Ztt="https://rpc.walletconnect.org/v1/",Oq=["eth_sendTransaction","personal_sign"],Gtt=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Bq=["chainChanged","accountsChanged"],Ytt=["chainChanged","accountsChanged","message","disconnect","connect"],Jtt=async()=>{let{createAppKit:e}=await Promise.resolve().then(()=>(gAe(),mAe));return e};function PN(e){return Number(e[0].split(":")[1])}function _N(e){return`0x${e.toString(16)}`}function Qtt(e){let{chains:t,optionalChains:r,methods:n,optionalMethods:o,events:s,optionalEvents:i,rpcMap:a}=e;if(!zs(t))throw new Error("Invalid chains");let c={chains:t,methods:n||Oq,events:s||Bq,rpcMap:{...t.length?{[PN(t)]:a[PN(t)]}:{}}},u=s?.filter(h=>!Bq.includes(h)),d=n?.filter(h=>!Oq.includes(h));if(!r&&!i&&!o&&!u?.length&&!d?.length)return{required:t.length?c:void 0};let f=u?.length&&d?.length||!r,p={chains:[...new Set(f?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(o?.length?o:Gtt))],events:[...new Set(c.events.concat(i?.length?i:Ytt))],rpcMap:a};return{required:t.length?c:void 0,optional:r.length?p:void 0}}var Xtt=class wAe{constructor(){this.events=new yAe.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=Ktt,this.on=(t,r)=>(this.events.on(t,r),this),this.once=(t,r)=>(this.events.once(t,r),this),this.removeListener=(t,r)=>(this.events.removeListener(t,r),this),this.off=(t,r)=>(this.events.off(t,r),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){let r=new wAe;return await r.initialize(t),r}async request(t,r){return await this.signer.request(t,this.formatChainId(this.chainId),r)}sendAsync(t,r,n){this.signer.sendAsync(t,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);let{required:r,optional:n}=Qtt(this.rpc);try{let o=await new Promise(async(i,a)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))}));let c=t?.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect({namespaces:{...r&&{[this.namespace]:r}},...n&&{optionalNamespaces:{[this.namespace]:n}},pairingTopic:t?.pairingTopic,scopedProperties:c}).then(u=>{i(u)}).catch(u=>{this.modal?.showErrorMessage("Unable to connect"),a(new Error(u.message))})});if(!o)return;let s=GB(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:_N(this.chainId)})}catch(o){throw this.signer.logger.error(o),o}finally{this.modal?.close()}}async authenticate(t,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{let n=await new Promise(async(s,i)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),i(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate({...t,chains:this.rpc.chains},r).then(a=>{s(a)}).catch(a=>{this.modal?.showErrorMessage("Unable to connect"),i(new Error(a.message))})}),o=n.session;if(o){let s=GB(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:_N(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{this.modal?.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{let{params:r}=t,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",t)}),this.signer.on("accountsChanged",t=>{this.accounts=this.parseAccounts(t),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",t=>{let r=parseInt(t);this.chainId=r,this.events.emit("chainChanged",_N(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",{...Sr("USER_DISCONNECTED"),data:t.topic,name:"USER_DISCONNECTED"})}),this.signer.on("display_uri",t=>{this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){let r=t.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",_N(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){let r=this.parseChainId(t);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(t){let[r,n,o]=t.split(":");return{chainId:`${r}:${n}`,address:o}}setAccounts(t){this.accounts=t.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){let r=t?.chains??[],n=t?.optionalChains??[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");let s=r.length?t?.methods||Oq:[],i=r.length?t?.events||Bq:[],a=t?.optionalMethods||[],c=t?.optionalEvents||[],u=t?.rpcMap||this.buildRpcMap(o,t.projectId),d=t?.qrModalOptions||void 0;return{chains:r?.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:s,events:i,optionalMethods:a,optionalEvents:c,rpcMap:u,showQrModal:!!t?.showQrModal,qrModalOptions:d,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,r){let n={};return t.forEach(o=>{n[o]=this.getRpcUrl(o,r)}),n}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?PN(this.rpc.chains):PN(this.rpc.optionalChains),this.signer=await Xee.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storage:t.storage,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{let n=await Jtt(),{convertWCMToAppKitOptions:o}=await Promise.resolve().then(function(){return nrt}),s=o({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!s.networks.length)throw new Error("No networks found for WalletConnect");r=n({...s,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:this.rpc.qrModalOptions?.enableMobileFullScreen===!0})}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;let{chains:r,optionalChains:n,rpcMap:o}=t;r&&zs(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=o?.[s]||this.getRpcUrl(s)})),n&&zs(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=o?.[s]||this.getRpcUrl(s)}))}getRpcUrl(t,r){return this.rpc.rpcMap?.[t]||`${Ztt}?chainId=eip155:${t}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{let t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:r?.accounts),this.setAccounts(r?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(r=>this.parseAccount(r))}},bAe=Xtt;function ert(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}var trt=e=>{let[t,r]=e.split(":");return xAe({id:r,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function rrt(e){let t=e.chains?.map(trt).filter(Boolean);if(t.length===0)throw new Error("At least one chain must be specified");let r=t.find(o=>o.id===e.defaultChain?.id),n={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:ert(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:r,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:e.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:e.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){let o=[...(e.mobileWallets||[]).map(a=>({id:a.id,name:a.name,links:a.links})),...(e.desktopWallets||[]).map(a=>({id:a.id,name:a.name,links:{native:a.links.native,universal:a.links.universal}}))],s=[...n.featuredWalletIds||[],...n.excludeWalletIds||[]],i=o.filter(a=>!s.includes(a.id));i.length&&(n.customWallets=i)}return n}function xAe(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var nrt=Object.freeze({__proto__:null,convertWCMToAppKitOptions:rrt,defineChain:xAe});var ECe=Ht(bCe(),1);l();l();function xCe(e){let t=Promise.resolve(),r=o=>{let s=t.then(()=>e("storage",{method:"POST",body:JSON.stringify(o)}));return t=s.catch(()=>{}),s},n=async()=>(await t,e("storage"));return{async getKeys(){return Object.keys(await n())},async getEntries(){return Object.entries(await n())},async getItem(o){return(await n())[o]},async setItem(o,s){await r({key:o,value:s})},async removeItem(o){await r({key:o,value:null})}}}var ta,vCe,rW,Jrt=(...e)=>rW(...e);async function aFr(e){if(vCe!==e.contextKey&&(ta=null,vCe=e.contextKey),rW=e.api,g({url:e.relayUrl,authorize:()=>e.api("relay-admission",{method:"POST"})}),ta?.connected)return ta;ta??=await bAe.init({projectId:e.projectId,customStoragePrefix:e.contextKey,chains:[e.chains[0]],optionalChains:e.chains.slice(1),methods:["personal_sign","eth_sendTransaction"],optionalMethods:[],disableProviderPing:!0,events:["accountsChanged","chainChanged"],showQrModal:!1,storage:xCe(Jrt),logger:"silent",telemetryEnabled:!1,metadata:e.metadata,rpcMap:Object.fromEntries(e.chains.map(d=>[d,`${e.runtimeUrl}/unavailable-rpc`]))});let t=document.createElement("dialog"),r=document.createElement("p");r.textContent="Scan with your phone wallet, then approve the connection there.";let n=document.createElement("canvas"),o=document.createElement("button");o.textContent="Cancel",o.type="button",t.append(r,n,o);let s,i=new Promise((d,f)=>{s=f}),a=()=>{ta.signer.abortPairingAttempt(),ta.signer.client.core.relayer.transportClose().catch(()=>{}),s(new Error("Wallet connection cancelled."))};o.onclick=a,t.addEventListener("cancel",a);let c=d=>{ECe.default.toCanvas(n,d,{width:280,margin:2}).catch(a),t.open||t.showModal()};ta.on("display_uri",c),document.body.append(t);let u;try{return await ta.signer.client.core.relayer.transportOpen(),await Promise.race([ta.connect(),i,new Promise((d,f)=>{u=setTimeout(()=>{a(),f(new Error("Wallet connection expired."))},18e4)})]),ta}finally{clearTimeout(u),ta.removeListener("display_uri",c),t.remove()}}async function cFr(e){rW=e.api;try{ta?.session&&await ta.disconnect()}finally{await ta?.signer.client.core.relayer.transportClose()}}export{aFr as connectWalletConnectEvm,cFr as disconnectWalletConnectEvm}; +/*! Bundled license information: + +tslib/tslib.es6.js: + (*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** *) + +@scure/base/lib/esm/index.js: + (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/ciphers/esm/utils.js: +@walletconnect/utils/dist/index.js: + (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *) + +@scure/bip39/esm/index.js: + (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) + +@walletconnect/relay-auth/dist/index.es.js: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/hashes/esm/utils.js: +@noble/hashes/esm/utils.js: +@noble/hashes/esm/utils.js: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/abstract/utils.js: +@noble/curves/esm/abstract/modular.js: +@noble/curves/esm/abstract/curve.js: +@noble/curves/esm/abstract/weierstrass.js: +@noble/curves/esm/_shortw_utils.js: +@noble/curves/esm/secp256k1.js: +@noble/curves/esm/abstract/utils.js: +@noble/curves/esm/abstract/modular.js: +@noble/curves/esm/abstract/curve.js: +@noble/curves/esm/abstract/weierstrass.js: +@noble/curves/esm/_shortw_utils.js: +@noble/curves/esm/secp256k1.js: +@noble/curves/esm/abstract/utils.js: +@noble/curves/esm/abstract/modular.js: +@noble/curves/esm/abstract/curve.js: +@noble/curves/esm/abstract/weierstrass.js: +@noble/curves/esm/_shortw_utils.js: +@noble/curves/esm/secp256k1.js: +@noble/curves/esm/utils.js: +@noble/curves/esm/abstract/modular.js: +@noble/curves/esm/abstract/curve.js: +@noble/curves/esm/abstract/edwards.js: +@noble/curves/esm/abstract/montgomery.js: +@noble/curves/esm/ed25519.js: +@noble/curves/esm/abstract/weierstrass.js: +@noble/curves/esm/_shortw_utils.js: +@noble/curves/esm/nist.js: +@noble/curves/esm/p256.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@lit/reactive-element/css-tag.js: +@lit/reactive-element/css-tag.mjs: + (** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +@lit/reactive-element/reactive-element.js: +lit-html/lit-html.js: +lit-element/lit-element.js: +@lit/reactive-element/decorators/custom-element.js: +@lit/reactive-element/decorators/property.js: +@lit/reactive-element/decorators/state.js: +@lit/reactive-element/decorators/event-options.js: +@lit/reactive-element/decorators/base.js: +@lit/reactive-element/decorators/query.js: +@lit/reactive-element/decorators/query-all.js: +@lit/reactive-element/decorators/query-async.js: +@lit/reactive-element/decorators/query-assigned-nodes.js: +@lit/reactive-element/reactive-element.mjs: +lit-html/lit-html.mjs: +lit-element/lit-element.mjs: +@lit/reactive-element/decorators/custom-element.mjs: +@lit/reactive-element/decorators/property.mjs: +lit-html/directive.js: +lit-html/async-directive.js: + (** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lit-html/is-server.js: + (** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +@lit/reactive-element/decorators/query-assigned-elements.js: + (** + * @license + * Copyright 2021 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lit-html/directives/if-defined.js: +lit-html/directives/class-map.js: + (** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lit-html/static.js: +lit-html/directive-helpers.js: +lit-html/directives/ref.js: + (** + * @license + * Copyright 2020 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) +*/ diff --git a/components.json b/components.json index 4bdd879ff..102d8da81 100644 --- a/components.json +++ b/components.json @@ -1651,6 +1651,7 @@ "people", "wallet-metamask", "wallet-unisat", + "wallet-walletconnect", "wallet", "object-provider", "kubo", diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index c41c58767..0b00ec61d 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -244,33 +244,49 @@ storage, and signed runtime audit scaffolding. An approval that expires before managed signing or external handoff completion fails closed instead of becoming a stale signing authority. -WalletConnect is a dedicated connector capsule (`wallet-walletconnect`), not a -wallet-provider SDK backend and not app-owned session state. `wallet-provider` -owns proof verification, linked accounts, approval state, receipts, and audit; -the connector owns only Reown/AppKit browser UX plus the operator-pinned local -adapter. Mode A is the first target: ElastOS acts as the dApp and external -wallets sign Runtime challenges or requests. Mode B, where external dApps treat -ElastOS as a WalletConnect wallet, is a later security milestone. Internal -capsules do not use WalletConnect or generic Wallet provider calls; their -product routes enter the private typed Wallet Bus through verified Runtime -authority. - -`wallet-walletconnect` remains invisible unless the runtime finds -`elastos.walletconnect.connector/v1` config plus a local hashed Reown/AppKit SDK -asset. A configured launch can read only the narrow -`/api/apps/wallet-walletconnect/wallet/config` contract for its project ID and -local SDK asset path. The dormant connector UI imports only that pinned local -asset and expects a stable adapter export named `connectWalletConnectEvm`, which -returns an EIP-1193 provider to the connector capsule. -`scripts/vendor-walletconnect-adapter.sh` builds that adapter from exact package -versions, and `scripts/configure-walletconnect-connector.mjs` pins a reviewed -local adapter by sha256. Until a real Reown project ID and reviewed adapter are -installed into the runtime data dir, the connector remains hidden and -unroutable. Do not commit a bundled default Reown Project ID; official -deployments and independent operators pin their own runtime config. Essentials -and ELA signing should start from that connector contract because the Essentials -DID toolkit is WalletConnect-backed; -do not add a visible Essentials surface until the pinned connector exists. +WalletConnect is a dedicated connector capsule (`wallet-walletconnect`). +`wallet-provider` owns proof verification, linked accounts, approval state, +receipts, and audit. The connector presents the account and approval controls; +trusted Home hosts the reviewed Reown EVM provider and bundled QR renderer. +Mode A connects external wallets to sign Runtime challenges and approved +requests. Mode B, where external dApps use ElastOS as a WalletConnect wallet, +requires its own security decision. Internal capsules enter the private typed +Wallet Bus through verified Runtime authority. + +Runtime keeps the SDK key/value store in private files selected by the verified +principal. Trusted Home combines its own authority with the carried connector +launch token to use storage and obtain a short-lived, single-use relay admission. +An opaque capsule cannot read pairing keys or publish encrypted signing requests. +Home accepts link actions, approval IDs, and disconnect actions; Runtime and +`wallet-provider` supply the exact proof or signing payload. Pairing carries +connection state. Each signing request retains its principal, requesting actor, +account, chain, payload hash, and expiry. Disconnect leaves linked accounts in +Wallet. Account or chain changes stop a request in progress. + +Inbox owns internet consent through the owner's passkey. Runtime connects only +to `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through +the existing local Exit. Runtime authenticates relay TLS, limits frame size and +sockets per principal, sends heartbeats, and expires idle connections. Turn Off +cancels handshakes and open sockets. Reopening the connector restores the SDK's +principal-scoped state and reconnects while consent and Home authority remain +valid. Hosted Carrier Exit selection remains a separate integration. + +The connector is installed with Home and stays hidden and unroutable until +`elastos.walletconnect.connector/v1` configuration and the matching hashed local +SDK asset exist. `scripts/vendor-walletconnect-adapter.sh` uses `npm ci` with the +complete dependency lock in `scripts/walletconnect/package-lock.json`. It builds +the `connectWalletConnectEvm` adapter inside the capsule's `vendor` directory; +release packaging includes those bytes in the verified capsule archive. + +The release workflow reads the operator's `REOWN_PROJECT_ID` secret. Independent +operators can supply `ELASTOS_WALLETCONNECT_PROJECT_FILE` or +`ELASTOS_WALLETCONNECT_PROJECT_ID` during release preparation or source-home +setup. Staging checks the reviewed adapter hash and includes `vendor/connector.json` +before the capsule is hashed. An existing operator configuration in +`ElastOS/SystemServices/WalletConnect/config.json` takes precedence. Source uses +fixture IDs in tests and carries each operator's project ID only in that +operator's release or installed configuration. A person using Home presses +Connect and scans the QR code. Essentials and ELA signing build on this boundary. Essentials, ELA, EID, BTC BIP-322, and UniversalX should reuse the same proof-binding shape. UniSat is the first dedicated browser Bitcoin connector because its injected API diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index 4a42b48f0..74118a8b2 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -1809,6 +1809,7 @@ dependencies = [ "elastos-wallet-contract", "flate2", "futures-lite", + "futures-util", "getrandom 0.2.17", "hex", "hkdf", @@ -1822,6 +1823,7 @@ dependencies = [ "qrcodegen", "rand 0.10.2", "rand 0.8.7", + "rcgen", "reqwest 0.12.28", "rustls", "semver", @@ -1834,6 +1836,8 @@ dependencies = [ "tar", "tempfile", "tokio", + "tokio-rustls", + "tokio-tungstenite", "toml", "tower", "tower-http 0.5.2", @@ -5874,8 +5878,12 @@ checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" dependencies = [ "futures-util", "log", + "rustls", + "rustls-pki-types", "tokio", + "tokio-rustls", "tungstenite", + "webpki-roots 0.26.11", ] [[package]] @@ -6139,6 +6147,8 @@ dependencies = [ "httparse", "log", "rand 0.8.7", + "rustls", + "rustls-pki-types", "sha1", "thiserror 1.0.69", "utf-8", diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index 2f57dc81a..5d11c023c 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -43,6 +43,8 @@ clap = { version = "4.0", features = ["derive"] } # Async runtime tokio = { version = "1.0", features = ["full"] } +tokio-tungstenite = { version = "0.24", features = ["rustls-tls-webpki-roots"] } +futures-util = { version = "0.3", features = ["sink"] } # Serialization serde = { version = "1.0", features = ["derive"] } @@ -121,6 +123,8 @@ data-encoding = "2.6" custody-provider = { path = "../../../capsules/custody-provider" } [dev-dependencies] +rcgen = "0.13" +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } tokio = { version = "1.0", features = ["full", "test-util"] } tempfile = "3.10" tower = { version = "0.5", features = ["util"] } diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 353afb4c9..89a165a06 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -3603,14 +3603,8 @@ fn require_wallet_link_context( state: &GatewayState, headers: &HeaderMap, ) -> anyhow::Result { - let authority = require_runtime_wallet_authority( - &state.data_dir, - headers, - &[super::gateway::WALLET_WALLETCONNECT_CAPSULE_ID], - )?; - let verified = authority.verified_context(); - let app = verified.actor().to_string(); - verified_wallet_link_context(state, &app, authority) + let _ = (state, headers); + anyhow::bail!("Wallet linking requires the trusted Home wallet connector bridge") } pub(in crate::api) fn verified_wallet_link_context( @@ -4960,6 +4954,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: data_dir.to_path_buf(), data_dir: data_dir.to_path_buf(), @@ -5222,6 +5217,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: data_dir.to_path_buf(), data_dir: data_dir.to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/browser_capsules.rs b/elastos/crates/elastos-server/src/api/browser_capsules.rs index e800493c6..2cb8618bc 100644 --- a/elastos/crates/elastos-server/src/api/browser_capsules.rs +++ b/elastos/crates/elastos-server/src/api/browser_capsules.rs @@ -366,11 +366,7 @@ fn shell_content_security_policy( format!("{home_source} 'unsafe-inline'"), ) }; - let connect_source = if !is_home_host { - format!("{default_source} {}", home_websocket_origin(&home_source)?) - } else { - default_source.clone() - }; + let connect_source = format!("{default_source} {}", home_websocket_origin(&home_source)?); // No allow-popups: a new window escapes connect-src and frame-src. Home // opens web links for its apps (`home:open-external`). let sandbox = if is_home_host { diff --git a/elastos/crates/elastos-server/src/api/capsule_inventory/preparation.rs b/elastos/crates/elastos-server/src/api/capsule_inventory/preparation.rs index b73dcc180..ad0767d72 100644 --- a/elastos/crates/elastos-server/src/api/capsule_inventory/preparation.rs +++ b/elastos/crates/elastos-server/src/api/capsule_inventory/preparation.rs @@ -5397,6 +5397,7 @@ mod tests { collaboration_presence_product_port: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: root.path().to_path_buf(), data_dir: root.path().to_path_buf(), @@ -5599,6 +5600,7 @@ mod tests { collaboration_presence_product_port: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: root.to_path_buf(), data_dir: root.to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway.rs b/elastos/crates/elastos-server/src/api/gateway.rs index 257633f3f..5cd1dd85e 100644 --- a/elastos/crates/elastos-server/src/api/gateway.rs +++ b/elastos/crates/elastos-server/src/api/gateway.rs @@ -117,6 +117,8 @@ mod gateway_transaction_effects; mod gateway_wallet; #[path = "gateway_wallet_adapter.rs"] mod gateway_wallet_adapter; +#[path = "gateway_walletconnect.rs"] +mod gateway_walletconnect; #[cfg(test)] use gateway_browser::browser_runtime_stream_socket_path; use gateway_capsule_catalog::*; @@ -454,7 +456,7 @@ pub(crate) const WALLETCONNECT_CONFIG_PATH: &str = "ElastOS/SystemServices/WalletConnect/config.json"; pub(crate) const WALLETCONNECT_SDK_PATH: &str = "capsules/wallet-walletconnect/vendor/reown-appkit.js"; -pub(crate) const WALLETCONNECT_SDK_PACKAGE: &str = "@reown/appkit"; +pub(crate) const WALLETCONNECT_SDK_PACKAGE: &str = "@walletconnect/ethereum-provider"; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -505,6 +507,7 @@ struct WalletPricePolicy { #[derive(Clone)] pub struct GatewayState { pub(crate) browser_internet: Arc, + pub(crate) walletconnect: Arc, pub(crate) carrier_endpoint: Option, pub provider_registry: Option>, pub(crate) collaboration_chat_product_port: @@ -861,6 +864,26 @@ fn gateway_router_with_api_url(state: GatewayState, gateway_api_url: String) -> ) .route("/api/apps/wallet/wallet/summary", get(wallet_app_summary)) .route("/api/wallet/prices", get(wallet_prices)) + .route( + "/api/apps/wallet-walletconnect/internet", + get(gateway_walletconnect::internet).post(gateway_walletconnect::internet), + ) + .route( + "/api/apps/wallet-walletconnect/storage", + get(gateway_walletconnect::storage).post(gateway_walletconnect::storage), + ) + .route( + "/api/apps/wallet-walletconnect/relay", + get(gateway_walletconnect::relay), + ) + .route( + "/api/apps/wallet-walletconnect/relay-admission", + post(gateway_walletconnect::admission), + ) + .route( + "/api/apps/wallet-walletconnect/host-config", + get(gateway_walletconnect::host_config).post(gateway_walletconnect::host_config), + ) .route("/api/wallet/qr", post(wallet_receive_qr)) .route( "/api/apps/wallet/wallet/managed", @@ -1019,6 +1042,10 @@ fn gateway_router_with_api_url(state: GatewayState, gateway_api_url: String) -> "/api/apps/home/wallet-connector/bitcoin/link/verify", post(home_wallet_connector_bitcoin_link_verify), ) + .route( + "/api/apps/home/wallet-connector/approvals/:request_id/review", + post(home_wallet_connector_approval_review), + ) .route( "/api/apps/home/wallet-connector/approvals/:request_id/handoff", post(home_wallet_connector_approval_handoff), diff --git a/elastos/crates/elastos-server/src/api/gateway_browser_internet.rs b/elastos/crates/elastos-server/src/api/gateway_browser_internet.rs index 3e8de5826..b33d1cb15 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser_internet.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser_internet.rs @@ -81,6 +81,11 @@ pub(crate) struct BrowserInternetService { generation: Mutex>, } impl BrowserInternetService { + pub(super) fn capability_manager(&self) -> anyhow::Result> { + self.manager + .clone() + .ok_or_else(|| anyhow::anyhow!("Runtime internet authority is unavailable")) + } pub(crate) fn new(manager: Option>) -> Self { Self { manager, diff --git a/elastos/crates/elastos-server/src/api/gateway_browser_remote.rs b/elastos/crates/elastos-server/src/api/gateway_browser_remote.rs index 5c3137d1d..fc882dccc 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser_remote.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser_remote.rs @@ -248,6 +248,7 @@ fn runtime_state( provider_registry: Some(registry), carrier_endpoint: Some(endpoint), browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(OnceLock::new()), collaboration_chat_product_port: None, collaboration_presence_product_port: None, @@ -2448,6 +2449,7 @@ mod tests { provider_registry: Some(registry), carrier_endpoint: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(OnceLock::new()), collaboration_chat_product_port: None, collaboration_presence_product_port: None, diff --git a/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs b/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs index 2ab121158..4a75f5bbc 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs @@ -4567,6 +4567,7 @@ async fn browser_wallet_read_timeout_test_state( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -8544,6 +8545,7 @@ async fn test_browser_net_provider_fails_closed_without_adapter_provider() { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(dir.path()), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: dir.path().to_path_buf(), data_dir: dir.path().to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs index 50d27a9c5..9a1368e67 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs @@ -1162,6 +1162,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: data_dir.path().to_path_buf(), data_dir: data_dir.path().to_path_buf(), @@ -1992,6 +1993,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: data_dir.path().to_path_buf(), data_dir: data_dir.path().to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs index 4af9f3c4b..c35badee5 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs @@ -922,6 +922,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(OnceLock::new()), cache_dir: data_dir.join("cache"), data_dir: data_dir.to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index d4940567a..c777dd4aa 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -5,8 +5,11 @@ use serde_json::json; const HOME_WALLET_CONNECTOR_REQUEST_SCHEMA: &str = "elastos.home.wallet-connector.effect.request/v1"; const HOME_WALLET_CONNECTOR_RESULT_SCHEMA: &str = "elastos.home.wallet-connector.effect.result/v1"; -const INJECTED_WALLET_CONNECTOR_IDS: &[&str] = - &[WALLET_METAMASK_CAPSULE_ID, WALLET_UNISAT_CAPSULE_ID]; +const HOSTED_WALLET_CONNECTOR_IDS: &[&str] = &[ + WALLET_METAMASK_CAPSULE_ID, + WALLET_UNISAT_CAPSULE_ID, + WALLET_WALLETCONNECT_CAPSULE_ID, +]; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -109,9 +112,9 @@ struct HomeWalletConnectorTransaction { chain_id: String, } -struct HomeWalletConnectorAuthority { - context: HomeLaunchTokenContext, - wallet: RuntimeWalletAuthority, +pub(super) struct HomeWalletConnectorAuthority { + pub(super) context: HomeLaunchTokenContext, + pub(super) wallet: RuntimeWalletAuthority, } pub(super) async fn home_wallet_connector_evm_link_challenge( @@ -125,7 +128,11 @@ pub(super) async fn home_wallet_connector_evm_link_challenge( &input.schema, &input.connector_id, &input.connector_token, - WALLET_METAMASK_CAPSULE_ID, + if input.connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + WALLET_WALLETCONNECT_CAPSULE_ID + } else { + WALLET_METAMASK_CAPSULE_ID + }, ) { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), @@ -171,7 +178,11 @@ pub(super) async fn home_wallet_connector_evm_link_verify( &input.schema, &input.connector_id, &input.connector_token, - WALLET_METAMASK_CAPSULE_ID, + if input.connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + WALLET_WALLETCONNECT_CAPSULE_ID + } else { + WALLET_METAMASK_CAPSULE_ID + }, ) { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), @@ -298,6 +309,39 @@ pub(super) async fn home_wallet_connector_bitcoin_link_verify( } } +pub(super) async fn home_wallet_connector_approval_review( + State(state): State, + headers: HeaderMap, + Path(request_id): Path, + Json(input): Json, +) -> Response { + let result = async { + validate_home_wallet_connector_request_id(&request_id)?; + let authority = require_home_wallet_connector_authority( + &state, + &headers, + &input.schema, + &input.connector_id, + &input.connector_token, + WALLET_WALLETCONNECT_CAPSULE_ID, + )?; + let request = + pending_wallet_approval_request(&state, &authority.wallet, &request_id).await?; + anyhow::ensure!( + request.connector_id.as_deref() == Some(WALLET_WALLETCONNECT_CAPSULE_ID) + && request.status == "pending" + && request.expires_at > now_ts(), + "WalletConnect request changed or expired" + ); + Ok::<_, anyhow::Error>(request) + } + .await; + match result { + Ok(request) => Json(request).into_response(), + Err(e) => system_error_response(e), + } +} + pub(super) async fn home_wallet_connector_approval_handoff( State(state): State, headers: HeaderMap, @@ -352,15 +396,27 @@ pub(super) async fn home_wallet_connector_approval_handoff( )); } }; - Json(json!({ + let mut response = json!({ "schema": HOME_WALLET_CONNECTOR_RESULT_SCHEMA, "action": "approval_handoff", "connector_id": input.connector_id, "request_id": request_id, "handoff": handoff, "evm_chains": wallet_connector_evm_chains(), - })) - .into_response() + }); + if input.connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + let Some(binding) = outcome.approval_request else { + return system_error_response(anyhow::anyhow!( + "WalletConnect approval binding is missing" + )); + }; + response["binding"] = json!({ + "principal_id":binding["principal_id"], "requested_by_actor":binding["requested_by_actor"], + "account_id":binding["account_id"], "chain_namespace":binding["chain_namespace"], + "payload_hash":binding["payload_hash"], "expires_at":binding["expires_at"], + }); + } + Json(response).into_response() } Err(err) => system_error_response(err), } @@ -416,7 +472,7 @@ pub(super) async fn home_wallet_connector_approval_complete( } } -fn require_home_wallet_connector_authority( +pub(super) fn require_home_wallet_connector_authority( state: &GatewayState, headers: &HeaderMap, schema: &str, @@ -427,8 +483,7 @@ fn require_home_wallet_connector_authority( if schema != HOME_WALLET_CONNECTOR_REQUEST_SCHEMA { anyhow::bail!("unsupported Home wallet-connector request schema"); } - if connector_id != expected_connector_id - || !INJECTED_WALLET_CONNECTOR_IDS.contains(&connector_id) + if connector_id != expected_connector_id || !HOSTED_WALLET_CONNECTOR_IDS.contains(&connector_id) { anyhow::bail!("Home wallet-connector actor mismatch"); } @@ -500,13 +555,17 @@ fn validate_home_wallet_connector_handoff( } match connector_id { - WALLET_METAMASK_CAPSULE_ID if handoff.intent == "bitcoin_bip322_proof" => { + WALLET_METAMASK_CAPSULE_ID | WALLET_WALLETCONNECT_CAPSULE_ID + if handoff.intent == "bitcoin_bip322_proof" => + { anyhow::bail!("MetaMask handoff cannot carry a Bitcoin approval") } WALLET_UNISAT_CAPSULE_ID if handoff.intent != "bitcoin_bip322_proof" => { anyhow::bail!("UniSat handoff must carry a Bitcoin approval") } - WALLET_METAMASK_CAPSULE_ID if handoff.intent == "transaction_intent" => { + WALLET_METAMASK_CAPSULE_ID | WALLET_WALLETCONNECT_CAPSULE_ID + if handoff.intent == "transaction_intent" => + { if handoff.status != "awaiting_wallet_transaction" || handoff.transaction.is_none() || handoff.message.is_some() @@ -515,7 +574,7 @@ fn validate_home_wallet_connector_handoff( anyhow::bail!("Wallet connector transaction handoff is invalid"); } } - WALLET_METAMASK_CAPSULE_ID => { + WALLET_METAMASK_CAPSULE_ID | WALLET_WALLETCONNECT_CAPSULE_ID => { if handoff.status != "awaiting_wallet_signature" || handoff.transaction.is_some() || handoff.message.is_none() diff --git a/elastos/crates/elastos-server/src/api/gateway_inbox.rs b/elastos/crates/elastos-server/src/api/gateway_inbox.rs index 9f3af801a..f70493dca 100644 --- a/elastos/crates/elastos-server/src/api/gateway_inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_inbox.rs @@ -109,6 +109,11 @@ pub(super) async fn append_inbox_requests( notifications.attention_count += usize::from(card.severity == "attention"); notifications.entries.push(card); } + if let Some(card) = gateway_walletconnect::notification(state, context) { + notifications.unread_count += usize::from(!card.read); + notifications.attention_count += usize::from(card.severity == "attention"); + notifications.entries.push(card); + } append_wallet_approval_notifications(notifications, wallet_approvals); // Runtime capability requests are the admin's to answer. if ensure_admin_context(&state.data_dir, context).is_ok() { @@ -390,6 +395,15 @@ async fn dispatch_inbox_action( ) .await; } + if action_id.starts_with("walletconnect-internet-") { + return gateway_walletconnect::answer( + state, + launch, + action_id, + action.step_up_token.as_deref(), + ) + .await; + } let data_dir = &state.data_dir; // Entries one account owns, such as its direct messages, change only for // that account. diff --git a/elastos/crates/elastos-server/src/api/gateway_models.rs b/elastos/crates/elastos-server/src/api/gateway_models.rs index 743032d0c..b477df956 100644 --- a/elastos/crates/elastos-server/src/api/gateway_models.rs +++ b/elastos/crates/elastos-server/src/api/gateway_models.rs @@ -641,6 +641,7 @@ struct SystemWalletApprovalSummary { resource: String, reason: String, account_id: String, + chain_namespace: String, address: String, proof_type: String, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs b/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs index 497baacef..5b710bacd 100644 --- a/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs +++ b/elastos/crates/elastos-server/src/api/gateway_passkey_step_up.rs @@ -227,6 +227,16 @@ async fn passkey_step_up_begin_inner( "Browser internet request has changed; review the current request" ); stored + } else if matches!( + operation.as_str(), + gateway_walletconnect::GRANT | gateway_walletconnect::REVOKE + ) { + let stored = gateway_walletconnect::step_up_request(state, &launch, &operation).await?; + anyhow::ensure!( + input.request == stored, + "WalletConnect request has changed; review the current request" + ); + stored } else { input.request }; @@ -1516,6 +1526,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(OnceLock::new()), cache_dir: data_dir.path().join("cache"), data_dir: data_dir.path().to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_server.rs b/elastos/crates/elastos-server/src/api/gateway_server.rs index ea637e4ae..2836bf53a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_server.rs +++ b/elastos/crates/elastos-server/src/api/gateway_server.rs @@ -120,6 +120,7 @@ async fn start_gateway_server_with_shutdown( collaboration_presence_product_port: collaboration.presence_product_port, collaboration_discovery_service: collaboration.discovery_service, browser_internet, + walletconnect: Default::default(), identity_manager: Arc::new(OnceLock::new()), cache_dir, data_dir: data_dir.clone(), diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/inspect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/inspect.rs index f626cfb0c..4de1f8d9b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/inspect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/inspect.rs @@ -150,6 +150,7 @@ async fn inspect_test_state(dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: dir.to_path_buf(), data_dir: dir.to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs b/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs index 0e7eabc25..964158936 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs @@ -156,6 +156,7 @@ fn test_state(cache_dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -345,6 +346,7 @@ async fn documents_test_state(cache_dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -382,6 +384,7 @@ async fn library_external_provider_test_state(cache_dir: &std::path::Path) -> Ga carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -416,6 +419,7 @@ async fn library_webspace_test_state(cache_dir: &std::path::Path) -> GatewayStat carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -486,6 +490,7 @@ async fn library_unmounted_operator_webspace_state(cache_dir: &std::path::Path) cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), browser_internet: Default::default(), + walletconnect: Default::default(), } } @@ -518,6 +523,7 @@ async fn library_test_state_with_content( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -538,6 +544,7 @@ async fn chain_test_state(cache_dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -558,6 +565,7 @@ async fn content_test_state(cache_dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -578,6 +586,7 @@ async fn net_test_state(cache_dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -602,6 +611,7 @@ async fn net_exit_test_state(cache_dir: &std::path::Path) -> GatewayState { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -727,6 +737,7 @@ async fn browser_engine_reconciliation_test_state( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -811,6 +822,7 @@ async fn browser_engine_retrying_close_test_state( carrier_endpoint, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -839,6 +851,7 @@ async fn browser_engine_policy_blocked_test_state(cache_dir: &std::path::Path) - carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -902,6 +915,7 @@ async fn browser_engine_remote_carrier_exit_test_state_with_close_failures( ), collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -962,6 +976,7 @@ async fn rejecting_browser_engine_remote_carrier_exit_test_state_with_close_fail ), collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -993,6 +1008,7 @@ async fn malformed_browser_summary_test_state(cache_dir: &std::path::Path) -> Ga carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -1030,6 +1046,7 @@ async fn browser_engine_attached_test_state_with_relay( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -1079,6 +1096,7 @@ async fn wallet_test_state_with_shared_provider( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -1134,6 +1152,7 @@ async fn wallet_chain_test_state_with_shared_wallet_provider( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: granted_browser_internet(cache_dir), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/model.rs b/elastos/crates/elastos-server/src/api/gateway_tests/model.rs index 0bf0841e2..5a1b0f241 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/model.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/model.rs @@ -62,6 +62,7 @@ async fn model_test_state( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), @@ -1525,6 +1526,7 @@ async fn scripted_model_state( carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: cache_dir.to_path_buf(), data_dir: cache_dir.to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/room.rs b/elastos/crates/elastos-server/src/api/gateway_tests/room.rs index 0bd08d2b9..caba4502d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/room.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/room.rs @@ -308,6 +308,7 @@ async fn test_gateway_carrier_bootstrap_route_returns_live_ticket() { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: dir.path().to_path_buf(), data_dir: dir.path().to_path_buf(), @@ -370,6 +371,7 @@ async fn test_gateway_carrier_bootstrap_prefers_managed_runtime_ticket() { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: dir.path().to_path_buf(), data_dir: dir.path().to_path_buf(), @@ -429,6 +431,7 @@ async fn test_gateway_carrier_bootstrap_publisher_role_uses_gateway_ticket() { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: dir.path().to_path_buf(), data_dir: dir.path().to_path_buf(), diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet.rs index c42c8edbf..8df875a98 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet.rs @@ -7,3 +7,5 @@ mod inbox; mod managed_approvals; mod prices; mod send; +#[cfg(unix)] +mod walletconnect; diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 2959fb5a3..55ae43b9b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -602,7 +602,7 @@ async fn test_metamask_connector_config_returns_runtime_evm_chain_metadata() { assert!(json.get("walletconnect").is_none()); } -fn seed_walletconnect_connector_config(data_dir: &std::path::Path) { +pub(super) fn seed_walletconnect_connector_config(data_dir: &std::path::Path) { let sdk = b"// pinned test WalletConnect SDK asset\n"; let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); std::fs::create_dir_all(sdk_path.parent().unwrap()).unwrap(); diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs new file mode 100644 index 000000000..beec3d5e9 --- /dev/null +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -0,0 +1,666 @@ +use super::super::*; +use futures_util::{SinkExt, StreamExt}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use tokio_tungstenite::{connect_async, tungstenite::Message}; + +const INTERNET: &str = "/api/apps/wallet-walletconnect/internet"; +const STORAGE: &str = "/api/apps/wallet-walletconnect/storage"; +const RELAY: &str = + "wss://relay.walletconnect.org/?projectId=test_walletconnect_project&auth=fixture"; + +async fn persistent_internet(data: &std::path::Path) -> Arc { + use elastos_runtime::capability::{CapabilityManager, CapabilityStore}; + use elastos_runtime::primitives::{audit::AuditLog, metrics::MetricsManager}; + let store = Arc::new(CapabilityStore::with_persistence(data.join("capability_store")).await.unwrap()); + let manager = Arc::new(CapabilityManager::load_or_generate(data, store, Arc::new(AuditLog::new()), Arc::new(MetricsManager::new()))); + Arc::new(BrowserInternetService::new(Some(manager))) +} + +struct Exit { + path: PathBuf, + calls: Arc, +} +#[async_trait::async_trait] +impl Provider for Exit { + fn name(&self) -> &'static str { + "walletconnect-fixture-exit" + } + fn schemes(&self) -> Vec<&'static str> { + vec!["exit"] + } + async fn handle(&self, _: ResourceRequest) -> Result { + Err(ProviderError::Provider("raw fixture".into())) + } + async fn send_raw(&self, request: &Value) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + assert_eq!(request["target"], "tls://relay.walletconnect.org:443"); + assert!(request["principal_id"].as_str().is_some()); + Ok(json!({"status":"ok", "data": { + "schema":"elastos.exit.stream-session/v1", "target":request["target"], + "stream_id":"stream:wc-fixture", "principal_id":request["principal_id"], "byte_transport":"adapter_ipc", + "relay_ipc":{"schema":"elastos.exit.relay-ipc/v1","kind":"unix_socket","path":self.path} + }})) + } +} + +struct Fixture { + data: tempfile::TempDir, + state: GatewayState, + app: Router, + connector: String, + inbox: String, + home: String, + addr: String, + calls: Arc, + pings: Arc, + pause_tls: Arc, + handshake: Arc, + resume: Arc, + gateway: tokio::task::JoinHandle<()>, + relay: tokio::task::JoinHandle<()>, +} +impl Drop for Fixture { + fn drop(&mut self) { + self.gateway.abort(); + self.relay.abort(); + } +} +impl Fixture { + async fn new() -> Self { + let data = tempfile::Builder::new() + .prefix("wc-") + .tempdir_in(if cfg!(target_os = "macos") { + "/private/tmp" + } else { + "/tmp" + }) + .unwrap(); + let owner = passkey_authority(data.path()); + super::connectors::seed_walletconnect_connector_config(data.path()); + let connector = projection_launch_token_for_authority_context( + data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &owner, + ); + let inbox = app_token_for_authority(data.path(), INBOX_CAPSULE_ID, &owner); + let mut state = test_state(data.path()); + state.browser_internet = persistent_internet(data.path()).await; + let cert = + rcgen::generate_simple_self_signed(vec!["relay.walletconnect.org".into()]).unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(cert.cert.der().clone()).unwrap(); + let client = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + *state.walletconnect.tls.lock().unwrap() = Some(Arc::new(client)); + let server = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![cert.cert.der().clone()], + rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()).into(), + ) + .unwrap(); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server)); + let path = data.path().join("relay.sock"); + let listener = UnixListener::bind(&path).unwrap(); + let pings = Arc::new(AtomicUsize::new(0)); + let observed = pings.clone(); + let pause_tls = Arc::new(AtomicBool::new(false)); + let handshake = Arc::new(tokio::sync::Notify::new()); + let resume = Arc::new(tokio::sync::Notify::new()); + let pause = pause_tls.clone(); + let entered = handshake.clone(); + let proceed = resume.clone(); + let relay = tokio::spawn(async move { + let mut connections = tokio::task::JoinSet::new(); + loop { + tokio::select! { + connection = listener.accept() => { + let (mut connection, _) = connection.unwrap(); + let acceptor = acceptor.clone(); let pings = observed.clone(); + let pause = pause.clone(); let entered = entered.clone(); let proceed = proceed.clone(); + connections.spawn(async move { + let mut line = Vec::new(); + loop { + let Ok(byte) = connection.read_u8().await else { return; }; + if byte == b'\n' { break; } + line.push(byte); assert!(line.len() < 16384); + } + let open: Value = serde_json::from_slice(&line).unwrap(); + assert_eq!(open["schema"], "elastos.exit.relay-open/v1"); + assert_eq!(open["target"], "tls://relay.walletconnect.org:443"); + if pause.load(Ordering::SeqCst) { entered.notify_one(); proceed.notified().await; } + let Ok(tls) = acceptor.accept(connection).await else { return; }; + let Ok(mut socket) = tokio_tungstenite::accept_async(tls).await else { return; }; + while let Some(Ok(frame)) = socket.next().await { + match frame { + Message::Text(_) => { if socket.send(frame).await.is_err() { break; } } + Message::Ping(_) => { pings.fetch_add(1, Ordering::SeqCst); if socket.flush().await.is_err() { break; } } + Message::Close(_) => break, + _ => {} + } + } + }); + } + result = connections.join_next(), if !connections.is_empty() => { result.unwrap().unwrap(); } + } + } + }); + let calls = Arc::new(AtomicUsize::new(0)); + let registry = Arc::new(ProviderRegistry::new()); + registry + .register_sub_provider( + "exit", + Arc::new(Exit { + path, + calls: calls.clone(), + }), + ) + .await + .unwrap(); + state.provider_registry = Some(registry); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let app = gateway_router_with_api_url(state.clone(), format!("http://{addr}")); + let served = app.clone(); + let gateway = tokio::spawn(async move { + axum::serve(listener, served).await.unwrap(); + }); + Self { + data, + state, + app, + connector, + inbox, + home: owner.home_token, + addr, + calls, + pings, + pause_tls, + handshake, + resume, + gateway, + relay, + } + } + async fn route(&self, token: &str, path: &str, body: Option) -> (StatusCode, Value) { + self.route_as(&self.home, token, path, body).await + } + async fn route_as( + &self, + home: &str, + token: &str, + path: &str, + body: Option, + ) -> (StatusCode, Value) { + let hosted = + path == STORAGE || path.ends_with("relay-admission") || path.ends_with("host-config"); + let origin = if hosted { + format!("http://{}", self.addr) + } else { + "null".into() + }; + let response = self + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, self.addr.as_str()) + .header("origin", origin.as_str()) + .uri(path) + .method(if body.is_some() { "POST" } else { "GET" }) + .header("x-elastos-home-token", if hosted { home } else { token }) + .header("x-elastos-walletconnect-connector", token) + .header(CONTENT_TYPE, "application/json") + .body(body.map_or_else(Body::empty, |v| Body::from(v.to_string()))) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 2 * 1024 * 1024) + .await + .unwrap(); + ( + status, + serde_json::from_slice(&bytes) + .unwrap_or_else(|_| json!({"text":String::from_utf8_lossy(&bytes)})), + ) + } + async fn allow(&self) { + let (status, pending) = self + .route(&self.connector, INTERNET, Some(json!({"action":"request"}))) + .await; + assert_eq!(status, StatusCode::OK, "{pending}"); + self.answer(&pending, false).await; + } + async fn answer(&self, record: &Value, off: bool) { + let operation = if off { + gateway_walletconnect::REVOKE + } else { + gateway_walletconnect::GRANT + }; + let token = gateway_passkey_step_up::issue_passkey_step_up_token_for_test( + self.data.path(), + &self.inbox, + INBOX_CAPSULE_ID, + operation, + &record["request"], + ) + .unwrap(); + let (status, value) = self.route(&self.inbox, "/api/apps/inbox/actions", Some(json!({ + "action_id":format!("walletconnect-internet-{}:{}", if off {"turn-off"} else {"allow"}, record["request"]["id"].as_str().unwrap()), + "step_up_token":token, + }))).await; + assert_eq!(status, StatusCode::OK, "{value}"); + } + async fn connect( + &self, + token: &str, + relay: &str, + ) -> tokio_tungstenite::WebSocketStream> + { + let (_, admission) = self + .route( + token, + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ) + .await; + let ticket = admission["token"].as_str().unwrap_or("refused"); + self.connect_ticket(ticket, relay).await + } + async fn connect_ticket( + &self, + ticket: &str, + relay: &str, + ) -> tokio_tungstenite::WebSocketStream> + { + let (mut socket, _) = connect_async(format!( + "ws://{}/api/apps/wallet-walletconnect/relay", + self.addr + )) + .await + .unwrap(); + socket + .send(Message::Text( + json!({"token":ticket,"relay":relay}).to_string(), + )) + .await + .unwrap(); + socket + } + async fn ready( + &self, + ) -> tokio_tungstenite::WebSocketStream> + { + let mut socket = self.connect(&self.connector, RELAY).await; + assert_eq!( + tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .unwrap() + .unwrap() + .unwrap(), + Message::Text("{\"ready\":true}".into()) + ); + socket + } +} + +#[tokio::test] +async fn walletconnect_real_relay_requires_consent_allowlist_and_connector() { + let f = Fixture::new().await; + let mut denied = f.connect(&f.connector, RELAY).await; + assert!(matches!( + denied.next().await, + Some(Ok(Message::Close(_))) | None + )); + assert_eq!(f.calls.load(Ordering::SeqCst), 0); + f.allow().await; + for (token, url) in [ + (&f.inbox, RELAY), + ( + &f.connector, + "wss://evil.example/?projectId=test_walletconnect_project", + ), + ( + &f.connector, + "wss://relay.walletconnect.org:444/?projectId=test_walletconnect_project", + ), + ( + &f.connector, + "wss://relay.walletconnect.org/?projectId=another-project", + ), + ] { + let mut denied = f.connect(token, url).await; + assert!(matches!( + denied.next().await, + Some(Ok(Message::Close(_))) | None + )); + } + assert_eq!(f.calls.load(Ordering::SeqCst), 0); + let mut socket = f.ready().await; + socket + .send(Message::Text("encrypted-payload".into())) + .await + .unwrap(); + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Text("encrypted-payload".into()) + ); + assert_eq!(f.calls.load(Ordering::SeqCst), 1); + let (_, granted) = f.route(&f.inbox, INTERNET, None).await; + // Missing step-up cannot stop an existing grant. + let (status, _) = f.route(&f.inbox, "/api/apps/inbox/actions", Some(json!({"action_id":format!("walletconnect-internet-turn-off:{}", granted["request"]["id"].as_str().unwrap())}))).await; + assert_ne!(status, StatusCode::OK); + f.answer(&granted, true).await; + assert!(matches!( + socket.next().await, + Some(Ok(Message::Close(_))) | None + )); + let mut refused = f.connect(&f.connector, RELAY).await; + assert!(matches!( + refused.next().await, + Some(Ok(Message::Close(_))) | None + )); + assert_eq!(f.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn walletconnect_storage_is_principal_scoped_and_survives_service_restart() { + let mut f = Fixture::new().await; + let (status, _) = f + .route( + &f.connector, + STORAGE, + Some(json!({"key":"session","value":{"expiry":123,"secret":"fixture-only"}})), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, _) = f.route(&f.inbox, STORAGE, None).await; + assert_ne!(status, StatusCode::OK); + let other = passkey_authority_with_name(f.data.path(), Some("other-wc")); + let token = projection_launch_token_for_authority_context( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &other, + ); + let (status, values) = f.route_as(&other.home_token, &token, STORAGE, None).await; + assert_eq!(status, StatusCode::OK, "{values}"); + assert_eq!(values, json!({})); + f.state.walletconnect = Default::default(); + f.app = gateway_router_with_api_url(f.state.clone(), format!("http://{}", f.addr)); + let (_, values) = f.route(&f.connector, STORAGE, None).await; + assert_eq!(values["session"]["secret"], "fixture-only"); + let (status, _) = f + .route( + &f.connector, + STORAGE, + Some(json!({"key":"too-large", "value":"x".repeat(1024 * 1024)})), + ) + .await; + assert_ne!(status, StatusCode::OK); + let (_, values) = f.route(&f.connector, STORAGE, None).await; + assert!(values.get("too-large").is_none()); +} + +#[tokio::test] +async fn walletconnect_relay_enforces_quota_and_tls_authentication() { + let f = Fixture::new().await; + f.allow().await; + let mut first = f.ready().await; + let mut second = f.ready().await; + let mut third = f.connect(&f.connector, RELAY).await; + assert!(matches!( + third.next().await, + Some(Ok(Message::Close(_))) | None + )); + assert_eq!(f.calls.load(Ordering::SeqCst), 2); + let (_, granted) = f.route(&f.inbox, INTERNET, None).await; + f.answer(&granted, true).await; + assert!(matches!( + first.next().await, + Some(Ok(Message::Close(_))) | None + )); + assert!(matches!( + second.next().await, + Some(Ok(Message::Close(_))) | None + )); + // Restoring access with an empty root store refuses the fake certificate. + *f.state.walletconnect.tls.lock().unwrap() = Some(Arc::new( + rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(rustls::RootCertStore::empty()) + .with_no_client_auth(), + )); + f.allow().await; + let mut refused = f.connect(&f.connector, RELAY).await; + assert!(matches!( + refused.next().await, + Some(Ok(Message::Close(_))) | None + )); + assert_eq!(f.calls.load(Ordering::SeqCst), 3, "TLS refusal happens after Exit admission"); +} + +#[tokio::test] +async fn walletconnect_relay_heartbeats_and_expires_idle_connection() { + let f = Fixture::new().await; + f.allow().await; + let mut socket = f.ready().await; + // Pause only after the real TCP/TLS handshakes. Pongs keep heartbeat alive, + // while only application data extends the separate idle deadline. + // Keep this runtime runnable so paused time advances only when the test + // asks it to. Wait for a real upstream pong between every clock step. + let clock_guard = tokio::spawn(async { + loop { + tokio::task::yield_now().await; + } + }); + tokio::time::pause(); + let mut pongs = f.state.walletconnect.pongs.load(Ordering::Relaxed); + for _ in 0..19 { + tokio::time::advance(Duration::from_secs(15)).await; + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while f.state.walletconnect.pongs.load(Ordering::Relaxed) <= pongs { + assert!( + std::time::Instant::now() < deadline, + "upstream pong was not processed" + ); + tokio::task::yield_now().await; + } + pongs = f.state.walletconnect.pongs.load(Ordering::Relaxed); + } + // Last pong was at 285 s, within its 45 s limit. Only the 300 s idle + // deadline can close this connection at the next tick. + tokio::time::advance(Duration::from_secs(15)).await; + tokio::time::resume(); + clock_guard.abort(); + assert!(f.pings.load(Ordering::SeqCst) > 0); + assert!(matches!( + tokio::time::timeout(Duration::from_secs(3), socket.next()) + .await + .unwrap(), + Some(Ok(Message::Close(_))) | None + )); +} + +#[tokio::test] +async fn walletconnect_reconnects_after_runtime_service_restart_with_saved_principal_state() { + let mut f = Fixture::new().await; + f.allow().await; + let (status, _) = f + .route( + &f.connector, + STORAGE, + Some(json!({"key":"pairing", "value":{"topic":"fixture-topic"}})), + ) + .await; + assert_eq!(status, StatusCode::OK); + let mut first = f.ready().await; + first.close(None).await.unwrap(); + f.gateway.abort(); + let _ = (&mut f.gateway).await; + let tls = f.state.walletconnect.tls.lock().unwrap().clone(); + f.state.walletconnect = Default::default(); + f.state.browser_internet = persistent_internet(f.data.path()).await; + *f.state.walletconnect.tls.lock().unwrap() = tls; + let listener = TcpListener::bind(&f.addr).await.unwrap(); + f.app = gateway_router_with_api_url(f.state.clone(), format!("http://{}", f.addr)); + let app = f.app.clone(); + f.gateway = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let (_, stored) = f.route(&f.connector, STORAGE, None).await; + assert_eq!(stored["pairing"]["topic"], "fixture-topic"); + let mut restored = f.ready().await; + restored + .send(Message::Text("restored-session-request".into())) + .await + .unwrap(); + assert_eq!( + restored.next().await.unwrap().unwrap(), + Message::Text("restored-session-request".into()) + ); + assert_eq!(f.calls.load(Ordering::SeqCst), 2); +} + +#[tokio::test] +async fn walletconnect_refuses_malformed_writes_and_cross_principal_host_authority() { + let f = Fixture::new().await; + for body in [ + json!({"key":"session","value":"x","unknown":true}), + json!({"key":"session","value":"x".repeat(2 * 1024 * 1024)}), + ] { + let (status, _) = f.route(&f.connector, STORAGE, Some(body)).await; + assert_ne!(status, StatusCode::OK); + } + let (_, stored) = f.route(&f.connector, STORAGE, None).await; + assert_eq!(stored, json!({})); + let other = passkey_authority_with_name(f.data.path(), Some("different-host")); + for path in [ + STORAGE, + "/api/apps/wallet-walletconnect/relay-admission", + "/api/apps/wallet-walletconnect/host-config", + ] { + let (status, _) = f + .route_as(&other.home_token, &f.connector, path, Some(json!({}))) + .await; + assert_ne!(status, StatusCode::OK); + } + let response = f + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, f.addr.as_str()) + .header("origin", "null") + .uri(STORAGE) + .header("x-elastos-home-token", &f.connector) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_ne!( + response.status(), + StatusCode::OK, + "capsule authority cannot read SDK keys" + ); + assert_eq!(f.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn walletconnect_admissions_expire_and_can_be_used_once() { + let f = Fixture::new().await; + f.allow().await; + let (_, admission) = f + .route( + &f.connector, + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ) + .await; + let token = admission["token"].as_str().unwrap(); + let mut socket = f.connect_ticket(token, RELAY).await; + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Text("{\"ready\":true}".into()) + ); + let mut replay = f.connect_ticket(token, RELAY).await; + assert!(matches!( + replay.next().await, + Some(Ok(Message::Close(_))) | None + )); + let (_, admission) = f + .route( + &f.connector, + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ) + .await; + gateway_walletconnect::expire_admissions_for_test(&f.state).await; + let mut expired = f + .connect_ticket(admission["token"].as_str().unwrap(), RELAY) + .await; + assert!(matches!( + expired.next().await, + Some(Ok(Message::Close(_))) | None + )); + assert_eq!(f.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn walletconnect_turn_off_cancels_a_tls_handshake_and_can_reconnect() { + let f = Fixture::new().await; + f.allow().await; + f.pause_tls.store(true, Ordering::SeqCst); + let mut socket = f.connect(&f.connector, RELAY).await; + tokio::time::timeout(Duration::from_secs(5), f.handshake.notified()) + .await + .unwrap(); + let (_, granted) = f.route(&f.inbox, INTERNET, None).await; + f.answer(&granted, true).await; + assert!(matches!( + socket.next().await, + Some(Ok(Message::Close(_))) | None + )); + f.pause_tls.store(false, Ordering::SeqCst); + f.resume.notify_one(); + f.allow().await; + let _restored = f.ready().await; + assert_eq!(f.calls.load(Ordering::SeqCst), 2); +} + +#[tokio::test] +async fn walletconnect_revoked_owner_cannot_send_another_relay_frame() { + let f = Fixture::new().await; + f.allow().await; + let mut socket = f.ready().await; + let owner = crate::auth::list_passkey_principals(f.data.path()) + .unwrap() + .into_iter() + .find(crate::auth::is_admin) + .unwrap(); + crate::auth::revoke_passkey_binding(f.data.path(), &owner.proof_binding_id, now_ts()).unwrap(); + socket + .send(Message::Text("refused-after-owner-revoke".into())) + .await + .unwrap(); + assert!(matches!( + tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .unwrap(), + Some(Ok(Message::Close(_))) | None + )); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_transaction_effects.rs b/elastos/crates/elastos-server/src/api/gateway_transaction_effects.rs index e25eb40bb..00ed37679 100644 --- a/elastos/crates/elastos-server/src/api/gateway_transaction_effects.rs +++ b/elastos/crates/elastos-server/src/api/gateway_transaction_effects.rs @@ -3461,6 +3461,7 @@ mod approved_request_resume_tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(OnceLock::new()), cache_dir: root.join("cache"), data_dir: root.join("data"), diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index b6ab198f0..660cd6fe9 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -282,7 +282,7 @@ pub(in crate::api::gateway) async fn approve_external_wallet_request( wallet_connector_label(capsule_id) ), handoff, - approval_request: None, + approval_request: data.get("approval_request").cloned(), }) } @@ -508,6 +508,11 @@ pub(in crate::api::gateway) fn system_wallet_approval_summary( reason: value.get("reason")?.as_str()?.to_string(), account_id: value.get("account_id")?.as_str()?.to_string(), address: value.get("address")?.as_str()?.to_string(), + chain_namespace: value + .get("chain_namespace") + .and_then(|v| v.as_str()) + .unwrap_or_default() + .to_string(), proof_type: value .get("proof_type") .and_then(|value| value.as_str()) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index bd428b821..d85b2de3b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -165,10 +165,7 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_complete( } fn require_capsule_owned_connector_effects(connector_id: &str) -> anyhow::Result<()> { - if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { - return Ok(()); - } - if connector_id == WALLET_METAMASK_CAPSULE_ID || connector_id == WALLET_UNISAT_CAPSULE_ID { + if is_wallet_connector_capsule_id(connector_id) { anyhow::bail!( "wallet connector injected-wallet effects require the trusted Home host bridge" ); @@ -218,11 +215,10 @@ pub(crate) fn ensure_wallet_connector_configured( validate_walletconnect_connector_config(&config)?; let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); - let bytes = std::fs::read(&sdk_path).map_err(|err| { - anyhow::anyhow!( - "WalletConnect connector is not configured: pinned SDK asset missing ({err})" - ) - })?; + let bytes = + gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)?.ok_or_else(|| { + anyhow::anyhow!("WalletConnect connector is not configured: pinned SDK asset missing") + })?; let digest = format!("{:x}", Sha256::digest(&bytes)); if !digest.eq_ignore_ascii_case(config.sdk_sha256.trim()) { anyhow::bail!("WalletConnect connector is not configured: pinned SDK hash mismatch"); @@ -233,9 +229,14 @@ pub(crate) fn ensure_wallet_connector_configured( pub(in crate::api::gateway) fn load_walletconnect_connector_config( data_dir: &FsPath, ) -> anyhow::Result { - let path = data_dir.join(WALLETCONNECT_CONFIG_PATH); - let bytes = std::fs::read(&path).map_err(|err| { - anyhow::anyhow!("WalletConnect connector is not configured: pinned config missing ({err})") + let operator = data_dir.join(WALLETCONNECT_CONFIG_PATH); + let path = if operator.try_exists()? { + operator + } else { + data_dir.join("capsules/wallet-walletconnect/vendor/connector.json") + }; + let bytes = gateway_walletconnect::read_bytes(&path, 8192)?.ok_or_else(|| { + anyhow::anyhow!("WalletConnect connector is not configured: pinned config missing") })?; serde_json::from_slice(&bytes).map_err(|err| { anyhow::anyhow!("WalletConnect connector is not configured: invalid pinned config ({err})") diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs new file mode 100644 index 000000000..08cd08363 --- /dev/null +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -0,0 +1,765 @@ +//! WalletConnect transport consent. Wallet proofs and signing authority stay in wallet-provider. +use super::*; +use super::gateway_browser::provider_response_data; +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use elastos_runtime::capability::{Action, CapabilityToken, ResourceId, TokenConstraints}; +use serde_json::json; +use std::io::Read; +use tokio::sync::{watch, Mutex}; +use tokio::time::Instant; + +pub(super) const GRANT: &str = "walletconnect.internet.grant"; +pub(super) const REVOKE: &str = "walletconnect.internet.revoke"; +const CONSENT: &str = "WalletConnect uses this computer's internet connection to reach the wallet relay. The relay can see the connection address. Your phone wallet holds your keys and approves each request. You can turn this connection off here in Inbox."; +const MAX_BYTES: usize = 1024 * 1024; +const MAX_SOCKETS: usize = 2; +const RESOURCE: &str = "elastos://walletconnect/internet"; + +#[derive(Default)] +pub(crate) struct WalletConnectService { + inner: Mutex, + #[cfg(test)] + pub(in crate::api::gateway) pongs: std::sync::atomic::AtomicUsize, + #[cfg(test)] + pub(in crate::api::gateway) tls: std::sync::Mutex>>, +} +#[derive(Default)] +struct Inner { + sockets: BTreeMap, + admissions: BTreeMap, +} +struct SocketOwner { + principal: String, + cancel: watch::Sender, + done: watch::Receiver, +} +struct SocketCompletion(watch::Sender); +impl Drop for SocketCompletion { + fn drop(&mut self) { + self.0.send_replace(true); + } +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Consent { + status: String, + id: String, + at: u64, + principal: Option, + proof: Option, + capability: Option, +} + +fn root(data: &FsPath) -> PathBuf { + data.join("ElastOS/SystemServices/WalletConnect") +} +pub(super) fn read_bytes(path: &FsPath, limit: usize) -> anyhow::Result>> { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = match options.open(path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.into()), + }; + anyhow::ensure!( + file.metadata()?.is_file(), + "WalletConnect state requires a regular file" + ); + let mut bytes = Vec::new(); + file.take(limit as u64 + 1).read_to_end(&mut bytes)?; + anyhow::ensure!( + bytes.len() <= limit, + "WalletConnect state exceeds its limit" + ); + Ok(Some(bytes)) +} +fn read(path: &FsPath, limit: usize) -> anyhow::Result> { + read_bytes(path, limit)? + .map(|bytes| serde_json::from_slice(&bytes).map_err(Into::into)) + .transpose() +} +fn load(data: &FsPath) -> anyhow::Result> { + read(&root(data).join("internet.json"), 8192) +} +fn save(data: &FsPath, value: &Consent) -> anyhow::Result<()> { + crate::auth::atomic_write( + &root(data).join("internet.json"), + &serde_json::to_vec(value)?, + ) +} +fn request(c: &Consent) -> anyhow::Result { + anyhow::ensure!( + c.status == "granted" || (c.status == "requested" && c.at + 1800 > now_ts()), + "Review the current WalletConnect request in Inbox" + ); + Ok( + json!({"resource":"elastos://walletconnect/internet", "id":c.id, "issued_at":c.at, + "text":if c.status == "granted" { "Stop WalletConnect relay access on this computer." } else { CONSENT }}), + ) +} +fn public(c: Option<&Consent>) -> serde_json::Value { + match c { + Some(c) => json!({"status":c.status, "request":request(c).ok()}), + None => json!({"status":"off"}), + } +} +async fn check_owner(state: &GatewayState) -> anyhow::Result<()> { + let data = &state.data_dir; + let c = load(data)? + .ok_or_else(|| anyhow::anyhow!("Review WalletConnect internet access in Inbox"))?; + anyhow::ensure!( + c.status == "granted", + "Review WalletConnect internet access in Inbox" + ); + let owner = crate::auth::load_principal_for_proof_binding( + data, + c.proof.as_deref().unwrap_or_default(), + )?; + crate::auth::ensure_proof_binding_not_revoked(&owner)?; + anyhow::ensure!( + Some(&owner.principal_id) == c.principal.as_ref() && crate::auth::is_admin(&owner), + "WalletConnect internet consent needs its active owner" + ); + let token = CapabilityToken::from_base64(c.capability.as_deref().unwrap_or_default()) + .map_err(anyhow::Error::msg)?; + state + .browser_internet + .capability_manager()? + .validate( + &token, + &owner.principal_id, + Action::Execute, + &ResourceId::new(RESOURCE), + None, + ) + .await?; + Ok(()) +} +pub(super) async fn step_up_request( + state: &GatewayState, + launch: &RequiredHomeLaunchToken, + op: &str, +) -> anyhow::Result { + ensure_admin_context(&state.data_dir, &launch.context)?; + anyhow::ensure!( + launch.launch_context.executable_actor == INBOX_CAPSULE_ID, + "Inbox launch required" + ); + let _guard = state.walletconnect.inner.lock().await; + let c = load(&state.data_dir)?.ok_or_else(|| anyhow::anyhow!("Open WalletConnect first"))?; + anyhow::ensure!( + (op == GRANT && c.status == "requested") || (op == REVOKE && c.status == "granted"), + "WalletConnect request has changed" + ); + request(&c) +} +pub(super) async fn answer( + state: &GatewayState, + launch: &RequiredHomeLaunchToken, + action: &str, + token: Option<&str>, +) -> anyhow::Result { + ensure_admin_context(&state.data_dir, &launch.context)?; + anyhow::ensure!( + launch.launch_context.executable_actor == INBOX_CAPSULE_ID, + "Inbox launch required" + ); + let mut inner = state.walletconnect.inner.lock().await; + let mut c = + load(&state.data_dir)?.ok_or_else(|| anyhow::anyhow!("Open WalletConnect first"))?; + let (verb, id) = action + .strip_prefix("walletconnect-internet-") + .and_then(|v| v.split_once(':')) + .ok_or_else(|| anyhow::anyhow!("Invalid WalletConnect internet action"))?; + anyhow::ensure!(id == c.id, "WalletConnect request has changed"); + match verb { + "deny" => { + anyhow::ensure!(c.status == "requested", "WalletConnect request has changed"); + c.status = "refused".into(); + } + "allow" | "turn-off" => { + let stopping = verb == "turn-off"; + if !(stopping && c.status == "revoked") { + anyhow::ensure!( + c.status == if stopping { "granted" } else { "requested" }, + "WalletConnect request has changed" + ); + consume_passkey_step_up_token( + &state.data_dir, + token.unwrap_or_default(), + launch, + 180, + if stopping { REVOKE } else { GRANT }, + &request(&c)?, + )?; + c.status = if stopping { "revoked" } else { "granted" }.into(); + c.principal = Some(launch.context.principal_id.clone()); + c.proof = launch.context.proof_binding_id.clone(); + if !stopping { + let capability = state.browser_internet.capability_manager()?.grant( + &launch.context.principal_id, + ResourceId::new(RESOURCE), + Action::Execute, + TokenConstraints::default(), + None, + ); + c.capability = Some(capability.to_base64().map_err(anyhow::Error::msg)?); + } + save(&state.data_dir, &c)?; + } + if stopping { + // Registration and Turn Off share this lock. Persist first so a restart + // also refuses access, then wait until both network ends are dropped. + inner.admissions.clear(); + for socket in inner.sockets.values() { + socket.cancel.send_replace(true); + } + for socket in inner.sockets.values_mut() { + tokio::time::timeout( + Duration::from_secs(3), + socket.done.wait_for(|done| *done), + ) + .await??; + } + inner.sockets.clear(); + if let Some(encoded) = &c.capability { + let capability = + CapabilityToken::from_base64(encoded).map_err(anyhow::Error::msg)?; + state + .browser_internet + .capability_manager()? + .revoke(*capability.id(), "WalletConnect internet stopped") + .await?; + } + return Ok("WalletConnect connection turned off.".into()); + } + } + _ => anyhow::bail!("Invalid WalletConnect internet action"), + } + save(&state.data_dir, &c)?; + Ok("WalletConnect internet choice saved.".into()) +} +pub(super) fn notification( + state: &GatewayState, + context: &HomeLaunchTokenContext, +) -> Option { + ensure_admin_context(&state.data_dir, context).ok()?; + let c = load(&state.data_dir).ok()??; + let pending = c.status == "requested" && request(&c).is_ok(); + let active = c.status == "granted" + || (c.status == "revoked" + && state + .walletconnect + .inner + .try_lock() + .ok() + .is_some_and(|inner| !inner.sockets.is_empty())); + Some(HomeNotificationEntrySummary { + id: "walletconnect-internet:permission".into(), + source_app: WALLET_WALLETCONNECT_CAPSULE_ID.into(), + kind: if pending { + "walletconnect_internet_request" + } else { + "walletconnect_internet_decision" + } + .into(), + title: "WalletConnect internet access".into(), + body: if pending { + CONSENT + } else if c.status == "granted" { + "WalletConnect can reach the wallet relay." + } else { + "WalletConnect relay access is off." + } + .into(), + severity: if pending { "attention" } else { "info" }.into(), + read: !pending, + created_at: c.at, + action_ref: if pending || active { + Some(HomeNotificationActionSummary { + app: INBOX_CAPSULE_ID.into(), + action_id: format!( + "walletconnect-internet-{}:{}", + if pending { "allow" } else { "turn-off" }, + c.id + ), + }) + } else { + None + }, + }) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct InternetAction { + action: String, +} +pub(super) async fn internet( + State(state): State, + method: axum::http::Method, + headers: HeaderMap, + input: Result, axum::extract::rejection::JsonRejection>, +) -> Response { + let result = async { + let authority = require_runtime_wallet_authority( + &state.data_dir, + &headers, + &[WALLET_WALLETCONNECT_CAPSULE_ID, INBOX_CAPSULE_ID], + )?; + let inner = state.walletconnect.inner.lock().await; + if method == axum::http::Method::POST { + let Json(input) = input.map_err(|_| { + anyhow::anyhow!("WalletConnect request body is invalid or exceeds its limit") + })?; + anyhow::ensure!( + input.action == "request", + "Invalid WalletConnect internet action" + ); + ensure_admin_context(&state.data_dir, &authority.home_launch_context())?; + let c = load(&state.data_dir)?; + if c.as_ref().is_none_or(|c| { + c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts()) + }) { + anyhow::ensure!( + inner.sockets.values().all(|s| *s.done.borrow()), + "Finish stopping WalletConnect first" + ); + save( + &state.data_dir, + &Consent { + status: "requested".into(), + id: gateway_home_token::uuid_like_token(), + at: now_ts(), + principal: None, + proof: None, + capability: None, + }, + )?; + } + } + Ok::<_, anyhow::Error>(public(load(&state.data_dir)?.as_ref())) + } + .await; + match result { + Ok(v) => Json(v).into_response(), + Err(e) => system_error_response(e), + } +} + +fn hosted(state: &GatewayState, headers: &HeaderMap) -> anyhow::Result { + let connector = headers + .get("x-elastos-walletconnect-connector") + .and_then(|h| h.to_str().ok()) + .ok_or_else(|| anyhow::anyhow!("Home wallet connector authority is required"))?; + Ok( + gateway_home_wallet_connector::require_home_wallet_connector_authority( + state, + headers, + "elastos.home.wallet-connector.effect.request/v1", + WALLET_WALLETCONNECT_CAPSULE_ID, + connector, + WALLET_WALLETCONNECT_CAPSULE_ID, + )? + .wallet, + ) +} +#[cfg(test)] +pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayState) { + for (expiry, _) in state + .walletconnect + .inner + .lock() + .await + .admissions + .values_mut() + { + *expiry = 0; + } +} +pub(super) async fn admission(State(state): State, headers: HeaderMap) -> Response { + let result = async { + let _ = hosted(&state, &headers)?; + let mut inner = state.walletconnect.inner.lock().await; + check_owner(&state).await?; + inner.admissions.retain(|_, (expiry, _)| *expiry > now_ts()); + anyhow::ensure!( + inner.admissions.len() < 128, + "WalletConnect admission quota exceeded" + ); + let token = gateway_home_token::uuid_like_token(); + inner + .admissions + .insert(token.clone(), (now_ts() + 15, headers)); + Ok::<_, anyhow::Error>(json!({"token":token})) + } + .await; + private_response(result) +} +pub(super) async fn host_config( + State(state): State, + method: axum::http::Method, + headers: HeaderMap, +) -> Response { + let result = async { + let authority = hosted(&state, &headers)?; + let inner = state.walletconnect.inner.lock().await; + let c = load(&state.data_dir)?; + if method == axum::http::Method::POST && c.as_ref().is_none_or(|c| c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts())) { + ensure_admin_context(&state.data_dir, &authority.home_launch_context())?; + anyhow::ensure!(inner.sockets.values().all(|s| *s.done.borrow()), "Finish stopping WalletConnect first"); + save(&state.data_dir, &Consent { status:"requested".into(), id:gateway_home_token::uuid_like_token(), at:now_ts(), principal:None, proof:None, capability:None })?; + } + let config = load_walletconnect_connector_config(&state.data_dir)?; + Ok::<_, anyhow::Error>(json!({"projectId":config.project_id, "principal_id":authority.home_launch_context().principal_id, + "internet":public(load(&state.data_dir)?.as_ref()), + "sdk_asset_path":"/apps/wallet-walletconnect/vendor/reown-appkit.js"})) + }.await; + private_response(result) +} +fn private_response(result: anyhow::Result) -> Response { + let mut response = match result { + Ok(value) => Json(value).into_response(), + Err(error) => system_error_response(error), + }; + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + response +} + +// Only the verified connector can read its principal's SDK key/value state. Keys +// are never path components; the principal's Runtime identity selects the file. +fn storage_path(data: &FsPath, principal: &str) -> PathBuf { + root(data).join("sessions").join(format!( + "{}.json", + hex::encode(Sha256::digest(principal.as_bytes())) + )) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct StorageWrite { + key: String, + value: Option, +} +pub(super) async fn storage( + State(state): State, + method: axum::http::Method, + headers: HeaderMap, + input: Result, axum::extract::rejection::JsonRejection>, +) -> Response { + let result = async { + let authority = hosted(&state, &headers)?; + let _guard = state.walletconnect.inner.lock().await; + let path = storage_path( + &state.data_dir, + &authority.home_launch_context().principal_id, + ); + let mut values: BTreeMap = + read(&path, MAX_BYTES)?.unwrap_or_default(); + if method == axum::http::Method::POST { + let Json(input) = input.map_err(|_| { + anyhow::anyhow!("WalletConnect request body is invalid or exceeds its limit") + })?; + anyhow::ensure!( + !input.key.is_empty() && input.key.len() <= 256, + "Invalid WalletConnect storage key" + ); + if let Some(value) = input.value { + values.insert(input.key, value); + } else { + values.remove(&input.key); + } + let bytes = serde_json::to_vec(&values)?; + anyhow::ensure!( + values.len() <= 256 && bytes.len() <= MAX_BYTES, + "WalletConnect session storage quota exceeded" + ); + crate::auth::atomic_write(&path, &bytes)?; + } + Ok::<_, anyhow::Error>(values) + } + .await; + private_response(result) +} + +fn relay_url(value: &str, project: &str) -> anyhow::Result { + anyhow::ensure!( + value.len() <= 8192, + "WalletConnect relay URL exceeds its limit" + ); + let url = url::Url::parse(value)?; + anyhow::ensure!( + url.scheme() == "wss" + && url.port_or_known_default() == Some(443) + && matches!( + url.host_str(), + Some("relay.walletconnect.com" | "relay.walletconnect.org") + ) + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + && url.path() == "/", + "WalletConnect relay is outside the allowlist" + ); + let ids: Vec<_> = url + .query_pairs() + .filter(|(k, _)| k == "projectId") + .map(|(_, v)| v.into_owned()) + .collect(); + anyhow::ensure!(ids == [project], "WalletConnect relay project has changed"); + Ok(url) +} +fn check_liveness(pong: Duration, activity: Duration) -> anyhow::Result<()> { + anyhow::ensure!( + pong < Duration::from_secs(45), + "WalletConnect heartbeat expired" + ); + anyhow::ensure!( + activity < Duration::from_secs(300), + "WalletConnect idle limit expired" + ); + Ok(()) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RelayHello { + token: String, + relay: String, +} +pub(super) async fn relay(State(state): State, ws: WebSocketUpgrade) -> Response { + // Authority travels in the first bounded frame, never in a URL or log. + ws.max_message_size(64 * 1024) + .max_frame_size(64 * 1024) + .on_upgrade(move |mut socket| async move { + let _ = relay_connection(&state, &mut socket).await; + // Error messages can contain upstream auth URLs. Keep them private. + let _ = socket.close().await; + }) +} +async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyhow::Result<()> { + let hello = tokio::time::timeout(Duration::from_secs(5), socket.recv()) + .await? + .ok_or_else(|| anyhow::anyhow!("WalletConnect transport closed"))??; + let hello = hello.into_data(); + anyhow::ensure!( + hello.len() <= 16 * 1024, + "WalletConnect hello exceeds its limit" + ); + let hello: RelayHello = serde_json::from_slice(&hello)?; + let headers = { + let mut inner = state.walletconnect.inner.lock().await; + let (expiry, headers) = inner + .admissions + .remove(&hello.token) + .ok_or_else(|| anyhow::anyhow!("Home transport admission required"))?; + anyhow::ensure!(expiry > now_ts(), "WalletConnect admission expired"); + headers + }; + let authority = hosted(state, &headers)?; + let config = load_walletconnect_connector_config(&state.data_dir)?; + let url = relay_url(&hello.relay, &config.project_id)?; + let principal = authority.home_launch_context().principal_id.clone(); + let id = gateway_home_token::uuid_like_token(); + let (cancel, mut cancelled) = watch::channel(false); + let (done, finished) = watch::channel(false); + let completion = SocketCompletion(done); + { + let mut inner = state.walletconnect.inner.lock().await; + check_owner(state).await?; + inner.sockets.retain(|_, s| !*s.done.borrow()); + anyhow::ensure!( + inner + .sockets + .values() + .filter(|s| s.principal == principal) + .count() + < MAX_SOCKETS, + "WalletConnect connection quota exceeded" + ); + inner.sockets.insert( + id.clone(), + SocketOwner { + principal, + cancel, + done: finished, + }, + ); + } + // All network work is inside the cancellation branch, including Exit admission, + // TLS and the upstream WebSocket handshake. Dropping it closes the transport. + let result = tokio::select! { + biased; + _ = cancelled.changed() => Ok(()), + result = transport(state, &headers, socket, url) => result, + }; + let _ = tokio::time::timeout(Duration::from_secs(1), socket.send(Message::Close(None))).await; + // Turn Off can hold the lock while it waits for done, so signal before removal. + drop(completion); + state.walletconnect.inner.lock().await.sockets.remove(&id); + result +} + +#[cfg(unix)] +async fn transport( + state: &GatewayState, + headers: &HeaderMap, + socket: &mut WebSocket, + url: url::Url, +) -> anyhow::Result<()> { + use futures_util::{SinkExt, StreamExt}; + use tokio::io::AsyncWriteExt; + use tokio_tungstenite::tungstenite::{ + client::IntoClientRequest, protocol::WebSocketConfig, Message as Upstream, + }; + let host = url.host_str().unwrap(); + let authority = hosted(state, headers)?; + let principal = authority.home_launch_context().principal_id; + let registry = state + .provider_registry + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Exit provider is unavailable"))?; + let target = format!("tls://{host}:443"); + let response = tokio::time::timeout(Duration::from_secs(10), registry.send_raw("exit", &json!({ + "op":"open_stream", "target":target, "principal_id":principal, + "reason":"WalletConnect relay", "stream_nonce":gateway_home_token::uuid_like_token(), + }))).await??; + let receipt = provider_response_data(&response) + .ok_or_else(|| anyhow::anyhow!("Exit admission failed"))?; + anyhow::ensure!( + receipt["schema"] == "elastos.exit.stream-session/v1" + && receipt["target"] == target + && receipt["principal_id"] == principal + && receipt["byte_transport"] == "adapter_ipc" + && receipt["relay_ipc"]["schema"] == "elastos.exit.relay-ipc/v1" + && receipt["relay_ipc"]["kind"] == "unix_socket", + "WalletConnect requires the local Exit transport" + ); + let path = receipt["relay_ipc"]["path"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("Exit relay is unavailable"))?; + anyhow::ensure!( + FsPath::new(path).is_absolute(), + "Exit relay path must be absolute" + ); + let open = async { + let mut stream = tokio::net::UnixStream::connect(path).await?; + stream.write_all(format!("{}\n", json!({"schema":"elastos.exit.relay-open/v1", "stream_id":receipt["stream_id"], + "target":target,"scheme":"tls","host":host,"principal_id":principal,"reason":"WalletConnect relay"})).as_bytes()).await?; + let config = WebSocketConfig { + max_message_size: Some(64 * 1024), + max_frame_size: Some(64 * 1024), + ..Default::default() + }; + // Rustls authenticates the relay hostname using the release's root store; + // Exit forwards TLS bytes and never holds WalletConnect session keys. + #[cfg(test)] + let connector = state + .walletconnect + .tls + .lock() + .unwrap() + .clone() + .map(tokio_tungstenite::Connector::Rustls); + #[cfg(not(test))] + let connector = None; + let mut request = url.as_str().into_client_request()?; + request.headers_mut().insert( + "origin", + gateway_home_token::home_browser_origin(headers)?.parse()?, + ); + let (upstream, _) = tokio_tungstenite::client_async_tls_with_config( + request, + stream, + Some(config), + connector, + ) + .await?; + Ok::<_, anyhow::Error>(upstream) + }; + let mut upstream = tokio::time::timeout(Duration::from_secs(15), open).await??; + socket + .send(Message::Text("{\"ready\":true}".into())) + .await?; + let mut heartbeat = tokio::time::interval(Duration::from_secs(15)); + let mut pong = Instant::now(); + let mut activity = Instant::now(); + loop { + tokio::select! { + _ = heartbeat.tick() => { + hosted(state, headers)?; + check_owner(state).await?; + check_liveness(pong.elapsed(), activity.elapsed())?; + tokio::time::timeout(Duration::from_secs(5), upstream.send(Upstream::Ping(Vec::new()))).await??; + } + frame = upstream.next() => match frame.transpose()? { + Some(Upstream::Text(text)) => { + activity = Instant::now(); + tokio::time::timeout(Duration::from_secs(5), socket.send(Message::Text(text))).await??; + } + Some(Upstream::Pong(_)) => { + pong = Instant::now(); + #[cfg(test)] + state.walletconnect.pongs.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + }, + Some(Upstream::Ping(_)) => { tokio::time::timeout(Duration::from_secs(5), upstream.flush()).await??; } + Some(Upstream::Close(_)) | None => break, + _ => anyhow::bail!("WalletConnect relay requires text frames"), + }, + frame = socket.recv() => match frame.transpose()? { + Some(Message::Text(text)) => { + hosted(state, headers)?; + check_owner(state).await?; + activity = Instant::now(); + tokio::time::timeout(Duration::from_secs(5), upstream.send(Upstream::Text(text))).await??; + } + Some(Message::Close(_)) | None => break, + Some(Message::Pong(_)) | Some(Message::Ping(_)) => {}, + _ => anyhow::bail!("WalletConnect requires text frames"), + }, + } + } + Ok(()) +} +#[cfg(not(unix))] +async fn transport( + _state: &GatewayState, + _headers: &HeaderMap, + _socket: &mut WebSocket, + _url: url::Url, +) -> anyhow::Result<()> { + anyhow::bail!("The local Exit transport is unavailable on this platform") +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn walletconnect_socket_completion_survives_task_unwind() { + let (done, finished) = watch::channel(false); + let completion = SocketCompletion(done); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _completion = completion; + panic!("fixture task failure"); + })); + assert!(panic.is_err()); + assert!(*finished.borrow()); + } + #[test] + fn walletconnect_heartbeat_and_idle_have_independent_deadlines() { + assert!(check_liveness(Duration::from_secs(44), Duration::from_secs(299)).is_ok()); + assert!(check_liveness(Duration::from_secs(45), Duration::ZERO) + .unwrap_err() + .to_string() + .contains("heartbeat")); + assert!(check_liveness(Duration::ZERO, Duration::from_secs(300)) + .unwrap_err() + .to_string() + .contains("idle")); + } +} diff --git a/elastos/crates/elastos-server/src/collaboration_startup.rs b/elastos/crates/elastos-server/src/collaboration_startup.rs index 366d543b5..0a812a38c 100644 --- a/elastos/crates/elastos-server/src/collaboration_startup.rs +++ b/elastos/crates/elastos-server/src/collaboration_startup.rs @@ -1658,6 +1658,7 @@ mod tests { collaboration_discovery_service: gateway_context.discovery_service.clone(), carrier_endpoint: gateway_context.carrier_endpoint.clone(), browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: temp.path().join("gateway-cache"), data_dir: temp.path().to_path_buf(), @@ -1842,6 +1843,7 @@ mod tests { carrier_endpoint: None, collaboration_discovery_service: None, browser_internet: Default::default(), + walletconnect: Default::default(), identity_manager: Arc::new(std::sync::OnceLock::new()), cache_dir: temp.path().join("gateway-cache"), data_dir: temp.path().to_path_buf(), diff --git a/elastos/crates/elastos-server/src/publish.rs b/elastos/crates/elastos-server/src/publish.rs index 0c8b8049f..a12c68dbb 100644 --- a/elastos/crates/elastos-server/src/publish.rs +++ b/elastos/crates/elastos-server/src/publish.rs @@ -25,6 +25,7 @@ const HOME_PUBLISH_CAPSULES: &[&str] = &[ "people", "wallet-metamask", "wallet-unisat", + "wallet-walletconnect", "wallet", "browser", "documents", @@ -2281,12 +2282,7 @@ mod tests { assert_eq!(selected, expected); assert!(selected.contains(&"archive-manager".to_string())); // Hidden in 0.8.0: still published as release assets for `setup --with`. - for hidden in [ - "services", - "wallet-walletconnect", - "content-block-graph-provider", - "elacity-player", - ] { + for hidden in ["services", "content-block-graph-provider", "elacity-player"] { assert!(!selected.contains(&hidden.to_string()), "{hidden}"); } assert!(selected.contains(&"chain-provider".to_string())); diff --git a/elastos/crates/elastos-server/src/server_infra.rs b/elastos/crates/elastos-server/src/server_infra.rs index c575eed6e..2410dba72 100644 --- a/elastos/crates/elastos-server/src/server_infra.rs +++ b/elastos/crates/elastos-server/src/server_infra.rs @@ -1197,12 +1197,24 @@ async fn setup_server_infrastructure_impl( // Retained Browser helpers from an earlier release stay stopped where // Browser is unavailable. - let browser_available = - elastos_server::setup::browser_available(&elastos_server::setup::detect_platform()); - if let Some(local_exit_config) = browser_available + let platform = elastos_server::setup::detect_platform(); + let browser_available = elastos_server::setup::browser_available(&platform); + let walletconnect_exit = elastos_server::setup::walletconnect::local_exit(&data_dir, &platform); + let browser_exit = browser_available .then(|| browser_local_exit_config_from_env(&data_dir)) - .flatten() - { + .flatten(); + for (name, config) in [ + ("browser-local-exit", browser_exit), + ( + "walletconnect-local-exit", + walletconnect_exit + .as_ref() + .map(|(helper, _)| helper.clone()), + ), + ] { + let Some(local_exit_config) = config else { + continue; + }; if let Some(path) = crate::find_installed_provider_binary("browser-local-exit") { if let Err(e) = verify_provider_binary("browser-local-exit", &path) { tracing::warn!( @@ -1212,13 +1224,10 @@ async fn setup_server_infrastructure_impl( } else { match spawn_browser_local_exit(&path, &local_exit_config) { Ok(child) => { - tracing::info!("browser-local-exit helper from {}", path.display()); - managed_host_processes.push(api::server::HostHelperProcess { - name: "browser-local-exit", - child, - }); + tracing::info!("{name} helper from {}", path.display()); + managed_host_processes.push(api::server::HostHelperProcess { name, child }); } - Err(e) => tracing::warn!("Failed to spawn browser-local-exit: {}", e), + Err(e) => tracing::warn!("Failed to spawn {name}: {}", e), } } } else { @@ -1230,8 +1239,20 @@ async fn setup_server_infrastructure_impl( match binaries::resolve_verified_native_provider_binary("exit-provider") { Ok(Some(path)) => { + let existing_exit = + exit_provider_config_from_env(&data_dir).unwrap_or(serde_json::Value::Null); + let extra = match elastos_server::setup::walletconnect::merge_exit_config( + existing_exit.clone(), + walletconnect_exit.as_ref().map(|(_, provider)| provider), + ) { + Ok(config) => config, + Err(error) => { + tracing::warn!(%error, "Exit configuration needs repair"); + existing_exit + } + }; let exit_config = provider::BridgeProviderConfig { - extra: exit_provider_config_from_env(&data_dir).unwrap_or(serde_json::Value::Null), + extra, ..Default::default() }; match provider::ProviderBridge::spawn(&path, exit_config).await { diff --git a/elastos/crates/elastos-server/src/setup.rs b/elastos/crates/elastos-server/src/setup.rs index 57c051387..4f5b36819 100644 --- a/elastos/crates/elastos-server/src/setup.rs +++ b/elastos/crates/elastos-server/src/setup.rs @@ -5,6 +5,7 @@ //! bounded preparation path, not this archive installer. use crate::api::capsule_inventory::MAX_MODEL_CATALOG_BYTES; +pub mod walletconnect; use anyhow::Context as _; use serde::{Deserialize, Serialize}; use sha2::Digest; @@ -5908,7 +5909,6 @@ pub(crate) mod tests { // download either); each stays installable with `setup --with`. let hidden = [ "services", - "wallet-walletconnect", "content-block-graph-provider", "elacity-player", "protected-content-protect-provider", diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs new file mode 100644 index 000000000..a4cc3ce85 --- /dev/null +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -0,0 +1,119 @@ +//! Relay-only defaults for a configured WalletConnect Home, independent of a Browser VM. +use std::path::Path; + +pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, serde_json::Value)> { + crate::api::gateway::ensure_wallet_connector_configured(data, "wallet-walletconnect").ok()?; + if !matches!(platform, "darwin-arm64" | "linux-amd64" | "linux-arm64") { return None; } + let socket = data.join("walletconnect-exit.sock"); + let hosts = ["relay.walletconnect.org", "relay.walletconnect.com"]; + let helper = serde_json::json!({ + "schema":"elastos.browser.local-exit.config/v1", "relay_ipc_path":socket, + "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], + "replace_existing_socket":true, + }); + let provider = serde_json::json!({"backends":[{ + "id":"walletconnect-local-exit", "kind":"stream_relay", + "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], + "adapter_ipc":{"kind":"unix_socket","path":socket}, + "relay_ipc":{"kind":"unix_socket","path":socket}, + }]}); + Some((helper, provider)) +} + +/// Keep the owner's existing Exit configuration and add only the relay-local backend. +pub fn merge_exit_config( + mut existing: serde_json::Value, + walletconnect: Option<&serde_json::Value>, +) -> anyhow::Result { + let Some(walletconnect) = walletconnect else { + return Ok(existing); + }; + if existing.is_null() { + existing = serde_json::json!({}); + } + let object = existing + .as_object_mut() + .ok_or_else(|| anyhow::anyhow!("Exit configuration must be an object"))?; + let backends = object + .entry("backends") + .or_insert_with(|| serde_json::json!([])) + .as_array_mut() + .ok_or_else(|| anyhow::anyhow!("Exit backends must be a list"))?; + let managed = &walletconnect["backends"][0]; + if let Some(previous) = backends.iter().find(|b| b["id"] == managed["id"]) { + anyhow::ensure!( + previous == managed, + "WalletConnect Exit backend has a conflicting route" + ); + } else { + backends.insert(0, managed.clone()); + } + Ok(existing) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use sha2::Digest; + + #[test] + fn walletconnect_local_exit_needs_pinned_config_and_uses_relay_hosts_only() { + let data = tempfile::tempdir().unwrap(); + assert!(local_exit(data.path(), "darwin-arm64").is_none()); + let sdk = data + .path() + .join("capsules/wallet-walletconnect/vendor/reown-appkit.js"); + std::fs::create_dir_all(sdk.parent().unwrap()).unwrap(); + std::fs::write(&sdk, "fixture-sdk").unwrap(); + let config = data + .path() + .join("ElastOS/SystemServices/WalletConnect/config.json"); + std::fs::create_dir_all(config.parent().unwrap()).unwrap(); + std::fs::write( + &config, + serde_json::to_vec(&serde_json::json!({ + "schema":"elastos.walletconnect.connector/v1", "project_id":"fixture-project", + "sdk_package":"@walletconnect/ethereum-provider", "sdk_version":"2.23.9", + "sdk_sha256":hex::encode(sha2::Sha256::digest(b"fixture-sdk")), + })) + .unwrap(), + ) + .unwrap(); + assert!(local_exit(data.path(), "windows-amd64").is_none()); + assert!(local_exit(data.path(), "linux-amd64").is_some()); + let (helper, provider) = local_exit(data.path(), "darwin-arm64").unwrap(); + assert_eq!( + helper["allowed_hosts"], + serde_json::json!(["relay.walletconnect.org", "relay.walletconnect.com"]) + ); + assert_eq!(helper["allowed_ports"], serde_json::json!([443])); + assert_eq!( + provider["backends"][0]["relay_ipc"]["path"], + helper["relay_ipc_path"] + ); + assert_eq!( + provider["backends"][0]["allowed_schemes"], + serde_json::json!(["tls"]) + ); + std::fs::write(sdk, "tampered").unwrap(); + assert!(local_exit(data.path(), "darwin-arm64").is_none()); + } + + #[test] + fn walletconnect_keeps_existing_remote_and_local_exit_configuration() { + let remote = + serde_json::json!({"backends":[], "remote_carrier_exits":[{"id":"owner-remote"}]}); + let wc = serde_json::json!({"backends":[{"id":"walletconnect-local-exit"}]}); + let merged = merge_exit_config(remote.clone(), Some(&wc)).unwrap(); + assert_eq!( + merged["remote_carrier_exits"], + remote["remote_carrier_exits"] + ); + assert_eq!(merged["backends"], wc["backends"]); + let local = serde_json::json!({"backends":[{"id":"owner-local"}]}); + let merged = merge_exit_config(local.clone(), Some(&wc)).unwrap(); + assert_eq!(merged["backends"][1], local["backends"][0]); + assert_eq!(merge_exit_config(remote.clone(), None).unwrap(), remote); + assert!(merge_exit_config(serde_json::json!({"backends":false}), Some(&wc)).is_err()); + } +} diff --git a/scripts/browser-internet-consent.test.mjs b/scripts/browser-internet-consent.test.mjs index d09952eb1..b1a8097ea 100644 --- a/scripts/browser-internet-consent.test.mjs +++ b/scripts/browser-internet-consent.test.mjs @@ -36,7 +36,11 @@ async function screen(page, name) { await page.waitForTimeout(250); await page.screenshot({path:`${process.env.BROWSER_INTERNET_SCREENSHOTS}/${process.env.BROWSER_INTERNET_SCREEN_THEME === "dark" ? "dark-" : ""}${name}.png`}); } -async function fixture() { +async function fixture(service = "browser") { + const walletconnect = service === "walletconnect"; + const prefix = walletconnect ? "walletconnect-internet" : "browser-internet"; + const kind = walletconnect ? "walletconnect_internet" : "browser_internet"; + const internetPath = walletconnect ? "/api/apps/wallet-walletconnect/internet" : "/api/apps/browser/internet"; const state = {consent:"off", expired:false, grantedRequestId:"fixture", requests:0, reads:0, opens:[], actions:[]}; const server=http.createServer(async (req,res) => { const url=new URL(req.url,"http://localhost"); @@ -60,28 +64,28 @@ async function fixture() { res.setHeader("content-type","text/html"); res.end(``);return; } - if (url.pathname === "/api/apps/browser/internet") { + if (url.pathname === internetPath) { state.reads++; if(input?.action === "revoke") {assert.equal(input.step_up_token,"fixture-step-up");state.consent="revoked";} if (input?.action === "end") {json({status:"ended"});return;} if (input?.action === "request") {state.requests++;state.consent="requested";state.expired=false;await state.requestBarrier;} - json({status:state.consent,request_id:state.consent==="granted"?state.grantedRequestId:undefined,request:state.expired?null:{resource:"elastos://browser/internet",grant_id:"fixture-grant",request_id:"fixture",text:consentText,expires_at:Math.floor(Date.now()/1000)+3600}});return; + json({status:state.consent,request_id:state.consent==="granted"?state.grantedRequestId:undefined,request:state.expired?null:{resource:`elastos://${service}/internet`,grant_id:"fixture-grant",request_id:"fixture",text:consentText,expires_at:Math.floor(Date.now()/1000)+3600}});return; } if (url.pathname === "/api/apps/inbox/summary") { const pending=state.consent === "requested"; const body=pending?consentText:state.consent === "granted"?"Browser can open websites. Allowed with your passkey.":state.consent === "refused"?"Browser cannot open websites. Not allowed.":"Browser cannot open websites. Turned off."; json({notifications:{unread_count:pending?1:0,attention_count:pending?1:0,entries:[{ - id:"browser-internet:permission",source_app:"browser",kind:pending?"browser_internet_request":"browser_internet_decision", + id:`${prefix}:permission`,source_app:walletconnect?"wallet-walletconnect":"browser",kind:`${kind}_${pending?"request":"decision"}`, title:pending?"Allow Browser to use the internet?":"Browser internet access",body,severity:pending?"attention":"info",read:!pending,created_at:1794312000, - action_ref:{app:"inbox",action_id:pending?"browser-internet-allow:fixture":state.consent==="granted"?"browser-internet-turn-off:fixture-grant":"browser-internet-request"}, + action_ref:{app:"inbox",action_id:pending?`${prefix}-allow:fixture`:state.consent==="granted"?`${prefix}-turn-off:fixture-grant`:`${prefix}-request`}, }]}});return; } if (url.pathname === "/api/apps/inbox/actions") { state.actions.push(input); - if(input.action_id === "browser-internet-allow:fixture") { + if(input.action_id === `${prefix}-allow:fixture`) { assert.equal(input.step_up_token,"fixture-step-up");state.consent="granted"; - } else if(input.action_id === "browser-internet-deny:fixture") state.consent="refused"; - else if(input.action_id === "browser-internet-turn-off:fixture-grant") {assert.equal(input.step_up_token,"fixture-step-up");state.consent="revoked";} + } else if(input.action_id === `${prefix}-deny:fixture`) state.consent="refused"; + else if(input.action_id === `${prefix}-turn-off:fixture-grant`) {assert.equal(input.step_up_token,"fixture-step-up");state.consent="revoked";} json({ok:true});return; } if (url.pathname === "/api/apps/browser/summary") { @@ -393,3 +397,37 @@ test("internet grant refusal points to the permission request", async () => { assert.doesNotMatch(readFileSync(new URL(`capsules/system/browser/${name}`,root),"utf8"),/browser-internet|browserInternet|browser\.internet|\/api\/apps\/browser\/internet/); } }); + + +test("WalletConnect Inbox keeps requests pending, uses passkey consent and separates completed decisions", async () => { + const f = await fixture("walletconnect"); + const browser = await chromium.launch({headless:true}); + try { + for (const width of [1280,390]) { + f.state.consent="requested"; f.state.actions=[]; + const page=await browser.newPage({viewport:{width,height:844}}); + await page.goto(f.url+"?app=inbox"); + const frame=page.frameLocator("iframe"); + await frame.getByRole("button",{name:"Allow",exact:true}).waitFor(); + assert.equal(await frame.locator("#pending-count").innerText(),"1"); + assert.equal(f.state.actions.length,0,"dynamic requests stay unread until answered"); + await frame.getByRole("button",{name:"Allow",exact:true}).click(); + await frame.getByRole("button",{name:"Turn Off",exact:true}).waitFor(); + assert.equal(await frame.locator("#pending-count").innerText(),"0"); + assert.deepEqual(await page.evaluate(()=>approvals),["walletconnect.internet.grant"]); + await frame.getByRole("button",{name:"Turn Off",exact:true}).click(); + await frame.getByRole("button",{name:"Turn Off",exact:true}).waitFor({state:"hidden"}); + assert.deepEqual(await page.evaluate(()=>approvals),["walletconnect.internet.grant","walletconnect.internet.revoke"]); + assert.equal(f.state.consent,"revoked"); + await page.close(); + } + f.state.consent="requested";f.state.actions=[]; + const page=await browser.newPage();await page.goto(f.url+"?app=inbox"); + const frame=page.frameLocator("iframe"); + await frame.getByRole("button",{name:"Don't Allow",exact:true}).click(); + await frame.getByRole("button",{name:"Allow",exact:true}).waitFor({state:"hidden"}); + assert.equal(f.state.consent,"refused"); + assert.deepEqual(await page.evaluate(()=>approvals),[]); + await page.close(); + } finally {await browser.close();await f.close();} +}); diff --git a/scripts/check-product-data.mjs b/scripts/check-product-data.mjs index b1218305f..0b026adc4 100644 --- a/scripts/check-product-data.mjs +++ b/scripts/check-product-data.mjs @@ -212,7 +212,7 @@ const protectedProviders = ["protected-content-protect-provider", "media-provide const obsolete = ["browser-engine-supervisor", "browser-native-proxy-engine", "browser-stream-bridge", "chat", "agent", "esp-shell", "capsule-inspector", "gba-engine-provider", "ai-provider", "llama-provider"]; const archiveAssets = ["home", "system", "services", "people", "documents", "library", "marketplace", "archive-manager", "inbox"]; // Hidden in 0.8.0: fresh Homes do not install them; they stay published for `setup --with` and updates. -const hiddenFromHome = ["services", "wallet-walletconnect", "content-block-graph-provider", "elacity-player", "protected-content-protect-provider", "protected-content-decrypt-provider", "media-provider", "media-tools"]; +const hiddenFromHome = ["services", "content-block-graph-provider", "elacity-player", "protected-content-protect-provider", "protected-content-decrypt-provider", "media-provider", "media-tools"]; export function parsePublishData(shellSource, rustSource) { const shell = (name) => { diff --git a/scripts/check-product-data.test.mjs b/scripts/check-product-data.test.mjs index 260647b6f..9605d3ef9 100644 --- a/scripts/check-product-data.test.mjs +++ b/scripts/check-product-data.test.mjs @@ -202,7 +202,7 @@ for (const [name, mutate, message] of [ ["unknown profile component", (value) => value.profiles.home.components.push("missing-provider"), /unknown component/], ["missing Wallet dependency", (value) => value.profiles.home.components = value.profiles.home.components.filter((entry) => entry !== "wallet-provider"), /Wallet\/Browser dependency/], ["Elacity Player without its protected providers", (value) => value.profiles.home.components.push("elacity-player"), /must occur once/], - ...["services", "wallet-walletconnect", "content-block-graph-provider", "media-tools"].map((name) => + ...["services", "content-block-graph-provider", "media-tools"].map((name) => [`hidden ${name} in default Home`, (value) => value.profiles.home.components.push(name), /hidden in 0\.8\.0/]), ["hidden component no longer published", (value) => delete value.external["content-block-graph-provider"], /stays published for --with/], ["default public edge service", (value) => value.profiles.home.components.push("tunnel-provider"), /developer --with component/], diff --git a/scripts/configure-walletconnect-connector.mjs b/scripts/configure-walletconnect-connector.mjs index ba2169695..b8339be07 100755 --- a/scripts/configure-walletconnect-connector.mjs +++ b/scripts/configure-walletconnect-connector.mjs @@ -5,7 +5,7 @@ import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; import { basename, dirname, resolve } from "node:path"; const CONFIG_SCHEMA = "elastos.walletconnect.connector/v1"; -const SDK_PACKAGE = "@reown/appkit"; +const SDK_PACKAGE = "@walletconnect/ethereum-provider"; const CONFIG_PATH = "ElastOS/SystemServices/WalletConnect/config.json"; const SDK_PATH = "capsules/wallet-walletconnect/vendor/reown-appkit.js"; diff --git a/scripts/home-shell-bridge-smoke.mjs b/scripts/home-shell-bridge-smoke.mjs index 4d51c643a..2de31ebc0 100644 --- a/scripts/home-shell-bridge-smoke.mjs +++ b/scripts/home-shell-bridge-smoke.mjs @@ -1610,7 +1610,7 @@ sendChildMessage("http://evil.invalid", walletFrameWindow, { }); sendChildMessage("null", walletFrameWindow, { type: "home:open-target", - target: "wallet-walletconnect", + target: "wallet-unknown", homeToken: "wallet-token", }); sendChildMessage("null", walletFrameWindow, { diff --git a/scripts/home-shell-regression-smoke.mjs b/scripts/home-shell-regression-smoke.mjs index 60ebfec0b..f1965155d 100644 --- a/scripts/home-shell-regression-smoke.mjs +++ b/scripts/home-shell-regression-smoke.mjs @@ -1897,10 +1897,10 @@ const continuityWalletEntry = await shellWindows.attachAuthorizedTarget({ launch_status: "launched", }); const continuityWallet = windowModel(continuityWalletEntry); -for (const target of ["wallet-metamask", "wallet-unisat"]) { +for (const target of ["wallet-metamask", "wallet-unisat", "wallet-walletconnect"]) { const connectorEntry = await shellWindows.attachAuthorizedTarget({ target, - title: target === "wallet-metamask" ? "MetaMask" : "UniSat", + title: ({ "wallet-metamask": "MetaMask", "wallet-unisat": "UniSat", "wallet-walletconnect": "WalletConnect" })[target], route: `/apps/${target}/?home_origin=http%3A%2F%2Flocalhost%3A61180` + `#home_token=deterministic-${target}-token`, diff --git a/scripts/home-wallet-connector-launch-headless-smoke.mjs b/scripts/home-wallet-connector-launch-headless-smoke.mjs index 660319709..36c43f124 100644 --- a/scripts/home-wallet-connector-launch-headless-smoke.mjs +++ b/scripts/home-wallet-connector-launch-headless-smoke.mjs @@ -14,10 +14,12 @@ const walletToken = "fixture-wallet-token"; const connectorTokens = Object.freeze({ "wallet-metamask": "fixture-metamask-token", "wallet-unisat": "fixture-unisat-token", + "wallet-walletconnect": "fixture-walletconnect-token", }); const connectorTitles = Object.freeze({ "wallet-metamask": "MetaMask", "wallet-unisat": "UniSat", + "wallet-walletconnect": "WalletConnect", }); const state = { launches: { @@ -25,6 +27,7 @@ const state = { wallet: 0, "wallet-metamask": 0, "wallet-unisat": 0, + "wallet-walletconnect": 0, }, connectorEffects: 0, homeStateWrites: [], @@ -77,6 +80,7 @@ function staticPath(pathname) { ["/apps/wallet/", join(repoRoot, "capsules/wallet/browser")], ["/apps/wallet-metamask/", join(repoRoot, "capsules/wallet-metamask/browser")], ["/apps/wallet-unisat/", join(repoRoot, "capsules/wallet-unisat/browser")], + ["/apps/wallet-walletconnect/", join(repoRoot, "capsules/wallet-walletconnect/browser")], ]; for (const [prefix, root] of roots) { if (!pathname.startsWith(prefix)) { @@ -253,7 +257,7 @@ async function handleApi(req, res, url) { json(res, 200, { wallet_accounts: { accounts: [], default_accounts: [] }, wallet_approvals: { approval_requests: [] }, - approval_methods: {}, + approval_methods: { walletconnect: { available: true } }, }); return true; } @@ -500,6 +504,7 @@ try { const connectorLabels = Object.freeze({ "wallet-metamask": "Connect wallet", "wallet-unisat": "Connect UniSat", + "wallet-walletconnect": "Connect wallet", }); const walletWindowBeforeConnectors = await homeWindowSnapshot( homeGui, @@ -640,13 +645,14 @@ try { assert(state.launches.wallet === 1, "Home launched Wallet more than once", state); assert( state.launches["wallet-metamask"] === 1 && - state.launches["wallet-unisat"] === 1, + state.launches["wallet-unisat"] === 1 && state.launches["wallet-walletconnect"] === 1, "one Wallet click did not produce exactly one Runtime connector launch", state, ); assert( await homeGui.locator('.window[data-target="wallet-metamask"]').count() === 0 && - await homeGui.locator('.window[data-target="wallet-unisat"]').count() === 0, + await homeGui.locator('.window[data-target="wallet-unisat"]').count() === 0 && + await homeGui.locator('.window[data-target="wallet-walletconnect"]').count() === 0, "Home GUI did not close connector windows independently", ); @@ -654,11 +660,11 @@ try { await postGuiCommandFromHost(page, { schema: "elastos.home.authorized-target-attachment/v1", receipt_id: "forged-target", - target: "wallet-walletconnect", - title: "WalletConnect", + target: "wallet-unknown", + title: "Unknown connector", attach_kind: "iframe", route: - `/apps/wallet-walletconnect/?home_origin=${encodeURIComponent(origin)}` + + `/apps/wallet-unknown/?home_origin=${encodeURIComponent(origin)}` + "#home_token=forged", }); await postGuiCommandFromHost(page, { @@ -694,7 +700,7 @@ try { ); assert( state.launches["wallet-metamask"] === 1 && - state.launches["wallet-unisat"] === 1, + state.launches["wallet-unisat"] === 1 && state.launches["wallet-walletconnect"] === 1, "descriptor rejection invoked the generic Runtime launch path", state, ); @@ -732,6 +738,8 @@ try { assert( !persistedState.includes("wallet-metamask") && !persistedState.includes("wallet-unisat") && + !persistedState.includes("wallet-walletconnect") && + !persistedState.includes("fixture-walletconnect-token") && !persistedState.includes("home_token") && !persistedState.includes("fixture-metamask-token") && !persistedState.includes("fixture-unisat-token") && @@ -748,6 +756,7 @@ try { `wallet_launches=${state.launches.wallet} ` + `metamask_launches=${state.launches["wallet-metamask"]} ` + `unisat_launches=${state.launches["wallet-unisat"]} ` + + `walletconnect_launches=${state.launches["wallet-walletconnect"]} ` + `connector_effects=${state.connectorEffects}`, ); } finally { diff --git a/scripts/home-walletconnect-launch.test.mjs b/scripts/home-walletconnect-launch.test.mjs new file mode 100644 index 000000000..057a2e433 --- /dev/null +++ b/scripts/home-walletconnect-launch.test.mjs @@ -0,0 +1,5 @@ +import test from "node:test"; + +test("Wallet opens each connector in a separate bounded Home window and closes it", { timeout: 45000 }, async () => { + await import("./home-wallet-connector-launch-headless-smoke.mjs"); +}); diff --git a/scripts/lib/walletconnect-adapter-loader.mjs b/scripts/lib/walletconnect-adapter-loader.mjs new file mode 100644 index 000000000..0d5d61b3a --- /dev/null +++ b/scripts/lib/walletconnect-adapter-loader.mjs @@ -0,0 +1,11 @@ +// Load the real adapter with deterministic SDK fixtures for lifecycle tests. +// The browser suite separately exercises the locked, bundled SDK itself. +export async function resolve(specifier, context, nextResolve) { + if (context.parentURL?.includes("/scripts/walletconnect/adapter.mjs")) { + const source = specifier === "@walletconnect/ethereum-provider" + ? "export const EthereumProvider = { init: options => globalThis.walletConnectSdkFixture(options) };" + : specifier === "qrcode" ? "export default { toCanvas: async () => {} };" : null; + if (source) return { url: `data:text/javascript,${encodeURIComponent(source)}`, shortCircuit: true }; + } + return nextResolve(specifier, context); +} diff --git a/scripts/lib/walletconnect-sdk-fixture.mjs b/scripts/lib/walletconnect-sdk-fixture.mjs new file mode 100644 index 000000000..ee0443fc3 --- /dev/null +++ b/scripts/lib/walletconnect-sdk-fixture.mjs @@ -0,0 +1,5 @@ +export async function connectWalletConnectEvm(options) { + if (new URL(options.runtimeUrl).origin !== globalThis.location.origin) throw new Error("SDK RPC URLs require the Home origin"); + globalThis.__wcFixtureOptions = options; + return globalThis.__wcFixtureProvider; +} diff --git a/scripts/prepare-release-platform-test.py b/scripts/prepare-release-platform-test.py index c90e48c07..7bca78235 100644 --- a/scripts/prepare-release-platform-test.py +++ b/scripts/prepare-release-platform-test.py @@ -154,7 +154,7 @@ def setUp(self): "publish-release.sh", "prepare-release-platform.sh", "release-platform-input.py", "components-release-integrity-check.py", "release-platforms.json", "release-signer.py", "check-versioning.sh", "build-media-tools.sh", "release-upstream-assets.py", "release-upstream-input.py", "browser-host-release.py", - "verify-linux-engine.py", + "verify-linux-engine.py", "stage-walletconnect-release.mjs", "browser-vm-image-inputs.py", "browser-image-cid-input.py", ): (scripts / name).write_bytes((SOURCE / "scripts" / name).read_bytes()) @@ -358,6 +358,16 @@ def setUp(self): "MOCK_AUDIT_LOG": str(self.root / "audit.log"), "ELASTOS_LLAMA_ARM64_BUNDLE": str(self.arm64_engine), "ELASTOS_LLAMA_AMD64_BUNDLE": str(self.amd64_engine)} + self.env.pop("ELASTOS_WALLETCONNECT_PROJECT_ID", None) + self.env.pop("ELASTOS_WALLETCONNECT_PROJECT_FILE", None) + wc_vendor = self.repo / "capsules/wallet-walletconnect/vendor" + wc_vendor.mkdir(parents=True, exist_ok=True) + wc_sdk = b"export const fixture = true;" + (wc_vendor / "reown-appkit.js").write_bytes(wc_sdk) + (wc_vendor / "adapter.json").write_text(json.dumps({ + "sdk_package": "@walletconnect/ethereum-provider", "sdk_version": "2.23.9", + "sdk_sha256": hashlib.sha256(wc_sdk).hexdigest(), + })) self.commit("fixture", init=True) (self.repo / "capsules/home/browser/secret.txt").write_text("ignored private input") @@ -736,6 +746,17 @@ def test_success_uses_real_packaging_and_receipt(self): self.assertIn("Output already exists", refused.stderr) self.assertEqual((output / "platform-input.json").read_bytes(), before) + def test_walletconnect_operator_config_and_bundle_enter_the_verified_release(self): + output, result = self.prepare(env={**self.env, "ELASTOS_WALLETCONNECT_PROJECT_ID": "fixture-project-id"}) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + with tarfile.open(output / "artifacts/wallet-walletconnect.tar.gz") as archive: + sdk = archive.extractfile("wallet-walletconnect/vendor/reown-appkit.js").read() + config = json.loads(archive.extractfile("wallet-walletconnect/vendor/connector.json").read()) + self.assertEqual(config["project_id"], "fixture-project-id") + self.assertEqual(config["sdk_sha256"], hashlib.sha256(sdk).hexdigest()) + result = self.command("python3", "scripts/release-platform-input.py", "verify", str(output)) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_packaging_refuses_a_projection_with_microvm_type(self): path = self.repo / "capsules/home-cli/capsule.json" manifest = json.loads(path.read_text()) diff --git a/scripts/publish-release.sh b/scripts/publish-release.sh index 1f165622d..68d7af957 100755 --- a/scripts/publish-release.sh +++ b/scripts/publish-release.sh @@ -26,7 +26,7 @@ NC='\033[0m' # Default publish scope: runtime core + first-party Home app surface. # Wallet/Browser surfaces require chain-provider and wallet-provider authority. # Developer-only capsules such as GBA, and the items hidden in 0.8.0 -# (services, wallet-walletconnect, elacity-player, content-block-graph-provider +# (services, elacity-player, content-block-graph-provider # and the protected-content providers), are published by the release asset and # support-binary loops below and installed with `elastos setup --with `. # availability-provider, drm-provider, rights-provider, key-provider, @@ -52,6 +52,7 @@ DEFAULT_CAPSULES=( people wallet-metamask wallet-unisat + wallet-walletconnect wallet browser documents @@ -83,6 +84,7 @@ REQUIRED_SUPPORTED_CAPSULES=( people wallet-metamask wallet-unisat + wallet-walletconnect wallet browser documents @@ -496,6 +498,9 @@ build_packaged_capsule_archive() { mkdir -p "${stage_root}/${capsule_name}/bin" || return install -m 755 "$native_renderer" "${stage_root}/${capsule_name}/bin/home-cli" || return fi + if [[ "$capsule_name" == wallet-walletconnect && -n "${ELASTOS_WALLETCONNECT_PROJECT_FILE:-}${ELASTOS_WALLETCONNECT_PROJECT_ID:-}" ]]; then + node scripts/stage-walletconnect-release.mjs "${stage_root}/${capsule_name}" || return + fi create_capsule_tar "$archive" "$stage_root" "$capsule_name" || return echo "$archive" } @@ -706,6 +711,9 @@ stage_wasm_capsule() { mkdir -p "${dest}/browser" || return copy_clean_capsule_tree "${capsule_dir}/browser" "${dest}/browser" || return fi + if [[ "$capsule_name" == wallet-walletconnect && -d "${capsule_dir}/vendor" ]]; then + copy_clean_capsule_tree "${capsule_dir}/vendor" "${dest}/vendor" || return + fi if [[ "$runtime_abi" == "elastos.runtime-projection/v1" ]]; then copy_release_source_file "$built_wasm" "${dest}/${entrypoint}" || return else @@ -970,7 +978,7 @@ build_platform_independent_direct_assets() { chat-room \ assistant \ elacity-player; do - if [[ -n "${ARTIFACTS_DIR:-}" && -f "${ARTIFACTS_DIR}/${capsule}.capsule.tar.gz" ]]; then + if [[ "$capsule" != wallet-walletconnect && -n "${ARTIFACTS_DIR:-}" && -f "${ARTIFACTS_DIR}/${capsule}.capsule.tar.gz" ]]; then archive="${ARTIFACTS_DIR}/${capsule}.capsule.tar.gz" else archive=$(build_packaged_capsule_archive "$platform" "$capsule") || return diff --git a/scripts/setup-source-home.sh b/scripts/setup-source-home.sh index 6600093ba..10f9487ec 100755 --- a/scripts/setup-source-home.sh +++ b/scripts/setup-source-home.sh @@ -1689,6 +1689,9 @@ stamp_source_home_components_manifest echo "[setup-source-home] install app capsules and manifest entrypoints" install_app_capsules +if [[ -n "${ELASTOS_WALLETCONNECT_PROJECT_FILE:-}${ELASTOS_WALLETCONNECT_PROJECT_ID:-}" ]]; then + node "${ROOT}/scripts/stage-walletconnect-release.mjs" "${DATA_DIR}/capsules/wallet-walletconnect" +fi for retired_provider in "${RETIRED_SOURCE_HOME_PROVIDER_BINARIES[@]}"; do rm -f "${DATA_DIR}/bin/${retired_provider}" done diff --git a/scripts/stage-walletconnect-release.mjs b/scripts/stage-walletconnect-release.mjs new file mode 100644 index 000000000..fd3687d94 --- /dev/null +++ b/scripts/stage-walletconnect-release.mjs @@ -0,0 +1,23 @@ +// Run against the private release stage or source-home install, before hashing +// its capsule. An operator supplies the project ID through a provisioned file. +import { readFile, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { resolve } from "node:path"; + +const capsule = resolve(process.argv[2]); +const operator = process.env.ELASTOS_WALLETCONNECT_PROJECT_FILE; +if (operator || process.env.ELASTOS_WALLETCONNECT_PROJECT_ID) { + const projectId = (operator ? await readFile(operator, "utf8") : process.env.ELASTOS_WALLETCONNECT_PROJECT_ID).trim(); + if (!/^[A-Za-z0-9_-]{8,128}$/.test(projectId)) throw new Error("Invalid WalletConnect operator project file"); + const manifest = JSON.parse(await readFile(resolve(capsule, "vendor/adapter.json"), "utf8")); + const sdk = await readFile(resolve(capsule, "vendor/reown-appkit.js")); + if (manifest.sdk_package !== "@walletconnect/ethereum-provider" + || manifest.sdk_version !== "2.23.9" + || manifest.sdk_sha256 !== createHash("sha256").update(sdk).digest("hex")) { + throw new Error("WalletConnect reviewed adapter hash mismatch"); + } + await writeFile(resolve(capsule, "vendor/connector.json"), JSON.stringify({ + schema: "elastos.walletconnect.connector/v1", project_id: projectId, + sdk_package: manifest.sdk_package, sdk_version: manifest.sdk_version, sdk_sha256: manifest.sdk_sha256, + }, null, 2) + "\n", { mode: 0o600 }); +} diff --git a/scripts/vendor-walletconnect-adapter.sh b/scripts/vendor-walletconnect-adapter.sh index 6b2fdcce4..4d1c53607 100755 --- a/scripts/vendor-walletconnect-adapter.sh +++ b/scripts/vendor-walletconnect-adapter.sh @@ -1,247 +1,36 @@ #!/usr/bin/env bash +# Build only the reviewed, locked graph. Release packaging ships this output. set -euo pipefail - ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -APPKIT_VERSION="${APPKIT_VERSION:-1.8.19}" -WAGMI_VERSION="${WAGMI_VERSION:-3.6.10}" -VIEM_VERSION="${VIEM_VERSION:-2.48.11}" -ESBUILD_VERSION="${ESBUILD_VERSION:-0.28.0}" -WALLETCONNECT_ETHEREUM_PROVIDER_VERSION="${WALLETCONNECT_ETHEREUM_PROVIDER_VERSION:-2.23.9}" -COINBASE_WALLET_SDK_VERSION="${COINBASE_WALLET_SDK_VERSION:-4.3.7}" -METAMASK_CONNECT_EVM_VERSION="${METAMASK_CONNECT_EVM_VERSION:-1.1.0}" -PORTO_VERSION="${PORTO_VERSION:-0.2.37}" -OUT_FILE="$ROOT_DIR/artifacts/walletconnect/reown-appkit.js" - -usage() { - cat <<'EOF' -Usage: - bash scripts/vendor-walletconnect-adapter.sh [--out-file ] - -Environment overrides: - APPKIT_VERSION exact @reown/appkit and @reown/appkit-adapter-wagmi version - WAGMI_VERSION exact wagmi version - VIEM_VERSION exact viem version - ESBUILD_VERSION exact esbuild version - WALLETCONNECT_ETHEREUM_PROVIDER_VERSION exact WalletConnect EIP-1193 provider version - COINBASE_WALLET_SDK_VERSION exact Coinbase connector dependency version - METAMASK_CONNECT_EVM_VERSION exact MetaMask connector dependency version - PORTO_VERSION exact Porto connector dependency version - -The output is a local ESM adapter bundle exporting connectWalletConnectEvm(). -Review it, then pin it with: - - node scripts/configure-walletconnect-connector.mjs \ - --data-dir \ - --project-id \ - --sdk-file \ - --sdk-version -EOF -} - -while [[ $# -gt 0 ]]; do - case "$1" in - --out-file) - OUT_FILE="${2:?missing --out-file value}" - shift 2 - ;; - --help|-h) - usage - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - usage >&2 - exit 1 - ;; - esac -done - -for version in \ - "$APPKIT_VERSION" \ - "$WAGMI_VERSION" \ - "$VIEM_VERSION" \ - "$ESBUILD_VERSION" \ - "$WALLETCONNECT_ETHEREUM_PROVIDER_VERSION" \ - "$COINBASE_WALLET_SDK_VERSION" \ - "$METAMASK_CONNECT_EVM_VERSION" \ - "$PORTO_VERSION"; do - if [[ -z "$version" || "$version" == ^* || "$version" == ~* || "$version" == "*" || "$version" =~ [[:space:]] ]]; then - echo "All package versions must be exact pins. Invalid: $version" >&2 - exit 1 - fi -done - -tmpdir="$(mktemp -d /tmp/elastos-walletconnect-adapter-XXXXXX)" -trap 'rm -rf "$tmpdir"' EXIT - -cat >"$tmpdir/package.json" <"$tmpdir/adapter.js" <<'JS' -import { createAppKit } from "@reown/appkit"; -import { base, defineChain, mainnet } from "@reown/appkit/networks"; -import { WagmiAdapter } from "@reown/appkit-adapter-wagmi"; - -const elastosEsc = defineChain({ - id: 20, - caipNetworkId: "eip155:20", - chainNamespace: "eip155", - name: "Elastos Smart Chain", - nativeCurrency: { - decimals: 18, - name: "ELA", - symbol: "ELA", - }, - rpcUrls: { - default: { http: ["https://api.elastos.io/esc"] }, - }, - blockExplorers: { - default: { name: "Elastos Explorer", url: "https://esc.elastos.io" }, - }, -}); - -const supportedNetworks = new Map([ - [1, mainnet], - [20, elastosEsc], - [8453, base], -]); - -let modal = null; -let adapter = null; -let modalKey = ""; - -export async function connectWalletConnectEvm(options = {}) { - const projectId = requiredText(options.projectId, "projectId"); - const chains = Array.isArray(options.chains) && options.chains.length > 0 - ? options.chains - : [1, 20, 8453]; - const networks = chains.map((chainId) => supportedNetworks.get(Number(chainId))).filter(Boolean); - if (networks.length === 0) { - throw new Error("No supported EVM networks configured for WalletConnect."); - } - - const key = `${projectId}:${networks.map((network) => network.id).join(",")}`; - if (!modal || modalKey !== key) { - adapter = new WagmiAdapter({ projectId, networks }); - modal = createAppKit({ - adapters: [adapter], - networks, - projectId, - metadata: options.metadata || {}, - enableReconnect: false, - enableWalletGuide: false, - features: { - analytics: false, - email: false, - socials: [], - swaps: false, - onramp: false, - }, - }); - modalKey = key; - } - - const existingProvider = eip1193Provider(modal.getWalletProvider?.()); - if (existingProvider && modal.getIsConnected?.()) { - return existingProvider; - } - - const providerPromise = waitForProvider(modal); - await modal.open({ view: "Connect", namespace: "eip155" }); - return providerPromise; -} - -function waitForProvider(currentModal) { - return new Promise((resolve, reject) => { - let done = false; - let unsubscribe = null; - const timeout = setTimeout(() => { - finish(null, new Error("WalletConnect connection was not completed.")); - }, 300000); - - function finish(provider, error) { - if (done) { - return; - } - done = true; - clearTimeout(timeout); - if (typeof unsubscribe === "function") { - unsubscribe(); - } - if (error) { - reject(error); - } else { - resolve(provider); - } - } - - unsubscribe = currentModal.subscribeProvider((state) => { - if (state?.error) { - finish(null, state.error); - return; - } - const provider = eip1193Provider(state?.provider); - if (provider && state?.isConnected) { - finish(provider, null); - } - }); - - const provider = eip1193Provider(currentModal.getWalletProvider?.()); - if (provider && currentModal.getIsConnected?.()) { - finish(provider, null); - } - }); -} - -function eip1193Provider(value) { - return value && typeof value.request === "function" ? value : null; -} - -function requiredText(value, label) { - if (typeof value !== "string" || value.trim().length === 0) { - throw new Error(`Missing ${label}.`); - } - return value.trim(); +OUT_FILE="$ROOT_DIR/capsules/wallet-walletconnect/vendor/reown-appkit.js" +if [[ "${1:-}" == --out-file ]]; then OUT_FILE="${2:?missing output path}"; shift 2; fi +[[ $# == 0 ]] || { echo 'Usage: scripts/vendor-walletconnect-adapter.sh [--out-file PATH]' >&2; exit 2; } +npm ci --prefix "$ROOT_DIR/scripts/walletconnect" --ignore-scripts --no-audit --no-fund +mkdir -p "$(dirname "$OUT_FILE")" +"$ROOT_DIR/scripts/walletconnect/node_modules/.bin/esbuild" "$ROOT_DIR/scripts/walletconnect/adapter.mjs" \ + --bundle --format=esm --platform=browser --target=es2022 --minify \ + --inject:"$ROOT_DIR/scripts/walletconnect/runtime-websocket.mjs" --outfile="$OUT_FILE" +node --input-type=module - "$ROOT_DIR" "$OUT_FILE" <<'JS' +import { createHash } from 'node:crypto'; +import { readFileSync, writeFileSync, copyFileSync, readdirSync, lstatSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +const [root, output] = process.argv.slice(2); +copyFileSync(join(root, 'scripts/walletconnect/package-lock.json'), join(dirname(output), 'package-lock.json')); +const sha = path => createHash('sha256').update(readFileSync(path)).digest('hex'); +writeFileSync(join(dirname(output), 'adapter.json'), JSON.stringify({ + sdk_package: '@walletconnect/ethereum-provider', sdk_version: '2.23.9', + sdk_sha256: sha(output), dependency_lock_sha256: sha(join(root, 'scripts/walletconnect/package-lock.json')), + source_sha256: Object.fromEntries(['adapter.mjs', 'runtime-storage.mjs', 'runtime-websocket.mjs', '../vendor-walletconnect-adapter.sh'].map(file => + [file, sha(join(root, 'scripts/walletconnect', file))])), +}, null, 2) + '\n'); +const lock = JSON.parse(readFileSync(join(root, 'scripts/walletconnect/package-lock.json'))); +const notices = []; +for (const name of Object.keys(lock.packages).filter(Boolean).sort()) { + const directory = join(root, 'scripts/walletconnect', name); + let files; + try { files = readdirSync(directory).filter(file => /^(license|licence|copying|notice)(\.|$)/i.test(file)); } + catch { continue; } // Optional dependencies for another host are locked, but absent. + for (const file of files.filter(file => lstatSync(join(directory, file)).isFile())) notices.push(`${name}/${file}\n${readFileSync(join(directory, file), 'utf8')}`); } +writeFileSync(join(dirname(output), 'LICENSES.txt'), notices.join('\n\n')); JS - -( - cd "$tmpdir" - npm install --ignore-scripts --no-audit --no-fund >/dev/null - npx esbuild adapter.js \ - --bundle \ - --format=esm \ - --platform=browser \ - --target=es2022 \ - --outfile="$OUT_FILE" >/dev/null -) - -sha="$(sha256sum "$OUT_FILE" | awk '{print $1}')" -cat < setImmediate(resolveTick)); const requestRoot = document.querySelector("#wallet-requests"); @@ -451,97 +450,9 @@ async function runMetaMaskHostBridgeSmoke() { }; } -async function runWalletConnectSmoke() { - const connectorId = "wallet-walletconnect"; - const document = new FakeDocument(); - const provider = createFakeProvider(); - const fetchCalls = []; - const completionBodies = []; - const sdkModule = `data:text/javascript,${encodeURIComponent(` - export async function connectWalletConnectEvm() { - return globalThis.__walletConnectProvider; - } - `)}`; - const top = { postMessage() {} }; - globalThis.document = document; - globalThis.__walletConnectProvider = provider; - globalThis.window = { - location: { - search: `?home_origin=${encodeURIComponent(HOME_ORIGIN)}`, - hash: `#home_token=${CONNECTOR_TOKEN}`, - origin: "null", - }, - top, - parent: top, - addEventListener() {}, - dispatchEvent() {}, - }; - globalThis.window.window = globalThis.window; - globalThis.fetch = async (url, init = {}) => { - fetchCalls.push({ url: String(url), init }); - if (init.headers?.["x-elastos-home-token"] !== CONNECTOR_TOKEN) { - throw new Error(`WalletConnect lost its fragment launch token for ${url}`); - } - if (String(url).endsWith("/wallet/config")) { - return response({ - evm_chains: handoffEnvelope(connectorId).evm_chains, - walletconnect: { - sdk_asset_path: sdkModule, - project_id: "runtime-test-project", - }, - }); - } - if (String(url).endsWith("/wallet/accounts")) { - return response({ - accounts: [{ - account_id: `wallet:eip155:20:${ADDRESS}`, - chain_namespace: "eip155:20", - address: ADDRESS, - proof_type: "siwe", - connector_id: connectorId, - }], - }); - } - if (String(url).endsWith("/wallet/approvals")) { - return response({ approval_requests: [approvalRequest(connectorId)] }); - } - if (String(url).endsWith("/approve")) { - return response({ handoff: handoffEnvelope(connectorId).handoff }); - } - if (String(url).endsWith("/complete")) { - completionBodies.push(JSON.parse(init.body || "{}")); - return response({ ok: true }); - } - throw new Error(`unexpected Runtime endpoint: ${url}`); - }; - await importConnectorFixture( - "capsules/wallet-walletconnect/browser/wallet-walletconnect.js", - ); - await new Promise((resolveTick) => setImmediate(resolveTick)); - const requestRoot = document.querySelector("#wallet-requests"); - const review = findReviewButton(requestRoot); - await requestRoot.listeners.get("click")({ target: review }); - const methods = provider.calls.map((call) => call.method); - if ( - !methods.includes("eth_sendTransaction") - || completionBodies.length !== 1 - || completionBodies[0].transaction_hash !== TX_HASH - || globalThis.window.location.search.includes("home_token") - ) { - throw new Error("WalletConnect configured path or fragment authority regressed"); - } - return { - connectorId, - providerMethods: methods, - runtimeEndpoints: fetchCalls.map((call) => call.url), - authorityTransport: "fragment", - effectOwner: "walletconnect-configured-path", - }; -} - const results = [ - await runMetaMaskHostBridgeSmoke(), - await runWalletConnectSmoke(), + await runHostedConnectorSmoke(), + await runHostedConnectorSmoke("wallet-walletconnect"), ]; console.log(JSON.stringify({ ok: true, results }, null, 2)); diff --git a/scripts/walletconnect-adapter-lifecycle.test.mjs b/scripts/walletconnect-adapter-lifecycle.test.mjs new file mode 100644 index 000000000..cbd5c696c --- /dev/null +++ b/scripts/walletconnect-adapter-lifecycle.test.mjs @@ -0,0 +1,60 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { register } from "node:module"; +register(new URL("./lib/walletconnect-adapter-loader.mjs", import.meta.url)); + +test("the real adapter resumes restored sessions and refreshes authority before reconnect or disconnect", async () => { + let initialized = 0, opened = 0, closed = 0, disconnected = 0, paired = 0; + const providers = []; + let sdkOptions; + globalThis.walletConnectSdkFixture = async options => { + initialized++; sdkOptions = options; + const provider = { + connected: true, session: { topic: "restored-session", expiry: Math.floor(Date.now() / 1000) + 600 }, + signer: { client: { core: { relayer: { + transportOpen: async () => { opened++; }, + transportClose: async () => { closed++; }, + } } } }, + connect: async () => { + assert.ok(provider.session.expiry < Date.now() / 1000, "an unexpired restored session needs no new pairing"); + paired++; + provider.session.expiry = Math.floor(Date.now() / 1000) + 600; + }, + on() {}, removeListener() {}, + disconnect: async () => { disconnected++; }, + }; + providers.push(provider);return provider; + }; + const { connectWalletConnectEvm, disconnectWalletConnectEvm } = await import("./walletconnect/adapter.mjs"); + const calls = []; + const options = { + contextKey: "principal-one", chains: [1], projectId: "fixture-project", + relayUrl: "ws://home.test/relay", runtimeUrl: "http://home.test/api/apps/wallet-walletconnect", + api: async (...args) => { calls.push(["old", ...args]);return {}; }, + }; + assert.equal(await connectWalletConnectEvm(options), providers[0]); + assert.equal(initialized, 1);assert.equal(opened, 1); + // A fresh launch for the same principal must update the API used by persisted Core. + const api = async (...args) => { calls.push(["fresh", ...args]);return {}; }; + assert.equal(await connectWalletConnectEvm({ ...options, api }), providers[0]); + await sdkOptions.storage.setItem("session", { topic: "same-pairing" }); + assert.equal(calls.at(-1)[0], "fresh"); + assert.equal(initialized, 1);assert.equal(opened, 2); + await disconnectWalletConnectEvm({ api }); + assert.equal(disconnected, 1);assert.equal(closed, 1); + assert.equal(calls.some(call => call[1].includes("account")), false, "disconnect leaves wallet-provider accounts intact"); + assert.equal(await connectWalletConnectEvm({ ...options, contextKey: "principal-two", api }), providers[1]); + assert.equal(initialized, 2); + assert.equal(paired, 0); + providers[1].session.expiry = 1; + let removed = 0; + globalThis.document = { + createElement: () => ({ append() {}, addEventListener() {}, remove() { removed++; } }), + body: { append() {} }, + }; + await connectWalletConnectEvm({ ...options, contextKey: "principal-two", api }); + assert.equal(paired, 1, "an expired session requires a fresh phone pairing even when the relay is connected"); + assert.equal(removed, 1); + delete globalThis.document; + delete globalThis.walletConnectSdkFixture; +}); diff --git a/scripts/walletconnect-connector-config-smoke.sh b/scripts/walletconnect-connector-config-smoke.sh index b681ce04c..c43986086 100755 --- a/scripts/walletconnect-connector-config-smoke.sh +++ b/scripts/walletconnect-connector-config-smoke.sh @@ -42,7 +42,7 @@ if (config.schema !== "elastos.walletconnect.connector/v1") { if (config.project_id !== "test_walletconnect_project") { throw new Error("wrong project id"); } -if (config.sdk_package !== "@reown/appkit") { +if (config.sdk_package !== "@walletconnect/ethereum-provider") { throw new Error("wrong sdk package"); } if (config.sdk_version !== "0.0.0-test") { diff --git a/scripts/walletconnect-home-host.test.mjs b/scripts/walletconnect-home-host.test.mjs new file mode 100644 index 000000000..c0b50e103 --- /dev/null +++ b/scripts/walletconnect-home-host.test.mjs @@ -0,0 +1,116 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { pathToFileURL } from "node:url"; +import { resolve } from "node:path"; + +const address = `0x${"12".repeat(20)}`; +const payloadHash = `0x${"34".repeat(32)}`; +const signature = `0x${"ab".repeat(65)}`; +const linkMessage = "Runtime ownership proof · fixture"; +const linkMessages = { "link-uppercase-hex": "0X4142", "link-odd-hex": "0x123" }; +const transactionHash = `0x${"56".repeat(32)}`; +const origin = "http://localhost:61180"; +const connector = "wallet-walletconnect"; + +async function fixture(scenario) { + globalThis.document = { querySelector() { return null; } }; + globalThis.location = { origin }; + globalThis.window = { addEventListener() {}, dispatchEvent() {} }; + const { setHomeAuthorityToken } = await import("../capsules/home/browser/shell-core.js?v=home-wallpaper-20261030b"); + setHomeAuthorityToken("home-authority-fixture"); + const host = await import(`../capsules/home/browser/home-wallet-connector-host.js?fixture=${scenario}`); + const calls = []; + globalThis.__wcFixtureProvider = { + connected: true, on() {}, + async request(input, expiry) { + calls.push({ ...input, expiry }); + if (input.method === "eth_requestAccounts") return [address]; + if (input.method === "personal_sign") return signature; + if (input.method === "eth_accounts") return [scenario === "wrong-account" ? `0x${"ab".repeat(20)}` : address]; + if (input.method === "eth_chainId") return scenario === "wrong-chain" ? "0x1" : "0x14"; + if (input.method === "eth_sendTransaction") return transactionHash; + throw new Error(`Unexpected wallet call: ${input.method}`); + }, + }; + const routes = []; + globalThis.fetch = async (path, input) => { + routes.push(path); + assert.equal(input.headers["x-elastos-home-token"], "home-authority-fixture"); + let value; + if (path.endsWith("host-config")) value = { + projectId: "fixture-project", principal_id: "principal-fixture", internet: { status: "granted" }, + sdk_asset_path: pathToFileURL(resolve("scripts/lib/walletconnect-sdk-fixture.mjs")).href, + }; + else if (path.endsWith("/evm/link/challenge")) value = { + schema: "elastos.home.wallet-connector.effect.result/v1", action: "evm_link_challenge", connector_id: connector, + challenge: { schema: "elastos.auth.challenge/v1", challenge_id: "challenge:fixture", message: linkMessages[scenario] || linkMessage, expires_at: Math.floor(Date.now() / 1000) + 600, resources: [] }, + }; + else if (path.endsWith("/evm/link/verify")) { + const body = JSON.parse(input.body); + assert.equal(body.message, linkMessages[scenario] || linkMessage); assert.equal(body.signature, signature); + value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "evm_link_complete", connector_id: connector, status: "linked" }; + } + else if (path.endsWith("/review")) value = { address, chain_namespace: "eip155:20", expires_at: Math.floor(Date.now() / 1000) + 600 }; + else if (path.endsWith("/handoff")) value = { + schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_handoff", + connector_id: connector, request_id: "approval:fixture", evm_chains: [], + handoff: { schema: "elastos.wallet.webconnect_handoff/v1", request_id: "approval:fixture", intent: "transaction_intent", + payload_hash: payloadHash, signer: address, status: "awaiting_wallet_transaction", + transaction: { from: address, to: `0x${"78".repeat(20)}`, value: "0x1", data: "0x", gas: "0x5208", gasPrice: "0x1", nonce: "0x1", chainId: "0x14" }, + }, + binding: { principal_id: "principal-fixture", requested_by_actor: "documents", account_id: "account-fixture", chain_namespace: "eip155:20", + payload_hash: payloadHash, expires_at: scenario === "expired" ? 1 : Math.floor(Date.now() / 1000) + 600 }, + }; + else if (path.endsWith("/complete")) { + const body = JSON.parse(input.body); + assert.equal(body.payload_hash, payloadHash); + assert.equal(body.signer, address); + assert.equal(body.transaction_hash, transactionHash); + value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_complete", connector_id: connector, + request_id: "approval:fixture", status: "completed" }; + } else throw new Error(`Unexpected Runtime route: ${path}`); + return { ok: true, json: async () => value }; + }; + let reply; + const complete = new Promise(resolveReply => { reply = resolveReply; }); + const context = { kind: "app-frame", targetId: connector, homeToken: "connector-fixture", walletEffectState: { inFlight: false, requestIds: new Set() } }; + const data = { type: host.WALLET_CONNECTOR_EFFECT_TYPE, schema: host.WALLET_CONNECTOR_EFFECT_SCHEMA, + requestId: "request:fixture", connectorId: scenario === "wrong-capsule" ? "wallet-metamask" : connector, + connectorToken: "connector-fixture", action: scenario.startsWith("link") ? { kind: "link" } : { kind: "approve", approvalRequestId: "approval:fixture" } }; + if (scenario === "injected-payload") data.action.payload = { to: "attacker" }; + assert.equal(host.handleHomeWalletConnectorEffect({ source: { postMessage: reply } }, context, data), true); + return { response: await complete, calls, routes }; +} + +test("trusted Home signs the exact Runtime transaction once", async () => { + const result = await fixture("valid"); + assert.equal(result.response.error, undefined, result.response.error); + assert.equal(result.calls.filter(c => c.method === "eth_sendTransaction").length, 1); + assert.ok(result.calls.find(c => c.method === "eth_sendTransaction").expiry >= 300); + assert.ok(result.calls.find(c => c.method === "eth_sendTransaction").expiry <= 600); + assert.equal(result.calls.find(c => c.method === "eth_sendTransaction").params[0].to, `0x${"78".repeat(20)}`); +}); +for (const scenario of ["wrong-account", "wrong-chain", "wrong-capsule", "expired", "injected-payload"]) { + test(`trusted Home refuses ${scenario} before a signing effect`, async () => { + const result = await fixture(scenario); + assert.equal(typeof result.response.error, "string"); + assert.equal(result.calls.filter(c => c.method === "eth_sendTransaction").length, 0); + assert.equal(result.routes.filter(p => p.endsWith("/complete")).length, 0); + }); +} + +test("WalletConnect signs the exact UTF-8 ownership proof as EIP-1193 DATA", async () => { + const result = await fixture("link"); + assert.equal(result.response.error, undefined, result.response.error); + assert.equal(result.response.result.status, "linked"); + assert.deepEqual(result.calls.find(c => c.method === "personal_sign").params, + ["0x" + Buffer.from(linkMessage, "utf8").toString("hex"), address]); +}); + +for (const [scenario, expected] of [["link-uppercase-hex", "0x4142"], ["link-odd-hex", "0x3078313233"]]) { + test(`WalletConnect personal_sign matches wallet-provider bytes for ${scenario}`, async () => { + const result = await fixture(scenario); + assert.equal(result.response.error, undefined, result.response.error); + assert.equal(result.calls.find(c => c.method === "personal_sign").params[0], expected); + }); +} diff --git a/scripts/walletconnect-runtime.test.mjs b/scripts/walletconnect-runtime.test.mjs new file mode 100644 index 000000000..82ed1ac3d --- /dev/null +++ b/scripts/walletconnect-runtime.test.mjs @@ -0,0 +1,133 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { runtimeStorage } from "./walletconnect/runtime-storage.mjs"; +import { configureRuntime, WebSocket } from "./walletconnect/runtime-websocket.mjs"; + +test("Runtime socket keeps relay credentials and launch authority out of URLs", () => { + const opened = []; + class Native { + constructor(url) { this.url = url; this.sent = []; opened.push(this); } + send(value) { this.sent.push(value); } + close() { this.onclose(); } + } + configureRuntime({ url: "ws://home.test/api/apps/wallet-walletconnect/relay", token: "principal-a-token", WebSocket: Native }); + const relay = "wss://relay.walletconnect.org/?auth=fixture-secret&projectId=fixture-project"; + const socket = new WebSocket(relay); + configureRuntime({ url: "ws://other.test/relay", token: "principal-b-token", WebSocket: Native }); + assert.equal(opened[0].url, "ws://home.test/api/apps/wallet-walletconnect/relay"); + opened[0].onopen(); + assert.deepEqual(JSON.parse(opened[0].sent[0]), { token: "principal-a-token", relay }); + assert.equal(socket.readyState, WebSocket.CONNECTING); + assert.throws(() => socket.send("too-early")); + let ready = 0; let payload; + socket.onopen = () => { ready++; }; + socket.onmessage = event => { payload = event.data; }; + opened[0].onmessage({ data: '{"ready":true}' }); + assert.equal(ready, 1); + socket.send("encrypted-request"); + assert.equal(opened[0].sent[1], "encrypted-request"); + opened[0].onmessage({ data: "encrypted-response" }); + assert.equal(payload, "encrypted-response"); + socket.close(); assert.equal(socket.readyState, WebSocket.CLOSED); +}); + +test("SDK storage serializes Runtime writes and recovers through a fresh adapter", async () => { + let state = {}; + const writes = []; + const api = async (path, input) => { + assert.equal(path, "storage"); + if (input) { + const { key, value } = JSON.parse(input.body); + writes.push(key); + if (value === null) delete state[key]; else state[key] = value; + } + return structuredClone(state); + }; + const first = runtimeStorage(api); + await Promise.all([first.setItem("session", { topic: "fixture", expiry: 100 }), first.setItem("keychain", "fixture-key")]); + const second = runtimeStorage(api); + assert.deepEqual(await second.getItem("session"), { topic: "fixture", expiry: 100 }); + assert.deepEqual(await second.getKeys(), ["session", "keychain"]); + await second.removeItem("session"); + assert.equal(await second.getItem("session"), undefined); + assert.deepEqual(writes, ["session", "keychain", "session"]); + const broken = runtimeStorage(async () => { throw new Error("refused"); }); + await assert.rejects(broken.setItem("session", "x"), /refused/); +}); + +test("a refused or closed Runtime admission rejects SDK registration before ready", async () => { + let native; + class Native { + constructor() { native = this; this.sent = []; } + send(value) { this.sent.push(value); } + close() { this.onclose(); } + } + configureRuntime({ url: "ws://home.test/relay", WebSocket: Native, authorize: async () => { throw new Error("refused"); } }); + const refused = new WebSocket("wss://relay.walletconnect.org/"); + let errors = 0; refused.onerror = () => { errors++; }; + await native.onopen(); + assert.equal(errors, 1); + assert.equal(refused.readyState, WebSocket.CLOSED); + assert.deepEqual(native.sent, []); + configureRuntime({ url: "ws://home.test/relay", WebSocket: Native, token: "fixture" }); + const closed = new WebSocket("wss://relay.walletconnect.org/"); + closed.onerror = () => { errors++; }; + native.onclose(); + assert.equal(errors, 2, "the SDK register() promise receives an error before open"); +}); + +test("the whole adapter dependency graph has registry integrity and exact roots", async () => { + const manifest = JSON.parse(await readFile(new URL("./walletconnect/package.json", import.meta.url))); + const lock = JSON.parse(await readFile(new URL("./walletconnect/package-lock.json", import.meta.url))); + assert.deepEqual(lock.packages[""].dependencies, manifest.dependencies); + for (const version of Object.values({ ...manifest.dependencies, ...manifest.devDependencies })) { + assert.match(version, /^\d+\.\d+\.\d+$/); + } + for (const [path, entry] of Object.entries(lock.packages)) { + if (!path) continue; + assert.match(entry.resolved, /^https:\/\/registry\.npmjs\.org\//, path); + assert.match(entry.integrity, /^sha512-/, path); + } +}); + +test("the shipped bundle matches the locked graph and current adapter sources", async () => { + const vendor = new URL("../capsules/wallet-walletconnect/vendor/", import.meta.url); + const manifest = JSON.parse(await readFile(new URL("adapter.json", vendor))); + const sha = bytes => createHash("sha256").update(bytes).digest("hex"); + assert.equal(manifest.sdk_sha256, sha(await readFile(new URL("reown-appkit.js", vendor)))); + assert.equal(manifest.dependency_lock_sha256, sha(await readFile(new URL("walletconnect/package-lock.json", import.meta.url)))); + assert.deepEqual(manifest.source_sha256, Object.fromEntries(await Promise.all( + ["adapter.mjs", "runtime-storage.mjs", "runtime-websocket.mjs", "../vendor-walletconnect-adapter.sh"].map(async file => + [file, sha(await readFile(new URL(`walletconnect/${file}`, import.meta.url)))]), + ))); +}); + +test("release stage installs config automatically only from the operator file and the reviewed bundle", async () => { + const dir = await mkdtemp(join(tmpdir(), "wc-release-")); + try { + const vendor = join(dir, "vendor"); await mkdir(vendor); + const sdk = "export const fixture = true;"; + await writeFile(join(vendor, "reown-appkit.js"), sdk); + await writeFile(join(vendor, "adapter.json"), JSON.stringify({ + sdk_package: "@walletconnect/ethereum-provider", sdk_version: "2.23.9", + sdk_sha256: createHash("sha256").update(sdk).digest("hex"), + })); + const script = resolve("scripts/stage-walletconnect-release.mjs"); + const env = { ...process.env }; delete env.ELASTOS_WALLETCONNECT_PROJECT_FILE; delete env.ELASTOS_WALLETCONNECT_PROJECT_ID; + execFileSync(process.execPath, [script, dir], { env }); + await assert.rejects(readFile(join(vendor, "connector.json")), /ENOENT/); + const project = join(dir, "operator-project"); await writeFile(project, "fixture-project-id"); + env.ELASTOS_WALLETCONNECT_PROJECT_FILE = project; + execFileSync(process.execPath, [script, dir], { env }); + const config = JSON.parse(await readFile(join(vendor, "connector.json"))); + assert.equal(config.schema, "elastos.walletconnect.connector/v1"); + assert.equal(config.project_id, "fixture-project-id"); + await writeFile(join(vendor, "reown-appkit.js"), "tampered"); + assert.throws(() => execFileSync(process.execPath, [script, dir], { env, stdio: "pipe" }), /failed/); + } finally { await rm(dir, { recursive: true, force: true }); } +}); diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs new file mode 100644 index 000000000..4e053cc04 --- /dev/null +++ b/scripts/walletconnect-sdk.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import http from "node:http"; +import { readFileSync, mkdirSync } from "node:fs"; +import { createRequire } from "node:module"; +const require = createRequire(new URL("../elastos/tools/browser-playwright-engine/package.json", import.meta.url)); +const { chromium } = require("playwright"); +const bundle = readFileSync(new URL("../capsules/wallet-walletconnect/vendor/reown-appkit.js", import.meta.url)); + +const fixture = ` +import { connectWalletConnectEvm } from '/sdk.js'; +window.methods = []; window.nativeUrls = []; +window.keys = Object.create(null); window.cancelled = false; window.failed = false; +class RelaySocket { + constructor(url) { + window.nativeUrls.push(url); this.readyState = 0; + queueMicrotask(() => { this.readyState = 1; this.onopen?.(); }); + } + send(raw) { + const message = JSON.parse(raw); + if (message.token) { + queueMicrotask(() => this.onmessage?.({ data: '{"ready":true}' })); return; + } + if (!message.method) return; + window.methods.push(message.method); + const result = message.method.endsWith('batchSubscribe') ? message.params.topics.map((_, i) => 'sub-' + i) + : message.method.endsWith('subscribe') ? 'fixture-subscription' : true; + queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ jsonrpc:'2.0', id:message.id, result }) })); + } + close() { this.readyState = 3; this.onclose?.(); } +} +globalThis.WebSocket = RelaySocket; +const api = async (path, input) => { + if (path === 'relay-admission') return { token:'fixture-admission' }; + if (path !== 'storage') throw new Error('unexpected Runtime resource'); + if (input) { + const { key, value } = JSON.parse(input.body); + if (value === null) delete window.keys[key]; else window.keys[key] = value; + } + return structuredClone(window.keys); +}; +window.pending = connectWalletConnectEvm({ + contextKey:'principal-fixture', projectId:'fixture-project-id', chains:[1], api, + relayUrl:location.origin.replace(/^http/, 'ws') + '/relay', + runtimeUrl:new URLSearchParams(location.search).has('relative') ? '/api/apps/wallet-walletconnect' : location.origin + '/api/apps/wallet-walletconnect', + metadata:{name:'Isolated Runtime fixture', description:'WalletConnect test', url:location.origin, icons:[]}, +}).catch(error => { window.cancelled = error.message === 'Wallet connection cancelled.'; window.failed = !window.cancelled; }); +`; + +test("the locked SDK reaches QR through Home, stores its keys through Runtime, and cancels", { timeout: 45000 }, async () => { + const server = http.createServer((req, res) => { + res.setHeader("content-security-policy", "default-src 'self'; script-src 'self'; connect-src 'self'; frame-src 'self'; style-src 'self'"); + if (req.url === "/sdk.js") { res.setHeader("content-type", "text/javascript"); res.end(bundle); } + else if (req.url === "/fixture.js") { res.setHeader("content-type", "text/javascript"); res.end(fixture); } + else { res.setHeader("content-type", "text/html"); res.end(''); } + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const origin = `http://127.0.0.1:${server.address().port}`; + let browser; + try { + browser = await chromium.launch({ headless: true }); + const invalid = await browser.newContext(); + const invalidPage = await invalid.newPage(); + await invalid.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); + await invalidPage.goto(`${origin}/?relative`); + await invalidPage.waitForFunction(() => window.failed, null, { timeout: 20000 }); + assert.equal(await invalidPage.locator("dialog[open]").count(), 0, "a relative RPC URL cannot initialize the real SDK"); + await invalid.close(); + for (const width of [1280, 390]) { + const context = await browser.newContext({ viewport: { width, height: 800 } }); + // CSP remains the same Home-only network boundary used by the product. + await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); + const page = await context.newPage(); + await page.goto(origin); + await page.locator("dialog[open] canvas").waitFor({ timeout: 20000 }); + const state = await page.evaluate(() => ({ + homeOnly: window.nativeUrls.length > 0 && window.nativeUrls.every(url => url === location.origin.replace(/^http/, "ws") + "/relay"), + subscribed: window.methods.some(method => method.endsWith("subscribe")), + runtimeKeys: Object.keys(window.keys).some(key => key.includes("keychain")), + localKeys: localStorage.length, + canvas: document.querySelector("canvas").width, + fits: document.querySelector("dialog").getBoundingClientRect().width <= innerWidth, + })); + assert.equal(state.homeOnly, true, "SDK sockets terminate at Home"); + assert.equal(state.subscribed, true); + assert.equal(state.runtimeKeys, true, "SDK keychain reaches the Runtime storage adapter"); + assert.equal(state.localKeys, 0); + assert.ok(state.canvas > 0); + assert.equal(state.fits, true); + if (process.env.WALLETCONNECT_SCREENSHOTS) { + mkdirSync(process.env.WALLETCONNECT_SCREENSHOTS, { recursive: true }); + await page.screenshot({ path: `${process.env.WALLETCONNECT_SCREENSHOTS}/qr-${width}.png` }); + } + await page.getByRole("button", { name: "Cancel", exact: true }).click(); + await page.waitForFunction(() => window.cancelled); + assert.equal(await page.locator("dialog").count(), 0); + await context.close(); + } + } finally { + await browser?.close(); + server.closeAllConnections(); + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/scripts/walletconnect/adapter.mjs b/scripts/walletconnect/adapter.mjs new file mode 100644 index 000000000..5d512ecb5 --- /dev/null +++ b/scripts/walletconnect/adapter.mjs @@ -0,0 +1,78 @@ +import { EthereumProvider } from "@walletconnect/ethereum-provider"; +import QRCode from "qrcode"; +import { configureRuntime } from "./runtime-websocket.mjs"; +import { runtimeStorage } from "./runtime-storage.mjs"; + +// The relay-only adapter uses Reown's provider and a bundled QR renderer. It +// needs neither the hosted wallet picker nor an external RPC for signing. +let provider; +let contextKey; +let currentApi; +const api = (...args) => currentApi(...args); +export async function connectWalletConnectEvm(options) { + if (contextKey !== options.contextKey) { provider = null; contextKey = options.contextKey; } + currentApi = options.api; + configureRuntime({ url: options.relayUrl, authorize: () => options.api("relay-admission", { method: "POST" }) }); + provider ??= await EthereumProvider.init({ + projectId: options.projectId, + customStoragePrefix: options.contextKey, + chains: [options.chains[0]], + optionalChains: options.chains.slice(1), + methods: ["personal_sign", "eth_sendTransaction"], + optionalMethods: [], + disableProviderPing: true, + events: ["accountsChanged", "chainChanged"], + showQrModal: false, + storage: runtimeStorage(api), + logger: "silent", + telemetryEnabled: false, + metadata: options.metadata, + // Non-wallet read RPCs have no network route in this adapter. + rpcMap: Object.fromEntries(options.chains.map(id => [id, `${options.runtimeUrl}/unavailable-rpc`])), + }); + // init() restores a live session from Runtime storage. Reopen its transport + // instead of asking the phone to approve another pairing after a restart. + await provider.signer.client.core.relayer.transportOpen(); + if (provider.connected && provider.session?.expiry > Date.now() / 1000) return provider; + const dialog = document.createElement("dialog"); + const text = document.createElement("p"); + text.textContent = "Scan with your phone wallet, then approve the connection there."; + const canvas = document.createElement("canvas"); + const cancel = document.createElement("button"); + cancel.textContent = "Cancel"; + cancel.type = "button"; + dialog.append(text, canvas, cancel); + let rejectCancel; + const cancelled = new Promise((_, reject) => { rejectCancel = reject; }); + const stop = () => { + provider.signer.abortPairingAttempt(); + provider.signer.client.core.relayer.transportClose().catch(() => {}); + rejectCancel(new Error("Wallet connection cancelled.")); + }; + cancel.onclick = stop; + dialog.addEventListener("cancel", stop); + const display = uri => { + QRCode.toCanvas(canvas, uri, { width: 280, margin: 2 }).catch(stop); + if (!dialog.open) dialog.showModal(); + }; + provider.on("display_uri", display); + document.body.append(dialog); + let timer; + try { + await Promise.race([ + provider.connect(), cancelled, + new Promise((_, reject) => { timer = setTimeout(() => { stop(); reject(new Error("Wallet connection expired.")); }, 180000); }), + ]); + return provider; + } finally { + clearTimeout(timer); + provider.removeListener("display_uri", display); + dialog.remove(); + } +} + +export async function disconnectWalletConnectEvm(options) { + currentApi = options.api; + try { if (provider?.session) await provider.disconnect(); } + finally { await provider?.signer.client.core.relayer.transportClose(); } +} diff --git a/scripts/walletconnect/package-lock.json b/scripts/walletconnect/package-lock.json new file mode 100644 index 000000000..f231e7c35 --- /dev/null +++ b/scripts/walletconnect/package-lock.json @@ -0,0 +1,4930 @@ +{ + "name": "walletconnect", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@walletconnect/ethereum-provider": "2.23.9", + "qrcode": "1.5.4" + }, + "devDependencies": { + "esbuild": "0.28.0" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@base-org/account": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@base-org/account/-/account-2.4.0.tgz", + "integrity": "sha512-A4Umpi8B9/pqR78D1Yoze4xHyQaujioVRqqO3d6xuDFw9VRtjg6tK3bPlwE0aW+nVH/ntllCpPa2PbI8Rnjcug==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@coinbase/cdp-sdk": "^1.0.0", + "@noble/hashes": "1.4.0", + "clsx": "1.2.1", + "eventemitter3": "5.0.1", + "idb-keyval": "6.2.1", + "ox": "0.6.9", + "preact": "10.24.2", + "viem": "^2.31.7", + "zustand": "5.0.3" + } + }, + "node_modules/@coinbase/cdp-sdk": { + "version": "1.62.0", + "resolved": "https://registry.npmjs.org/@coinbase/cdp-sdk/-/cdp-sdk-1.62.0.tgz", + "integrity": "sha512-i25CM7YkheI4bIUUfdEl1ZFl8OhPtlr6HsOULSSPrOOetEEIo6KC81vr3RmrhejwYLzC9GSbVbfxy2pxgjPIXQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana-program/system": "^0.16.0", + "@solana-program/token": "^0.16.0", + "@solana/kit": "^8.6.0", + "abitype": "1.0.6", + "axios": "^1.18.0", + "axios-retry": "^4.5.0", + "bs58": "^6.0.0", + "jose": "^6.2.0", + "md5": "^2.3.0", + "uncrypto": "^0.1.3", + "viem": "^2.47.0", + "zod": "^3.25.76" + }, + "peerDependencies": { + "@x402/core": "^2.29.0", + "@x402/evm": "^2.29.0", + "@x402/extensions": "^2.29.0", + "@x402/svm": "^2.29.0" + }, + "peerDependenciesMeta": { + "@x402/core": { + "optional": true + }, + "@x402/evm": { + "optional": true + }, + "@x402/extensions": { + "optional": true + }, + "@x402/svm": { + "optional": true + } + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", + "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", + "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", + "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", + "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", + "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", + "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", + "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", + "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", + "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", + "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", + "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", + "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", + "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", + "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", + "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", + "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", + "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", + "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", + "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", + "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", + "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", + "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", + "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", + "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", + "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@lit-labs/ssr-dom-shim": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz", + "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@lit/react": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@lit/react/-/react-1.0.8.tgz", + "integrity": "sha512-p2+YcF+JE67SRX3mMlJ1TKCSTsgyOVdAwd/nxp3NuV1+Cb6MWALbN6nT7Ld4tpmYofcE5kcaSY1YBB9erY+6fw==", + "license": "BSD-3-Clause", + "optional": true, + "peerDependencies": { + "@types/react": "17 || 18 || 19" + } + }, + "node_modules/@lit/reactive-element": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz", + "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0" + } + }, + "node_modules/@msgpack/msgpack": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz", + "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.8.0.tgz", + "integrity": "sha512-j84kjAbzEnQHaSIhRPUmB3/eVXu2k3dKPl2LOrR8fSOIL+89U+7lV117EWHtq/GHM3ReGHM46iRBdZfpc4HRUQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.7.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves/node_modules/@noble/hashes": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.0.tgz", + "integrity": "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz", + "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@phosphor-icons/webcomponents": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@phosphor-icons/webcomponents/-/webcomponents-2.1.5.tgz", + "integrity": "sha512-JcvQkZxvcX2jK+QCclm8+e8HXqtdFW9xV4/kk2aL9Y3dJA2oQVt+pzbv1orkumz3rfx4K9mn9fDoMr1He1yr7Q==", + "license": "MIT", + "dependencies": { + "lit": "^3" + } + }, + "node_modules/@reown/appkit": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit/-/appkit-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-7JjEp+JNxRUDOa7CxOCbUbG8uYVo38ojc9FN/fuzJuJADUzKDaH287MLV9qI1ZyQyXA8qXvhXRqjtw+3xo2/7A==", + "hasInstallScript": true, + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-pay": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-scaffold-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/universal-provider": "2.23.2", + "bs58": "6.0.0", + "semver": "7.7.2", + "valtio": "2.1.7", + "viem": ">=2.37.9" + }, + "optionalDependencies": { + "@lit/react": "1.0.8" + } + }, + "node_modules/@reown/appkit-common": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-common/-/appkit-common-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-wf53EzDmCJ5ICtDY5B1MddVeCwoqDGPVmaxD4wQJLR9uanhBXfKq1sJou+Uj8lZCyI72Z+r9YlsePOlYH2Ge3A==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "big.js": "6.2.2", + "dayjs": "1.11.13", + "viem": ">=2.37.9" + } + }, + "node_modules/@reown/appkit-controllers": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-controllers/-/appkit-controllers-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-wY5yvMB0o2AwitwDHHO0u2tmqR+n3Crv0AHjIcY037PC3mhF9TPEUKqE9vlrFImQWQRxl0WRfuKfzmUAPxZExw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/universal-provider": "2.23.2", + "valtio": "2.1.7", + "viem": ">=2.37.9" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@msgpack/msgpack": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", + "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/core": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", + "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.39.3", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/sign-client": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", + "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.2", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/types": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", + "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/universal-provider": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", + "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "es-toolkit": "1.39.3", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/utils": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", + "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.2", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "bs58": "6.0.0", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@reown/appkit-controllers/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-controllers/node_modules/es-toolkit": { + "version": "1.39.3", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", + "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/@reown/appkit-controllers/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-controllers/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-pay": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-pay/-/appkit-pay-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-sVE8UT7CDA8zsg3opvbGjSZHSnohOVPF77vP6Ln4G0+vfoiXNhZaZa89Pg0MDjh+KGy0OulWVUdXuZ9jJQFvPg==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", + "lit": "3.3.0", + "valtio": "2.1.7" + } + }, + "node_modules/@reown/appkit-polyfills": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-polyfills/-/appkit-polyfills-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-OyYavslCegfUlKu8Ah6BZhbqQrK7bImvUm+EKjjvnfNN9J0F9uWMFwbTpZxenBcfAI6cyaD9aTTUunMn5no1Og==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "buffer": "6.0.3" + } + }, + "node_modules/@reown/appkit-scaffold-ui": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-scaffold-ui/-/appkit-scaffold-ui-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-f+SYFGDy+uY1EAvWcH6vZgga1bOuzBvYSKYiRX2QQy8INtZqwwiLLvS4cgm5Yp1WvYRal5RdfZkKl5qha498gw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-pay": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "lit": "3.3.0" + } + }, + "node_modules/@reown/appkit-ui": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-ui/-/appkit-ui-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-E1u2ZVZV0iFDSgrgtdQTZAXNbI+Lakj8E8V+jJQ47JaEVKv9SROvPu2fVqfIrqHQF68NmAk1dnbYi4luOiM0Fg==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@phosphor-icons/webcomponents": "2.1.5", + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "lit": "3.3.0", + "qrcode": "1.5.3" + } + }, + "node_modules/@reown/appkit-ui/node_modules/qrcode": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.3.tgz", + "integrity": "sha512-puyri6ApkEHYiVl4CFzo1tDkAZ+ATcnbJrJ6RiBM1Fhctdn/ix9MTE3hRph33omisEbC/2fcfemsseiKgBPKZg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "encode-utf8": "^1.0.3", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/@reown/appkit-utils": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-utils/-/appkit-utils-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-9El8sYbXDaMYxg4R6LujA965yYQGjNcPMXqympLtzNl1es5qkniW7eAdEpLmZrsaqNrfTaHT1G65wYy7sA595w==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", + "@wallet-standard/wallet": "1.1.0", + "@walletconnect/logger": "3.0.2", + "@walletconnect/universal-provider": "2.23.2", + "valtio": "2.1.7", + "viem": ">=2.37.9" + }, + "optionalDependencies": { + "@base-org/account": "2.4.0", + "@safe-global/safe-apps-provider": "0.18.6", + "@safe-global/safe-apps-sdk": "9.1.0" + }, + "peerDependencies": { + "valtio": "2.1.7" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@msgpack/msgpack": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", + "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/core": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", + "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.39.3", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/sign-client": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", + "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.2", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/types": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", + "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/universal-provider": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", + "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "es-toolkit": "1.39.3", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit-utils/node_modules/@walletconnect/utils": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", + "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.2", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "bs58": "6.0.0", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@reown/appkit-utils/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-utils/node_modules/es-toolkit": { + "version": "1.39.3", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", + "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/@reown/appkit-utils/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@reown/appkit-utils/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit-wallet": { + "version": "1.8.17-wc-circular-dependencies-fix.0", + "resolved": "https://registry.npmjs.org/@reown/appkit-wallet/-/appkit-wallet-1.8.17-wc-circular-dependencies-fix.0.tgz", + "integrity": "sha512-s0RTVNtgPtXGs+eZELVvTu1FRLuN15MyhVS//3/4XafVQkBBJarciXk9pFP71xeSHRzjYR1lXHnVw28687cUvQ==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", + "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/logger": "3.0.2", + "zod": "3.22.4" + } + }, + "node_modules/@reown/appkit-wallet/node_modules/zod": { + "version": "3.22.4", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz", + "integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/@reown/appkit/node_modules/@msgpack/msgpack": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", + "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", + "license": "ISC", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@reown/appkit/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/core": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", + "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.39.3", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/sign-client": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", + "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.2", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/types": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", + "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/universal-provider": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", + "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/utils": "2.23.2", + "es-toolkit": "1.39.3", + "events": "3.3.0" + } + }, + "node_modules/@reown/appkit/node_modules/@walletconnect/utils": { + "version": "2.23.2", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", + "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.2", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.2", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "bs58": "6.0.0", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@reown/appkit/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@reown/appkit/node_modules/es-toolkit": { + "version": "1.39.3", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", + "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/@reown/appkit/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@reown/appkit/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@safe-global/safe-apps-provider": { + "version": "0.18.6", + "resolved": "https://registry.npmjs.org/@safe-global/safe-apps-provider/-/safe-apps-provider-0.18.6.tgz", + "integrity": "sha512-4LhMmjPWlIO8TTDC2AwLk44XKXaK6hfBTWyljDm0HQ6TWlOEijVWNrt2s3OCVMSxlXAcEzYfqyu1daHZooTC2Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@safe-global/safe-apps-sdk": "^9.1.0", + "events": "^3.3.0" + } + }, + "node_modules/@safe-global/safe-apps-sdk": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/@safe-global/safe-apps-sdk/-/safe-apps-sdk-9.1.0.tgz", + "integrity": "sha512-N5p/ulfnnA2Pi2M3YeWjULeWbjo7ei22JwU/IXnhoHzKq3pYCN6ynL9mJBOlvDVv892EgLPCWCOwQk/uBT2v0Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@safe-global/safe-gateway-typescript-sdk": "^3.5.3", + "viem": "^2.1.1" + } + }, + "node_modules/@safe-global/safe-gateway-typescript-sdk": { + "version": "3.23.1", + "resolved": "https://registry.npmjs.org/@safe-global/safe-gateway-typescript-sdk/-/safe-gateway-typescript-sdk-3.23.1.tgz", + "integrity": "sha512-6ORQfwtEJYpalCeVO21L4XXGSdbEMfyp2hEv6cP82afKXSwvse6d3sdelgaPWUxHIsFRkWvHDdzh8IyyKHZKxw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=16" + } + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", + "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.9.0", + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", + "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@solana-program/system": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@solana-program/system/-/system-0.16.0.tgz", + "integrity": "sha512-/RG6q2E2vG/XpdOt8Jj/kbQktPlL5JyJuNGAeN9wDcxKDKQtrGTJpDrJgQUxiEy23fsPNXQbLN8XeCtYoMof3Q==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@solana/kit": "^8.5.0" + } + }, + "node_modules/@solana-program/token": { + "version": "0.16.1", + "resolved": "https://registry.npmjs.org/@solana-program/token/-/token-0.16.1.tgz", + "integrity": "sha512-X9dsvbh+VDq4SuCfvxn95P1DCvtBYHJOBiVmgBJMfW8l/lp8uSwEhy9IurpcdltnGi5kNIkCm4sk4YOXKAMiCw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@solana-program/system": "^0.14.0" + }, + "peerDependencies": { + "@solana/kit": "^8.0.0" + } + }, + "node_modules/@solana-program/token/node_modules/@solana-program/system": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/@solana-program/system/-/system-0.14.1.tgz", + "integrity": "sha512-K6ZiIrAKoJAfcwfUdsoFvfSAxeRJaRrV7BPFTJvUVRS4m3zszN+nLcdaNMMe2F1/zTriZqC+xh+Kgw6ziGUqpQ==", + "license": "Apache-2.0", + "optional": true, + "peerDependencies": { + "@solana/kit": "^8.0.0" + } + }, + "node_modules/@solana/accounts": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/accounts/-/accounts-8.6.0.tgz", + "integrity": "sha512-yIcrKjbUXzs1K6KkcRJfAHFOsn8Jpp9AeczcHOHQoBv11AxHM5KmdCTv8rnv7OObq696sd3gpbamVxtqnL0meQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/addresses": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/addresses/-/addresses-8.6.0.tgz", + "integrity": "sha512-V30spa+zKsY7i4elEEOZQB/1xpRc0CzbSypI/yTZwj/Bg1o09T6A+pflMDTBoIWH3sglmigdK1jApEOOA7Bypg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/assertions": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/nominal-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/assertions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/assertions/-/assertions-8.6.0.tgz", + "integrity": "sha512-zQFbZoPFE3GqBw/7JyZxaH5t/Ibm7eHOmOfRI542/zz0BHWSnMkR0N5aSndPJd9creMUP+mFtX8hAr6bZ6rDBg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs/-/codecs-8.6.0.tgz", + "integrity": "sha512-7vUVLdYlTay3rsijiBPN4g992V8RXbgY2DNAXrsE6eHFnwaX8gzdDNASgF4Z0mbgNC026qdLG6LTY4l16tvE8g==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/fixed-points": "8.6.0", + "@solana/options": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-core": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-core/-/codecs-core-8.6.0.tgz", + "integrity": "sha512-1N2XZ1yCJGmdTE3g5Fh6/UOE6y46qing+7CZpxfrgB4Q+1l+R/d0z4G15IpQUNl3vzqML8CFF791f/A1XSVmJA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-data-structures": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-data-structures/-/codecs-data-structures-8.6.0.tgz", + "integrity": "sha512-BLwclFSLVqugUktXucjGfpUFSaX4V7payjSi6x0DDdLs6PaFfjiH3ykQPV5QRkTeOlf0xC6dOMUUntDhYzVyGw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-numbers": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-numbers/-/codecs-numbers-8.6.0.tgz", + "integrity": "sha512-GRIArvWJiYxH5w1RMKn7IOCLy0uYB/WRT2kFW/uyXHzL1VNFyud2BIzG0D3iM+AxTd85SdS/x93aV7NEw0mTOQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/codecs-strings": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/codecs-strings/-/codecs-strings-8.6.0.tgz", + "integrity": "sha512-bLS/o5NdCRb9xj23zLACPjxYvDhdjvSDH4XoBAmQ1CPn3cDvVqVvAz0T41Bs/LMykhamkmpqTcWLoTOVqjTz3w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "fastestsmallesttextencoderdecoder": "^1.0.22", + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "fastestsmallesttextencoderdecoder": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/errors": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/errors/-/errors-8.6.0.tgz", + "integrity": "sha512-viHL51ymR1HZB7ZTp0ESkLOyHCa4bPfok9dvRYbMmYokY5ys1xinISKHUhcOHsg9zbuAWBRJUOnZRWAPbb4+yA==", + "license": "MIT", + "optional": true, + "dependencies": { + "chalk": "5.6.2", + "commander": "15.0.0" + }, + "bin": { + "errors": "bin/cli.mjs" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/fast-stable-stringify": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/fast-stable-stringify/-/fast-stable-stringify-8.6.0.tgz", + "integrity": "sha512-PVuzLesqjvuW1qeg0brkUtpRnQYCLS0mB7SsFu+iio+dxFzbrrHzkSYVoUBEEbjXysCq1L350Frs1+v7CEsXGQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/fixed-points": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/fixed-points/-/fixed-points-8.6.0.tgz", + "integrity": "sha512-yS0XIHwWETtTjAgUHPhpQpcigPvC6phba3vW7rvVPSvVz1FhxNki82ojyl1pISglK7IkUTYcGhaXDhsY/oz8rQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/functional": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/functional/-/functional-8.6.0.tgz", + "integrity": "sha512-greLf2tiMJ5oWaSdp3zkAcUF3sIG3CU1UssxoMYNHy/xywbZifKnOl5syQjKY1XdYPZZmLAWJBFYCkzVns5bxA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/instruction-plans": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/instruction-plans/-/instruction-plans-8.6.0.tgz", + "integrity": "sha512-hq1bLZStauHKmwHWheCoF9UxcFlJsYm9X4saUj4llkJl6GmTrDTmeiE93mJngz4GO6cAkm65D/AjYRcp69jUVw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/instructions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/instructions/-/instructions-8.6.0.tgz", + "integrity": "sha512-1mXhgf5XaIJir02TgkUwzNRJs8mCCRRRsW45ZwqCp66bnIxmxEy3a91twgGXvBfE6dvzzg3TNSjcfqGQ/ADBog==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/keys": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/keys/-/keys-8.6.0.tgz", + "integrity": "sha512-vxj3zmcHfY0EqDSJR8nn7w/qQAdCG3uSyGGcIfLgf/ZhVUgVDYDUyUqrxSL5DxAs64czhSu+ufRh7B5AKwMtaQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/assertions": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/promises": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/kit": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/kit/-/kit-8.6.0.tgz", + "integrity": "sha512-UaigU+LiTzkU237FxfiJhxufvEfb1J02djJOnGpSz1GAjZtbZ8oc4EkQ1bS4sHewSRyR9RUk6yhBb5bLHG0w4w==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/addresses": "8.6.0", + "@solana/codecs": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/offchain-messages": "8.6.0", + "@solana/plugin-core": "8.6.0", + "@solana/plugin-interfaces": "8.6.0", + "@solana/program-client-core": "8.6.0", + "@solana/programs": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc": "8.6.0", + "@solana/rpc-api": "8.6.0", + "@solana/rpc-parsed-types": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-subscriptions": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/signers": "8.6.0", + "@solana/subscribable": "8.6.0", + "@solana/sysvars": "8.6.0", + "@solana/transaction-confirmation": "8.6.0", + "@solana/transaction-introspection": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/nominal-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/nominal-types/-/nominal-types-8.6.0.tgz", + "integrity": "sha512-uuRReiuEWfTTwtlJNvTSStuHrDF45Itl2k3BGg/4kHWxqUdtS5u4PK4bMgzoPWoyPorDj5y6TEMa+MydM5D7Sg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/offchain-messages": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/offchain-messages/-/offchain-messages-8.6.0.tgz", + "integrity": "sha512-VFic3fotmL9fIjs7Amk402CMWLeWwhNQvAF9cyZO++x42oU2FNeTe27rxfgFLYPaIHaRonlII+5pmsHQHA240Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/nominal-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/options": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/options/-/options-8.6.0.tgz", + "integrity": "sha512-WFsTtIQukNGGHRImcmn8Se8o6A4vu4wY0fuLSeB/L7C45FPoQI2fTIud6hf9g2fum0dR3U0pFNIciwQjlVq2LA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/plugin-core": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/plugin-core/-/plugin-core-8.6.0.tgz", + "integrity": "sha512-wvjpR66FreDxDXfF5RrIay7aXW+JfcmSj1TiDu+rUyWaV1Xu390E/KKL3dM6OfkIOtP66H9M9w1XihB8syMkfg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/plugin-interfaces": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/plugin-interfaces/-/plugin-interfaces-8.6.0.tgz", + "integrity": "sha512-ta+JYsKD7GMUoBLbeE1nYKDPN9nOwQN1y04xR4tbyfDbNsGLPz3fTKH8Y48bOs552sW4OcUB8F3pGVZefqPyWg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/addresses": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/signers": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/program-client-core": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/program-client-core/-/program-client-core-8.6.0.tgz", + "integrity": "sha512-e6Wx2Y2UrQ0dPB6hndVcyUXQwBt9/DLr8k2P7tRgW0JNVhHNylZQ6aYQAqxZzS8Z92gGz7l3XL+r9tCLKBkIVw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/plugin-interfaces": "8.6.0", + "@solana/rpc-api": "8.6.0", + "@solana/signers": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/programs": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/programs/-/programs-8.6.0.tgz", + "integrity": "sha512-JKGtqXtiT4zon7xZkmys2G1/HchwbNjzbP+E+0Rp/Cko+svB9w9SE2PROEVJZS8UH98lbi1epjsHYAgESamwvg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/promises": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/promises/-/promises-8.6.0.tgz", + "integrity": "sha512-HLlAMwXnEyhg9HxVJGDlWgFlM4QUt/Qq0nL69bbC7COCHhUQFRcKLq5uIbaXPy7FNJlNBSTTCBZwI0IK9up0SQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc/-/rpc-8.6.0.tgz", + "integrity": "sha512-u5dg96ThDVAeklC9vtVpuYL7wRqkyolm++qYKd6yL7tPRdKZNxdGHbFHQR2qIcMQ0oVfEA9tGnQhplj+6Yt/0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/fast-stable-stringify": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/rpc-api": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-transport-http": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-api": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-api/-/rpc-api-8.6.0.tgz", + "integrity": "sha512-NFHtOB9z4HyV8frN84o+d9jKj5luRzrySZJLgwMgcG/Q2fWahTDrP+ZqRKLmqibvFBg/fwhcxl77+TfKZjpvhA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/rpc-parsed-types": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-parsed-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-parsed-types/-/rpc-parsed-types-8.6.0.tgz", + "integrity": "sha512-wZKtQOS3RdHZqJ3ycpdibup31tfbY6lHYGUKjmzeF6N2E2y7WEpB7qiEr9AMBB00mDUtorcqBMpOli6PyT4Gog==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-spec": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-spec/-/rpc-spec-8.6.0.tgz", + "integrity": "sha512-V1c+r6HXTb/nCEl5SHKLPzzb6aMEbr0lFOcgjEX8TQ8fE6ZlLzNz3tKvcgbBlOJCeyVXSrcNl3tv8i8xNp+n/g==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/subscribable": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-spec-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-spec-types/-/rpc-spec-types-8.6.0.tgz", + "integrity": "sha512-6+2F2BN2CXp4g7cnvLp2mRo/XwdN5At7f3HbdEablxNe1UvI5S8WIEY3l/Y+nh2NQIaEVz9fLjmTYV+UfZNzEg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions/-/rpc-subscriptions-8.6.0.tgz", + "integrity": "sha512-ZaoFtiKg25KqYykBslB8TDWqfm7S162FyTJvFI0HL0U94K1O675IG2h913mes3voatigpqLneFxkNrVs5yE7tA==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/fast-stable-stringify": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-subscriptions-api": "8.6.0", + "@solana/rpc-subscriptions-channel-websocket": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/subscribable": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions-api": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-api/-/rpc-subscriptions-api-8.6.0.tgz", + "integrity": "sha512-Cbyi0ZpwNCcxRgjjc1vKVWBdwNOAKGT1VjryfQU/FDySUo2Lg8u5LUsJb6d53QD5dhEU+0nooxfBmRUUyebZug==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/rpc-transformers": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions-channel-websocket": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-channel-websocket/-/rpc-subscriptions-channel-websocket-8.6.0.tgz", + "integrity": "sha512-k1UmMiIJFeo7wAUTiqg7Ni6gdsJAd65D3Wxqdtf5iBX9TjkvWGrL3KXdJq2ZzS1c9eqd220W0v7fkFTA8tfX5Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/rpc-subscriptions-spec": "8.6.0", + "@solana/subscribable": "8.6.0", + "ws": "^8.21.3" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-subscriptions-spec": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-spec/-/rpc-subscriptions-spec-8.6.0.tgz", + "integrity": "sha512-m7lBQS9hgzWN1ZI+JUy5rV8ctG7oy0WbGHoj4vevB4esK2SYUyI0eQB4GrQhVwGnkyTxATS/R91ZZzWYDKGXlg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/subscribable": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-transformers": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-transformers/-/rpc-transformers-8.6.0.tgz", + "integrity": "sha512-aSfctQeLTszEQdNGDrPWbi/7voJYrYo/rvIZRDbokYQRDwMuphw7kENGdwaQB7A9XSX0tsPe+dKkbxjWf0Druw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-transport-http": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-transport-http/-/rpc-transport-http-8.6.0.tgz", + "integrity": "sha512-jr7ef/UOIO7bRjI7DEXji3J7nCFO3jIYPGw3L0fyF7VEJox9Bh8TNHsn9G9jv1kqdwkUnFrPPWVMvmAWQwSmvg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/rpc-spec": "8.6.0", + "@solana/rpc-spec-types": "8.6.0", + "undici-types": "^8.12.3" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/rpc-types": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/rpc-types/-/rpc-types-8.6.0.tgz", + "integrity": "sha512-gg05ZjZq8sFcf0JKO6/MQ1oYSFQuT5SU51dhirGjfl8UCxX/Q6ocsUgzb9a/zPNrRsXJkduaZF1bARah7MrrYw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/fixed-points": "8.6.0", + "@solana/nominal-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/signers": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/signers/-/signers-8.6.0.tgz", + "integrity": "sha512-q8FNQfGnMsHc7VLBhh+TwsMfodiYtYhoTqNj6lDIP2bz93l173rzcZWSRH/hg/7ksFdhHuV4nEkWj0L65N0S0Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/instruction-plans": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/offchain-messages": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/subscribable": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/subscribable/-/subscribable-8.6.0.tgz", + "integrity": "sha512-z6qRloUTxoI459dUV2K/HQZO1HYuP5f6NQxXxd25TtM2TDpnjOzoO3pJAlOZP3cwXGgtGk6UWmMEY1a4j0TILw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/errors": "8.6.0", + "@solana/promises": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/sysvars": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/sysvars/-/sysvars-8.6.0.tgz", + "integrity": "sha512-oAIVThVcZr2qDwdvc3Fx+CKCbG1d4VwwRDXbu/tDKVDUIZXDWoTP//BX0u1FimkuirMHHW9Sl+AsSGFba0KPew==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/accounts": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transaction-confirmation": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transaction-confirmation/-/transaction-confirmation-8.6.0.tgz", + "integrity": "sha512-kd7LwN1k6L+k9jXMjzm6KqGDuUsETZ1pWMnWY7ZT+1bDjRPbki/RylQc+2CIF7YYphT5GIloTmUziAAmhyw4eQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/promises": "8.6.0", + "@solana/rpc": "8.6.0", + "@solana/rpc-subscriptions": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transaction-introspection": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transaction-introspection/-/transaction-introspection-8.6.0.tgz", + "integrity": "sha512-/7MYRLnM7AF0983oaicjhvWWQEdeFgknBiKG5LVFd8WT68m5vL18d7/fZHkvsA41zWkIIrRVuh0PM4COeENNlQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0", + "@solana/transactions": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transaction-messages": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transaction-messages/-/transaction-messages-8.6.0.tgz", + "integrity": "sha512-Zb7mB8Xu+AXaNiSmgghsyliGNoi7HO4hKdyQC0Qth4hW9QOBMdjSJ687KIUwsAzDSVXwdIbsnkUPpwCl1fcMdw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/rpc-types": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@solana/transactions": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/@solana/transactions/-/transactions-8.6.0.tgz", + "integrity": "sha512-m2i0dxDtB9mGqhJd714OQpKzGFp9cQbU80kwIBFflOrHdZ2cJzZ61xjGe+vegz/WGsqPec604pUbHKXXIFkNjg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@solana/addresses": "8.6.0", + "@solana/codecs-core": "8.6.0", + "@solana/codecs-data-structures": "8.6.0", + "@solana/codecs-numbers": "8.6.0", + "@solana/codecs-strings": "8.6.0", + "@solana/errors": "8.6.0", + "@solana/functional": "8.6.0", + "@solana/instructions": "8.6.0", + "@solana/keys": "8.6.0", + "@solana/nominal-types": "8.6.0", + "@solana/rpc-types": "8.6.0", + "@solana/transaction-messages": "8.6.0" + }, + "engines": { + "node": ">=20.18.0" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/@wallet-standard/base": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@wallet-standard/base/-/base-1.1.1.tgz", + "integrity": "sha512-gggIHTtxicF9XFMQ12DkfS6NAG92Ak795JeSA7f2whAQ6Y3AkMWWuCMxSZXG2NIPN42kEaZSNVjqMsJRaJRxMQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=22" + } + }, + "node_modules/@wallet-standard/wallet": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@wallet-standard/wallet/-/wallet-1.1.0.tgz", + "integrity": "sha512-Gt8TnSlDZpAl+RWOOAB/kuvC7RpcdWAlFbHNoi4gsXsfaWa1QCT6LBcfIYTPdOZC9OVZUDwqGuGAcqZejDmHjg==", + "license": "Apache-2.0", + "dependencies": { + "@wallet-standard/base": "^1.1.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@walletconnect/core": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.9.tgz", + "integrity": "sha512-ws4WG8LeagUo2ERRo02HryXRcpwIRmCQ3pHLW5gWbVReLXXIpgk6ZAfID3fEGHevIwwnHSGww+nNhNpdXyiq0g==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/jsonrpc-ws-connection": "1.0.16", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.9", + "@walletconnect/utils": "2.23.9", + "@walletconnect/window-getters": "1.0.1", + "es-toolkit": "1.44.0", + "events": "3.3.0", + "uint8arrays": "3.1.1" + }, + "engines": { + "node": ">=18.20.8" + } + }, + "node_modules/@walletconnect/environment": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/environment/-/environment-1.0.1.tgz", + "integrity": "sha512-T426LLZtHj8e8rYnKfzsw1aG6+M0BT1ZxayMdv/p8yM0MU+eJDISqNY3/bccxRr4LrF9csq02Rhqt08Ibl0VRg==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/ethereum-provider": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/ethereum-provider/-/ethereum-provider-2.23.9.tgz", + "integrity": "sha512-Cb72KWl9S6mMs+c1MVGlSx07Dap1LFznYyWrg/XT5B8VtBKaH9Sw2lAvAL0ajGet6J5sq8sUx1pkg68tZwkqmA==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@reown/appkit": "1.8.17-wc-circular-dependencies-fix.0", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.9", + "@walletconnect/types": "2.23.9", + "@walletconnect/universal-provider": "2.23.9", + "@walletconnect/utils": "2.23.9", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/events": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/events/-/events-1.0.1.tgz", + "integrity": "sha512-NPTqaoi0oPBVNuLv7qPaJazmGHs5JGyO8eEAk5VGKmJzDR7AHzD4k6ilox5kxk1iwiOnFopBOOMLs86Oa76HpQ==", + "license": "MIT", + "dependencies": { + "keyvaluestorage-interface": "^1.0.0", + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/heartbeat": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@walletconnect/heartbeat/-/heartbeat-1.2.2.tgz", + "integrity": "sha512-uASiRmC5MwhuRuf05vq4AT48Pq8RMi876zV8rr8cV969uTOzWdB/k+Lj5yI2PBtB1bGQisGen7MM1GcZlQTBXw==", + "license": "MIT", + "dependencies": { + "@walletconnect/events": "^1.0.1", + "@walletconnect/time": "^1.0.2", + "events": "^3.3.0" + } + }, + "node_modules/@walletconnect/jsonrpc-http-connection": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-http-connection/-/jsonrpc-http-connection-1.0.8.tgz", + "integrity": "sha512-+B7cRuaxijLeFDJUq5hAzNyef3e3tBDIxyaCNmFtjwnod5AGis3RToNqzFU33vpVcxFhofkpE7Cx+5MYejbMGw==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-utils": "^1.0.6", + "@walletconnect/safe-json": "^1.0.1", + "cross-fetch": "^3.1.4", + "events": "^3.3.0" + } + }, + "node_modules/@walletconnect/jsonrpc-provider": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-provider/-/jsonrpc-provider-1.0.14.tgz", + "integrity": "sha512-rtsNY1XqHvWj0EtITNeuf8PHMvlCLiS3EjQL+WOkxEOA4KPxsohFnBDeyPYiNm4ZvkQdLnece36opYidmtbmow==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-utils": "^1.0.8", + "@walletconnect/safe-json": "^1.0.2", + "events": "^3.3.0" + } + }, + "node_modules/@walletconnect/jsonrpc-types": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-types/-/jsonrpc-types-1.0.4.tgz", + "integrity": "sha512-P6679fG/M+wuWg9TY8mh6xFSdYnFyFjwFelxyISxMDrlbXokorEVXYOxiqEbrU3x1BmBoCAJJ+vtEaEoMlpCBQ==", + "license": "MIT", + "dependencies": { + "events": "^3.3.0", + "keyvaluestorage-interface": "^1.0.0" + } + }, + "node_modules/@walletconnect/jsonrpc-utils": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-utils/-/jsonrpc-utils-1.0.8.tgz", + "integrity": "sha512-vdeb03bD8VzJUL6ZtzRYsFMq1eZQcM3EAzT0a3st59dyLfJ0wq+tKMpmGH7HlB7waD858UWgfIcudbPFsbzVdw==", + "license": "MIT", + "dependencies": { + "@walletconnect/environment": "^1.0.1", + "@walletconnect/jsonrpc-types": "^1.0.3", + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/jsonrpc-ws-connection": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-ws-connection/-/jsonrpc-ws-connection-1.0.16.tgz", + "integrity": "sha512-G81JmsMqh5nJheE1mPst1W0WfVv0SG3N7JggwLLGnI7iuDZJq8cRJvQwLGKHn5H1WTW7DEPCo00zz5w62AbL3Q==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-utils": "^1.0.6", + "@walletconnect/safe-json": "^1.0.2", + "events": "^3.3.0", + "ws": "^7.5.1" + } + }, + "node_modules/@walletconnect/jsonrpc-ws-connection/node_modules/ws": { + "version": "7.5.13", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", + "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/@walletconnect/keyvaluestorage": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@walletconnect/keyvaluestorage/-/keyvaluestorage-1.1.1.tgz", + "integrity": "sha512-V7ZQq2+mSxAq7MrRqDxanTzu2RcElfK1PfNYiaVnJgJ7Q7G7hTVwF8voIBx92qsRyGHZihrwNPHuZd1aKkd0rA==", + "license": "MIT", + "dependencies": { + "@walletconnect/safe-json": "^1.0.1", + "idb-keyval": "^6.2.1", + "unstorage": "^1.9.0" + }, + "peerDependencies": { + "@react-native-async-storage/async-storage": "1.x" + }, + "peerDependenciesMeta": { + "@react-native-async-storage/async-storage": { + "optional": true + } + } + }, + "node_modules/@walletconnect/logger": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@walletconnect/logger/-/logger-3.0.2.tgz", + "integrity": "sha512-7wR3wAwJTOmX4gbcUZcFMov8fjftY05+5cO/d4cpDD8wDzJ+cIlKdYOXaXfxHLSYeDazMXIsxMYjHYVDfkx+nA==", + "license": "MIT", + "dependencies": { + "@walletconnect/safe-json": "^1.0.2", + "pino": "10.0.0" + } + }, + "node_modules/@walletconnect/relay-api": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@walletconnect/relay-api/-/relay-api-1.0.11.tgz", + "integrity": "sha512-tLPErkze/HmC9aCmdZOhtVmYZq1wKfWTJtygQHoWtgg722Jd4homo54Cs4ak2RUFUZIGO2RsOpIcWipaua5D5Q==", + "license": "MIT", + "dependencies": { + "@walletconnect/jsonrpc-types": "^1.0.2" + } + }, + "node_modules/@walletconnect/relay-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@walletconnect/relay-auth/-/relay-auth-1.1.0.tgz", + "integrity": "sha512-qFw+a9uRz26jRCDgL7Q5TA9qYIgcNY8jpJzI1zAWNZ8i7mQjaijRnWFKsCHAU9CyGjvt6RKrRXyFtFOpWTVmCQ==", + "license": "MIT", + "dependencies": { + "@noble/curves": "1.8.0", + "@noble/hashes": "1.7.0", + "@walletconnect/safe-json": "^1.0.1", + "@walletconnect/time": "^1.0.2", + "uint8arrays": "^3.0.0" + } + }, + "node_modules/@walletconnect/relay-auth/node_modules/@noble/hashes": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.0.tgz", + "integrity": "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/safe-json": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@walletconnect/safe-json/-/safe-json-1.0.2.tgz", + "integrity": "sha512-Ogb7I27kZ3LPC3ibn8ldyUr5544t3/STow9+lzz7Sfo808YD7SBWk7SAsdBFlYgP2zDRy2hS3sKRcuSRM0OTmA==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/sign-client": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.9.tgz", + "integrity": "sha512-Xj+hw4E6mGRyhCdVOT/RMgnG+up/Y3v0ho5PlkVozvXWeVSqHNh9DmjLuU97a7OACoGd/oHBF6g3NVqD7MgCMQ==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/core": "2.23.9", + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/logger": "3.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.9", + "@walletconnect/utils": "2.23.9", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/time": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@walletconnect/time/-/time-1.0.2.tgz", + "integrity": "sha512-uzdd9woDcJ1AaBZRhqy5rNC9laqWGErfc4dxA9a87mPdKOgWMD85mcFo9dIYIts/Jwocfwn07EC6EzclKubk/g==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/types": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.9.tgz", + "integrity": "sha512-IUl1PpD/Dig8IE2OZ9XtjbPohEyOZJ73xs92EDUzoIyzRtfm36g2D340pY3iu3AAdLv1yFiaZafB8Hf8RFze8A==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/heartbeat": "1.2.2", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/universal-provider": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.9.tgz", + "integrity": "sha512-dNk6X1USUcIX1nx3H61V3pO15E/2ejyeBsKLBOo8YXrnYCrKGG/KB1LIqJXHpQlXT+9bJE9cOnn61ETdCXgkPw==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@walletconnect/events": "1.0.1", + "@walletconnect/jsonrpc-http-connection": "1.0.8", + "@walletconnect/jsonrpc-provider": "1.0.14", + "@walletconnect/jsonrpc-types": "1.0.4", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/sign-client": "2.23.9", + "@walletconnect/types": "2.23.9", + "@walletconnect/utils": "2.23.9", + "es-toolkit": "1.44.0", + "events": "3.3.0" + } + }, + "node_modules/@walletconnect/utils": { + "version": "2.23.9", + "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.9.tgz", + "integrity": "sha512-C5TltCs8UPypNiteYnKSv8+ZDK2EjVDyXCxN6kA9bkA+j6KGsNIV7l9MUA8WBAvE5Gi5EcBdhD3R9Hpo/1HHqQ==", + "license": "SEE LICENSE IN LICENSE.md", + "dependencies": { + "@msgpack/msgpack": "3.1.3", + "@noble/ciphers": "1.3.0", + "@noble/curves": "1.9.7", + "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", + "@walletconnect/jsonrpc-utils": "1.0.8", + "@walletconnect/keyvaluestorage": "1.1.1", + "@walletconnect/logger": "3.0.2", + "@walletconnect/relay-api": "1.0.11", + "@walletconnect/relay-auth": "1.1.0", + "@walletconnect/safe-json": "1.0.2", + "@walletconnect/time": "1.0.2", + "@walletconnect/types": "2.23.9", + "@walletconnect/window-getters": "1.0.1", + "@walletconnect/window-metadata": "1.0.1", + "blakejs": "1.2.1", + "detect-browser": "5.3.0", + "ox": "0.9.3", + "uint8arrays": "3.1.1" + } + }, + "node_modules/@walletconnect/utils/node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/utils/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/utils/node_modules/abitype": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", + "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/@walletconnect/utils/node_modules/ox": { + "version": "0.9.3", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", + "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.0.9", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@walletconnect/utils/node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@walletconnect/window-getters": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/window-getters/-/window-getters-1.0.1.tgz", + "integrity": "sha512-vHp+HqzGxORPAN8gY03qnbTMnhqIwjeRJNOMOAzePRg4xVEEE2WvYsI9G2NMjOknA8hnuYbU3/hwLcKbjhc8+Q==", + "license": "MIT", + "dependencies": { + "tslib": "1.14.1" + } + }, + "node_modules/@walletconnect/window-metadata": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@walletconnect/window-metadata/-/window-metadata-1.0.1.tgz", + "integrity": "sha512-9koTqyGrM2cqFRW517BPY/iEtUDx2r1+Pwwu5m7sJ7ka79wi3EyqhqcICk/yDmv6jAS1rjKgTKXlEhanYjijcA==", + "license": "MIT", + "dependencies": { + "@walletconnect/window-getters": "^1.0.1", + "tslib": "1.14.1" + } + }, + "node_modules/abitype": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.0.6.tgz", + "integrity": "sha512-MMSqYh4+C/aVqI2RQaWqbvI4Kxo5cQV40WQ4QFtDnNzCkqChm8MuENhElmynZlO0qUy/ObkEUaXtKqYnx1Kp3A==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3 >=3.22.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT", + "optional": true + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/axios": { + "version": "1.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", + "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "follow-redirects": "^1.16.2", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/axios-retry": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-4.5.0.tgz", + "integrity": "sha512-aR99oXhpEDGo0UuAlYcn2iGRds30k366Zfa05XWScR9QaQD4JYiP3/1Qt1u7YlefUOK+cn0CcwoL1oefavQUlQ==", + "deprecated": "axios-retry is no longer maintained. See https://github.com/softonic/axios-retry for alternatives.", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "is-retry-allowed": "^2.2.0" + }, + "peerDependencies": { + "axios": "0.x || 1.x" + } + }, + "node_modules/base-x": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz", + "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/big.js": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-6.2.2.tgz", + "integrity": "sha512-y/ie+Faknx7sZA5MfGA2xKlu0GDv8RWrXGsmlteyJQ2lvoKv9GBK/fpRMc2qlSoBAgNxrixICFCBefIq8WCQpQ==", + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/bigjs" + } + }, + "node_modules/blakejs": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/blakejs/-/blakejs-1.2.1.tgz", + "integrity": "sha512-QXUSXI3QVc/gJME0dBpXrag1kbzOqCjCX8/b54ntNyW6sjtoqxqRk3LTmXzaJoh71zMsDCjM+47jS7XiwN/+fQ==", + "license": "MIT" + }, + "node_modules/bs58": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", + "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", + "license": "MIT", + "dependencies": { + "base-x": "^5.0.0" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "optional": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/cookie-es": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-1.2.3.tgz", + "integrity": "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw==", + "license": "MIT" + }, + "node_modules/cross-fetch": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.2.0.tgz", + "integrity": "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.7.0" + } + }, + "node_modules/crossws": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/crossws/-/crossws-0.3.5.tgz", + "integrity": "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==", + "license": "MIT", + "dependencies": { + "uncrypto": "^0.1.3" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/dayjs": { + "version": "1.11.13", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", + "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "optional": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, + "node_modules/detect-browser": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/detect-browser/-/detect-browser-5.3.0.tgz", + "integrity": "sha512-53rsFbGdwMwlF7qvCt0ypLM5V5/Mbl0szB7GPN8y9NCcbknYOeVVXdrXEq+90IwAfrrzt6Hd+u2E2ntakICU8w==", + "license": "MIT" + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/encode-utf8": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/encode-utf8/-/encode-utf8-1.0.3.tgz", + "integrity": "sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw==", + "license": "MIT" + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "optional": true, + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-toolkit": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.44.0.tgz", + "integrity": "sha512-6penXeZalaV88MM3cGkFZZfOoLGWshWWfdy0tWw/RlVVyhvMaWSBTOvXNeiW3e5FwdS5ePW0LGEu17zT139ktg==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/esbuild": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.0", + "@esbuild/android-arm": "0.28.0", + "@esbuild/android-arm64": "0.28.0", + "@esbuild/android-x64": "0.28.0", + "@esbuild/darwin-arm64": "0.28.0", + "@esbuild/darwin-x64": "0.28.0", + "@esbuild/freebsd-arm64": "0.28.0", + "@esbuild/freebsd-x64": "0.28.0", + "@esbuild/linux-arm": "0.28.0", + "@esbuild/linux-arm64": "0.28.0", + "@esbuild/linux-ia32": "0.28.0", + "@esbuild/linux-loong64": "0.28.0", + "@esbuild/linux-mips64el": "0.28.0", + "@esbuild/linux-ppc64": "0.28.0", + "@esbuild/linux-riscv64": "0.28.0", + "@esbuild/linux-s390x": "0.28.0", + "@esbuild/linux-x64": "0.28.0", + "@esbuild/netbsd-arm64": "0.28.0", + "@esbuild/netbsd-x64": "0.28.0", + "@esbuild/openbsd-arm64": "0.28.0", + "@esbuild/openbsd-x64": "0.28.0", + "@esbuild/openharmony-arm64": "0.28.0", + "@esbuild/sunos-x64": "0.28.0", + "@esbuild/win32-arm64": "0.28.0", + "@esbuild/win32-ia32": "0.28.0", + "@esbuild/win32-x64": "0.28.0" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "optional": true, + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "optional": true, + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/h3": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.11.tgz", + "integrity": "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==", + "license": "MIT", + "dependencies": { + "cookie-es": "^1.2.3", + "crossws": "^0.3.5", + "defu": "^6.1.6", + "destr": "^2.0.5", + "iron-webcrypto": "^1.2.1", + "node-mock-http": "^1.0.4", + "radix3": "^1.1.2", + "ufo": "^1.6.3", + "uncrypto": "^0.1.3" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "optional": true, + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "optional": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/idb-keyval": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/idb-keyval/-/idb-keyval-6.2.1.tgz", + "integrity": "sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==", + "license": "Apache-2.0" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/iron-webcrypto": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz", + "integrity": "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/brc-dd" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "license": "MIT", + "optional": true + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-retry-allowed": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-2.2.0.tgz", + "integrity": "sha512-XVm7LOeLpTW4jV19QSH38vkswxoLud8sQ57YwJVTPWdiaI9I8keEhGFpBlslyVsgdQy4Opg8QOLb8YRgsyZiQg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isows": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", + "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/jose": { + "version": "6.2.17", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", + "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/keyvaluestorage-interface": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/keyvaluestorage-interface/-/keyvaluestorage-interface-1.0.0.tgz", + "integrity": "sha512-8t6Q3TclQ4uZynJY9IGr2+SsIGwK9JHcO6ootkHCGA0CrQCRy+VkouYNO2xicET6b9al7QKzpebNow+gkpCL8g==", + "license": "MIT" + }, + "node_modules/lit": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.0.tgz", + "integrity": "sha512-DGVsqsOIHBww2DqnuZzW7QsuCdahp50ojuDaBPC7jUDRpYoH0z7kHBBYZewRzer75FwtrkmkKk7iOAwSaWdBmw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit/reactive-element": "^2.1.0", + "lit-element": "^4.2.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-element": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz", + "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0", + "@lit/reactive-element": "^2.1.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-html": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz", + "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==", + "license": "BSD-3-Clause", + "dependencies": { + "@types/trusted-types": "^2.0.2" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "optional": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT", + "optional": true + }, + "node_modules/multiformats": { + "version": "9.9.0", + "resolved": "https://registry.npmjs.org/multiformats/-/multiformats-9.9.0.tgz", + "integrity": "sha512-HoMUjhH9T8DDBNT+6xzkrd9ga/XiBI4xLr58LJACwK6G3HTOPeMz4nB4KJs33L2BelrIJa7P0VuNaVF3hMYfjg==", + "license": "(Apache-2.0 AND MIT)" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "license": "MIT" + }, + "node_modules/node-mock-http": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.5.tgz", + "integrity": "sha512-KQyt/wLjG3TAc7DOUhpqWzgd4ERxR80JOlTK5VE5R1S12IaPVN5qkj4klBce9HPG1Njuup4Sb5bljaT34lIyjw==", + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ofetch": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/ofetch/-/ofetch-1.5.1.tgz", + "integrity": "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==", + "license": "MIT", + "dependencies": { + "destr": "^2.0.5", + "node-fetch-native": "^1.6.7", + "ufo": "^1.6.1" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ox": { + "version": "0.6.9", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.6.9.tgz", + "integrity": "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@adraffy/ens-normalize": "^1.10.1", + "@noble/curves": "^1.6.0", + "@noble/hashes": "^1.5.0", + "@scure/bip32": "^1.5.0", + "@scure/bip39": "^1.4.0", + "abitype": "^1.0.6", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/ox/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pino": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.0.0.tgz", + "integrity": "sha512-eI9pKwWEix40kfvSzqEP6ldqOoBIN7dwD/o91TY5z8vQI12sAffpR/pOqAD1IVVwIVHDpHjkq0joBPdJD0rafA==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "slow-redact": "^0.3.0", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/preact": { + "version": "10.24.2", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.2.tgz", + "integrity": "sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==", + "license": "MIT", + "optional": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/process-warning": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", + "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/proxy-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/proxy-compare/-/proxy-compare-3.0.1.tgz", + "integrity": "sha512-V9plBAt3qjMlS1+nC8771KNf6oJ12gExvaxnNzN/9yVRLdTv/lc+oJlnSzrdYDAvBfTStPCoiaCOTmTs0adv7Q==", + "license": "MIT" + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/radix3": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.2.tgz", + "integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, + "node_modules/slow-redact": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/slow-redact/-/slow-redact-0.3.2.tgz", + "integrity": "sha512-MseHyi2+E/hBRqdOi5COy6wZ7j7DxXRz9NkseavNYSvvWC06D8a5cidVZX3tcG5eCW3NIyVU4zT63hw0Q486jw==", + "license": "MIT" + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/thread-stream": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz", + "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "license": "MIT" + }, + "node_modules/uint8arrays": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/uint8arrays/-/uint8arrays-3.1.1.tgz", + "integrity": "sha512-+QJa8QRnbdXVpHYjLoTpJIdCTiw9Ir62nocClWuXIq2JIh4Uta0cQsTSpFL678p2CN8B+XSApwcU+pQEqVpKWg==", + "license": "MIT", + "dependencies": { + "multiformats": "^9.4.2" + } + }, + "node_modules/uncrypto": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz", + "integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.12.4.tgz", + "integrity": "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ==", + "license": "MIT", + "optional": true + }, + "node_modules/unstorage": { + "version": "1.17.6", + "resolved": "https://registry.npmjs.org/unstorage/-/unstorage-1.17.6.tgz", + "integrity": "sha512-gjKtcmn/KwZuJZO9o2sc0esAQnhmTw0LviDHwevTXbJMYs0dRTp8ZEEWXHU0vTpzbN3cA0yxlTeyXssMp3zDqw==", + "license": "MIT", + "dependencies": { + "anymatch": "^3.1.3", + "chokidar": "^5.0.0", + "destr": "^2.0.5", + "h3": "^1.15.11", + "lru-cache": "^11.5.3", + "node-fetch-native": "^1.6.7", + "ofetch": "^1.5.1", + "ufo": "^1.6.4" + }, + "peerDependencies": { + "@azure/app-configuration": "^1.8.0", + "@azure/cosmos": "^4.2.0", + "@azure/data-tables": "^13.3.0", + "@azure/identity": "^4.6.0", + "@azure/keyvault-secrets": "^4.9.0", + "@azure/storage-blob": "^12.26.0", + "@capacitor/preferences": "^6 || ^7 || ^8", + "@deno/kv": ">=0.9.0", + "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0 || ^11.0.0", + "@planetscale/database": "^1.19.0", + "@upstash/redis": "^1.34.3", + "@vercel/blob": ">=0.27.1", + "@vercel/functions": "^2.2.12 || ^3.0.0", + "@vercel/kv": "^1 || ^2 || ^3", + "aws4fetch": "^1.0.20", + "db0": ">=0.2.1", + "idb-keyval": "^6.2.1", + "ioredis": "^5.4.2", + "uploadthing": "^7.4.4" + }, + "peerDependenciesMeta": { + "@azure/app-configuration": { + "optional": true + }, + "@azure/cosmos": { + "optional": true + }, + "@azure/data-tables": { + "optional": true + }, + "@azure/identity": { + "optional": true + }, + "@azure/keyvault-secrets": { + "optional": true + }, + "@azure/storage-blob": { + "optional": true + }, + "@capacitor/preferences": { + "optional": true + }, + "@deno/kv": { + "optional": true + }, + "@netlify/blobs": { + "optional": true + }, + "@planetscale/database": { + "optional": true + }, + "@upstash/redis": { + "optional": true + }, + "@vercel/blob": { + "optional": true + }, + "@vercel/functions": { + "optional": true + }, + "@vercel/kv": { + "optional": true + }, + "aws4fetch": { + "optional": true + }, + "db0": { + "optional": true + }, + "idb-keyval": { + "optional": true + }, + "ioredis": { + "optional": true + }, + "uploadthing": { + "optional": true + } + } + }, + "node_modules/valtio": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/valtio/-/valtio-2.1.7.tgz", + "integrity": "sha512-DwJhCDpujuQuKdJ2H84VbTjEJJteaSmqsuUltsfbfdbotVfNeTE4K/qc/Wi57I9x8/2ed4JNdjEna7O6PfavRg==", + "license": "MIT", + "dependencies": { + "proxy-compare": "^3.0.1" + }, + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "react": ">=18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/viem": { + "version": "2.57.19", + "resolved": "https://registry.npmjs.org/viem/-/viem-2.57.19.tgz", + "integrity": "sha512-ULAHSwef42oL1reV41Os40iR34PF9BFNIX/RBapHLAJL1X6VmrgQikS4q4ulZ7/8GqlFLqrRI5GoNms3hcxsHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@noble/curves": "1.9.1", + "@noble/hashes": "1.8.0", + "@scure/bip32": "1.7.0", + "@scure/bip39": "1.6.0", + "abitype": "1.2.3", + "isows": "1.0.7", + "ox": "0.14.65", + "ws": "8.21.0" + }, + "peerDependencies": { + "mppx": ">=0.17.0", + "typescript": ">=5.0.4" + }, + "peerDependenciesMeta": { + "mppx": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/viem/node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/viem/node_modules/abitype": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz", + "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/ox": { + "version": "0.14.65", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.65.tgz", + "integrity": "sha512-K7oj+jvEP4Gf78ZOYuWAWzKEX/g5z7p6ukj84gdbFnezmFSt6SpprEp9tH5tymXsywSqRdeqk+8JL4+9o0Schw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.2.3", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zustand": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.3.tgz", + "integrity": "sha512-14fwWQtU3pH4dE0dOpdMiWjddcH+QzKIgk1cl8epwSE7yag43k/AD/m4L6+K7DytAOr9gGBe3/EXj9g7cdostg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + } + } +} diff --git a/scripts/walletconnect/package.json b/scripts/walletconnect/package.json new file mode 100644 index 000000000..0ed1b65a5 --- /dev/null +++ b/scripts/walletconnect/package.json @@ -0,0 +1,9 @@ +{ + "private": true, + "type": "module", + "dependencies": { + "@walletconnect/ethereum-provider": "2.23.9", + "qrcode": "1.5.4" + }, + "devDependencies": { "esbuild": "0.28.0" } +} diff --git a/scripts/walletconnect/runtime-storage.mjs b/scripts/walletconnect/runtime-storage.mjs new file mode 100644 index 000000000..ab6ba6dc9 --- /dev/null +++ b/scripts/walletconnect/runtime-storage.mjs @@ -0,0 +1,16 @@ +export function runtimeStorage(api) { + let queue = Promise.resolve(); + const update = body => { + const next = queue.then(() => api("storage", { method: "POST", body: JSON.stringify(body) })); + queue = next.catch(() => {}); + return next; + }; + const all = async () => { await queue; return api("storage"); }; + return { + async getKeys() { return Object.keys(await all()); }, + async getEntries() { return Object.entries(await all()); }, + async getItem(key) { return (await all())[key]; }, + async setItem(key, value) { await update({ key, value }); }, + async removeItem(key) { await update({ key, value: null }); }, + }; +} diff --git a/scripts/walletconnect/runtime-websocket.mjs b/scripts/walletconnect/runtime-websocket.mjs new file mode 100644 index 000000000..0dcbb69df --- /dev/null +++ b/scripts/walletconnect/runtime-websocket.mjs @@ -0,0 +1,61 @@ +// esbuild injects this WebSocket into the SDK. Every SDK socket terminates at +// Home; relay credentials and launch authority travel in the first frame. +let runtime; +export function configureRuntime(options) { + runtime = options; +} + +export class WebSocket extends EventTarget { + static CONNECTING = 0; + static OPEN = 1; + static CLOSING = 2; + static CLOSED = 3; + CONNECTING = 0; + OPEN = 1; + CLOSING = 2; + CLOSED = 3; + readyState = 0; + bufferedAmount = 0; + protocol = ""; + extensions = ""; + constructor(relay) { + super(); + if (!runtime) throw new Error("WalletConnect Runtime transport is unavailable."); + const current = runtime; + this.url = "Runtime WalletConnect relay"; + const NativeSocket = current.WebSocket || globalThis.WebSocket; + const socket = this.socket = new NativeSocket(current.url); + socket.onopen = async () => { + try { + const token = current.authorize ? (await current.authorize()).token : current.token; + if (this.readyState === 0) socket.send(JSON.stringify({ token, relay })); + } catch { this.fail(); this.close(); } + }; + socket.onmessage = event => { + if (this.readyState === 0) { + if (event.data !== '{"ready":true}') { this.close(); return; } + this.readyState = 1; + this.emit("open", new Event("open")); + } else { + this.emit("message", new MessageEvent("message", { data: event.data })); + } + }; + socket.onerror = () => this.fail(); + socket.onclose = () => { + if (this.readyState === 0) this.fail(); + this.readyState = 3; + this.emit("close", new Event("close")); + }; + } + fail() { + if (this.failed) return; + this.failed = true; + this.emit("error", new Event("error")); + } + emit(name, event) { this[`on${name}`]?.(event); this.dispatchEvent(event); } + send(data) { + if (this.readyState !== 1) throw new Error("WalletConnect connection is closed."); + this.socket.send(data); + } + close() { if (this.readyState === 0) this.fail(); this.readyState = 2; this.socket.close(); } +} From e6621f305ec8df1ec62099775150aab4743edcda Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 11:30:05 -0500 Subject: [PATCH 002/139] test(walletconnect): add opt-in Runtime real-relay acceptance --- .../api/gateway_tests/wallet/walletconnect.rs | 3 + .../wallet/walletconnect_real_relay.rs | 96 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index beec3d5e9..54632ee29 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -8,6 +8,9 @@ const STORAGE: &str = "/api/apps/wallet-walletconnect/storage"; const RELAY: &str = "wss://relay.walletconnect.org/?projectId=test_walletconnect_project&auth=fixture"; +#[path = "walletconnect_real_relay.rs"] +mod real_relay; + async fn persistent_internet(data: &std::path::Path) -> Arc { use elastos_runtime::capability::{CapabilityManager, CapabilityStore}; use elastos_runtime::primitives::{audit::AuditLog, metrics::MetricsManager}; diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs new file mode 100644 index 000000000..f18dde740 --- /dev/null +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -0,0 +1,96 @@ +//! Opt-in network acceptance. The project ID enters only through the operator file. +use super::*; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use ed25519_dalek::{Signer, SigningKey}; +use tokio::net::TcpStream; + +// Matches @walletconnect/relay-auth's locked signJWT/encodeIss implementation. +fn relay_auth() -> String { + let key = SigningKey::generate(&mut rand::rngs::OsRng); + let mut public = vec![0xed, 0x01]; + public.extend_from_slice(key.verifying_key().as_bytes()); + let issuer = format!("did:key:z{}", bs58::encode(public).into_string()); + let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","typ":"JWT"}"#); + let payload = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({ + "iss": issuer, "sub": gateway_home_token::uuid_like_token(), + "aud": "wss://relay.walletconnect.org", "iat": now_ts(), "exp": now_ts() + 300, + })) + .unwrap(), + ); + let data = format!("{header}.{payload}"); + format!("{data}.{}", URL_SAFE_NO_PAD.encode(key.sign(data.as_bytes()).to_bytes())) +} + +#[tokio::test] +#[ignore = "operator acceptance: needs ELASTOS_WALLETCONNECT_PROJECT_FILE and the real relay"] +async fn walletconnect_real_project_opens_through_runtime_and_exit() { + let file = std::env::var_os("ELASTOS_WALLETCONNECT_PROJECT_FILE") + .expect("set ELASTOS_WALLETCONNECT_PROJECT_FILE"); + let project = std::fs::read_to_string(file).expect("read operator project file"); + let project = project.trim(); + assert!(project.len() >= 8 && project.len() <= 128); + assert!(project.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')); + let mut f = Fixture::new().await; + assert!(!f.addr.ends_with(":8090")); + let config_path = f.data.path().join(WALLETCONNECT_CONFIG_PATH); + let mut config: Value = serde_json::from_slice(&std::fs::read(&config_path).unwrap()).unwrap(); + config["project_id"] = json!(project); + crate::auth::atomic_write(&config_path, &serde_json::to_vec(&config).unwrap()).unwrap(); + // Use the production root store. This Exit harness forwards raw TLS bytes; + // Runtime retains relay authentication and the HTTP/WebSocket handshake. + *f.state.walletconnect.tls.lock().unwrap() = None; + let path = f.data.path().join("real-relay.sock"); + let listener = UnixListener::bind(&path).unwrap(); + f.relay.abort(); + f.relay = tokio::spawn(async move { + let mut connections = tokio::task::JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept() => { + let (mut stream, _) = accepted.unwrap(); + connections.spawn(async move { + let mut line = Vec::new(); + loop { + let Ok(byte) = stream.read_u8().await else { return; }; + if byte == b'\n' { break; } + line.push(byte); + assert!(line.len() < 16384); + } + let open: Value = serde_json::from_slice(&line).unwrap(); + assert_eq!(open["schema"], "elastos.exit.relay-open/v1"); + assert_eq!(open["target"], "tls://relay.walletconnect.org:443"); + let Ok(Ok(mut remote)) = tokio::time::timeout( + Duration::from_secs(10), TcpStream::connect(("relay.walletconnect.org", 443)) + ).await else { return; }; + let _ = tokio::io::copy_bidirectional(&mut stream, &mut remote).await; + }); + } + result = connections.join_next(), if !connections.is_empty() => { result.unwrap().unwrap(); } + } + } + }); + let registry = f.state.provider_registry.as_ref().unwrap(); + registry.unregister_sub_provider("exit").await.unwrap(); + registry.register_sub_provider("exit", Arc::new(Exit { path, calls: f.calls.clone() })).await.unwrap(); + f.allow().await; + let mut url = url::Url::parse("wss://relay.walletconnect.org/").unwrap(); + url.query_pairs_mut().append_pair("projectId", project).append_pair("auth", &relay_auth()); + let mut socket = f.connect(&f.connector, url.as_str()).await; + let first = tokio::time::timeout(Duration::from_secs(30), socket.next()).await; + assert!(matches!(first, Ok(Some(Ok(Message::Text(ref value)))) if value == "{\"ready\":true}"), + "Runtime did not confirm the authenticated upstream WebSocket upgrade"); + // A successful relay RPC also excludes a post-upgrade authentication close. + socket.send(Message::Text(json!({ + "id": 1, "jsonrpc": "2.0", "method": "irn_subscribe", + "params": { "topic": format!("{:x}", Sha256::digest(gateway_home_token::uuid_like_token())) }, + }).to_string())).await.unwrap(); + let response = tokio::time::timeout(Duration::from_secs(15), socket.next()).await; + let Ok(Some(Ok(Message::Text(response)))) = response else { + panic!("real relay did not answer the subscription through Runtime"); + }; + let response: Value = serde_json::from_str(&response).expect("relay JSON response"); + assert!(response["id"] == 1 && response["result"].is_string(), "real relay subscription failed"); + socket.close(None).await.unwrap(); + println!("PASS: Runtime -> Exit harness -> authenticated Reown WSS upgrade and subscription; project ; ephemeral localhost port; no 401/403"); +} From 456e092fac930b3da806c10ba75a7dca52638fa7 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 11:39:37 -0500 Subject: [PATCH 003/139] fix(walletconnect): admit same-Home relay upgrades before ticket redemption --- .../src/api/gateway_frontdoor.rs | 9 ++++- .../api/gateway_tests/wallet/walletconnect.rs | 36 ++++++++++++++++--- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs b/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs index 6d931659d..056e2da78 100644 --- a/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs +++ b/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs @@ -253,6 +253,13 @@ pub(super) async fn gateway_admission( let sign_in = sign_in_route(path, method) && same_gateway_origin(headers); let ticket = read && gateway_home_terminal::admitted_terminal_ticket(path, request.uri().query()).await; + // The browser WebSocket API cannot send a launch-token header. Trusted Home + // may upgrade this one transport; its first frame must redeem the short-lived + // admission issued through the separately authenticated Home route. + let walletconnect_transport = method == Method::GET + && path == "/api/apps/wallet-walletconnect/relay" + && origin.is_some_and(|origin| origin != "null") + && same_gateway_origin(headers); let runtime_session = runtime_operator_route(path, method) && headers.contains_key("authorization") && !headers.contains_key("origin") @@ -272,7 +279,7 @@ pub(super) async fn gateway_admission( // or lost its session. Another app's token stays the generic refusal, and // so does every other route. let mut browser_launch_renewal = None; - if !public && !sign_in && !ticket && !runtime_session { + if !public && !sign_in && !ticket && !walletconnect_transport && !runtime_session { match gateway_home_token::require_gateway_launch(&state.data_dir, headers) { Ok(()) => {} Err(_) if browser_api_path(path) => { diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 54632ee29..e5ef05d82 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -1,7 +1,7 @@ use super::super::*; use futures_util::{SinkExt, StreamExt}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use tokio_tungstenite::{connect_async, tungstenite::Message}; +use tokio_tungstenite::{connect_async, tungstenite::{client::IntoClientRequest, Message}}; const INTERNET: &str = "/api/apps/wallet-walletconnect/internet"; const STORAGE: &str = "/api/apps/wallet-walletconnect/storage"; @@ -287,10 +287,12 @@ impl Fixture { relay: &str, ) -> tokio_tungstenite::WebSocketStream> { - let (mut socket, _) = connect_async(format!( + let mut request = format!( "ws://{}/api/apps/wallet-walletconnect/relay", self.addr - )) + ).into_client_request().unwrap(); + request.headers_mut().insert("origin", format!("http://{}", self.addr).parse().unwrap()); + let (mut socket, _) = connect_async(request) .await .unwrap(); socket @@ -318,6 +320,25 @@ impl Fixture { } } +#[tokio::test] +async fn walletconnect_websocket_upgrade_requires_same_home_origin_and_first_frame_admission() { + let f = Fixture::new().await; + for origin in [None, Some("null"), Some("https://other.example")] { + let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) + .into_client_request().unwrap(); + if let Some(origin) = origin { + request.headers_mut().insert("origin", origin.parse().unwrap()); + } + let result = connect_async(request).await; + assert!(matches!(result, Err(tokio_tungstenite::tungstenite::Error::Http(ref response)) if response.status() == StatusCode::FORBIDDEN)); + } + // This matches the browser API: same-Home Origin, no custom auth header, + // and a refused first-frame ticket. Upgrading grants no Exit access. + let mut socket = f.connect_ticket("refused", RELAY).await; + assert!(matches!(socket.next().await, Some(Ok(Message::Close(_))) | None)); + assert_eq!(f.calls.load(Ordering::SeqCst), 0); +} + #[tokio::test] async fn walletconnect_real_relay_requires_consent_allowlist_and_connector() { let f = Fixture::new().await; @@ -390,7 +411,10 @@ async fn walletconnect_storage_is_principal_scoped_and_survives_service_restart( assert_eq!(status, StatusCode::OK); let (status, _) = f.route(&f.inbox, STORAGE, None).await; assert_ne!(status, StatusCode::OK); - let other = passkey_authority_with_name(f.data.path(), Some("other-wc")); + let other = passkey_authority_with_name_role_credential( + f.data.path(), Some("other-wc"), crate::auth::RuntimePrincipalRole::Admin, "other-wc-credential", + ); + assert_ne!(other.principal_id, runtime_wallet_authority_for_app_token(f.data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &f.connector).home_launch_context().principal_id); let token = projection_launch_token_for_authority_context( f.data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, @@ -550,7 +574,9 @@ async fn walletconnect_refuses_malformed_writes_and_cross_principal_host_authori } let (_, stored) = f.route(&f.connector, STORAGE, None).await; assert_eq!(stored, json!({})); - let other = passkey_authority_with_name(f.data.path(), Some("different-host")); + let other = passkey_authority_with_name_role_credential( + f.data.path(), Some("different-host"), crate::auth::RuntimePrincipalRole::Admin, "different-host-credential", + ); for path in [ STORAGE, "/api/apps/wallet-walletconnect/relay-admission", From 9374aea0d569eea0d82e8f3d9de885fedefbbf62 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 11:53:53 -0500 Subject: [PATCH 004/139] fix(walletconnect): return typed wallet-link denials and align Home CSP proof --- .../elastos-server/src/api/auth_gateway.rs | 20 ++++++++++++++++++- .../src/api/gateway_tests/content_sandbox.rs | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 89a165a06..aebab491f 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -3599,12 +3599,23 @@ pub(in crate::api) struct WalletLinkContext { authority: RuntimeWalletAuthority, } +#[derive(Debug)] +struct WalletConnectorBridgeRequired; + +impl std::fmt::Display for WalletConnectorBridgeRequired { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("Wallet linking requires the trusted Home wallet connector bridge") + } +} + +impl std::error::Error for WalletConnectorBridgeRequired {} + fn require_wallet_link_context( state: &GatewayState, headers: &HeaderMap, ) -> anyhow::Result { let _ = (state, headers); - anyhow::bail!("Wallet linking requires the trusted Home wallet connector bridge") + Err(WalletConnectorBridgeRequired.into()) } pub(in crate::api) fn verified_wallet_link_context( @@ -4786,6 +4797,7 @@ pub(in crate::api) fn auth_error_response(err: anyhow::Error) -> Response { let text = err.to_string(); let status = if err.is::() || err.is::() + || err.is::() || text.contains("missing") || text.contains("invalid") || text.contains("expired") @@ -6631,6 +6643,12 @@ mod tests { ); } + #[test] + fn wallet_connector_bridge_refusal_is_typed_even_with_context() { + let error = anyhow::Error::new(WalletConnectorBridgeRequired).context("wallet link refused"); + assert_eq!(auth_error_response(error).status(), StatusCode::FORBIDDEN); + } + #[test] fn registration_denial_is_typed_even_with_context() { for error in [ diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index 86066ecd0..4686638fb 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -289,7 +289,7 @@ async fn content_sandbox_site_files_and_admitted_bundle_preserve_provenance() { .unwrap(); assert_eq!(home.status(), StatusCode::OK); assert_eq!(home.headers().get("content-security-policy").unwrap(), - "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self'; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"); + "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' ws://localhost:61180; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"); let health = app .oneshot( Request::builder() From 21829350e53d55d073a700998bcb6557d700daf2 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 11:57:58 -0500 Subject: [PATCH 005/139] build(walletconnect): rebuild pinned Runtime adapter and source provenance --- .../wallet-walletconnect/vendor/adapter.json | 10 +- .../vendor/reown-appkit.js | 102 +++++++++--------- 2 files changed, 59 insertions(+), 53 deletions(-) diff --git a/capsules/wallet-walletconnect/vendor/adapter.json b/capsules/wallet-walletconnect/vendor/adapter.json index 94035ff70..394fbe2a6 100644 --- a/capsules/wallet-walletconnect/vendor/adapter.json +++ b/capsules/wallet-walletconnect/vendor/adapter.json @@ -1,6 +1,12 @@ { "sdk_package": "@walletconnect/ethereum-provider", "sdk_version": "2.23.9", - "sdk_sha256": "2d49248cf55d0f7f6a37ca3836d28681384a23be32ac3e9158f98619cbd84dc7", - "dependency_lock_sha256": "a12af83d3f92729c8bf06ff21505973a68c01d9fe08e157d837adc6c4b08833d" + "sdk_sha256": "6cff318e63fa0b8c9cc7ee95ce92d5a5470df6cd742a8ad8c2033ce829bb1895", + "dependency_lock_sha256": "a12af83d3f92729c8bf06ff21505973a68c01d9fe08e157d837adc6c4b08833d", + "source_sha256": { + "adapter.mjs": "8365b7d00728a0242f3065f39bfc43d8cff192587b2b9a05036d029b3f22e7af", + "runtime-storage.mjs": "3e3d746baf073b0b0704b97a2bd7cdc67931fdb13ea08578d5c3ad4b2c7a81d0", + "runtime-websocket.mjs": "69912984aa26ddc315871695b5f19c136aec254e1e846554d5609de83c3d3121", + "../vendor-walletconnect-adapter.sh": "ea02a352688ec39ddf818ac29e8473a8225e414ea7fc62f142b589c0a3cea1d7" + } } diff --git a/capsules/wallet-walletconnect/vendor/reown-appkit.js b/capsules/wallet-walletconnect/vendor/reown-appkit.js index 952929045..be8f896d7 100644 --- a/capsules/wallet-walletconnect/vendor/reown-appkit.js +++ b/capsules/wallet-walletconnect/vendor/reown-appkit.js @@ -1,4 +1,4 @@ -var PCe=Object.create;var nA=Object.defineProperty;var NCe=Object.getOwnPropertyDescriptor;var RCe=Object.getOwnPropertyNames;var OCe=Object.getPrototypeOf,BCe=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Te=(e,t)=>{for(var r in t)nA(e,r,{get:t[r],enumerable:!0})},rA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of RCe(t))!BCe.call(e,o)&&o!==r&&nA(e,o,{get:()=>t[o],enumerable:!(n=NCe(t,o))||n.enumerable});return e},Bo=(e,t,r)=>(rA(e,t,"default"),r&&rA(r,t,"default")),Ht=(e,t,r)=>(r=e!=null?PCe(OCe(e)):{},rA(t||!e||!e.__esModule?nA(r,"default",{value:e,enumerable:!0}):r,e)),Yx=e=>rA(nA({},"__esModule",{value:!0}),e);function g(e){zN=e}var zN,m,l=b(()=>{m=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;readyState=0;bufferedAmount=0;protocol="";extensions="";constructor(t){if(super(),!zN)throw new Error("WalletConnect Runtime transport is unavailable.");let r=zN;this.url="Runtime WalletConnect relay";let n=r.WebSocket||globalThis.WebSocket,o=this.socket=new n(r.url);o.onopen=async()=>{try{let s=r.authorize?(await r.authorize()).token:r.token;this.readyState===0&&o.send(JSON.stringify({token:s,relay:t}))}catch{this.close()}},o.onmessage=s=>{if(this.readyState===0){if(s.data!=='{"ready":true}'){this.close();return}this.readyState=1,this.emit("open",new Event("open"))}else this.emit("message",new MessageEvent("message",{data:s.data}))},o.onerror=()=>this.emit("error",new Event("error")),o.onclose=()=>{this.readyState=3,this.emit("close",new Event("close"))}}emit(t,r){this[`on${t}`]?.(r),this.dispatchEvent(r)}send(t){if(this.readyState!==1)throw new Error("WalletConnect connection is closed.");this.socket.send(t)}close(){this.readyState=2,this.socket.close()}}});var ks=_e((ent,VN)=>{"use strict";l();var y2=typeof Reflect=="object"?Reflect:null,uW=y2&&typeof y2.apply=="function"?y2.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},oA;y2&&typeof y2.ownKeys=="function"?oA=y2.ownKeys:Object.getOwnPropertySymbols?oA=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:oA=function(t){return Object.getOwnPropertyNames(t)};function kCe(e){console&&console.warn&&console.warn(e)}var fW=Number.isNaN||function(t){return t!==t};function Ar(){Ar.init.call(this)}VN.exports=Ar;VN.exports.once=MCe;Ar.EventEmitter=Ar;Ar.prototype._events=void 0;Ar.prototype._eventsCount=0;Ar.prototype._maxListeners=void 0;var dW=10;function sA(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(Ar,"defaultMaxListeners",{enumerable:!0,get:function(){return dW},set:function(e){if(typeof e!="number"||e<0||fW(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");dW=e}});Ar.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Ar.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||fW(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function pW(e){return e._maxListeners===void 0?Ar.defaultMaxListeners:e._maxListeners}Ar.prototype.getMaxListeners=function(){return pW(this)};Ar.prototype.emit=function(t){for(var r=[],n=1;n0&&(i=r[0]),i instanceof Error)throw i;var a=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw a.context=i,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")uW(c,this,r);else for(var u=c.length,d=wW(c,u),n=0;n0&&i.length>o&&!i.warned){i.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=i.length,kCe(a)}return e}Ar.prototype.addListener=function(t,r){return hW(this,t,r,!1)};Ar.prototype.on=Ar.prototype.addListener;Ar.prototype.prependListener=function(t,r){return hW(this,t,r,!0)};function UCe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function mW(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=UCe.bind(n);return o.listener=r,n.wrapFn=o,o}Ar.prototype.once=function(t,r){return sA(r),this.on(t,mW(this,t,r)),this};Ar.prototype.prependOnceListener=function(t,r){return sA(r),this.prependListener(t,mW(this,t,r)),this};Ar.prototype.removeListener=function(t,r){var n,o,s,i,a;if(sA(r),o=this._events,o===void 0)return this;if(n=o[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(s=-1,i=n.length-1;i>=0;i--)if(n[i]===r||n[i].listener===r){a=n[i].listener,s=i;break}if(s<0)return this;s===0?n.shift():DCe(n,s),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,a||r)}return this};Ar.prototype.off=Ar.prototype.removeListener;Ar.prototype.removeAllListeners=function(t){var r,n,o;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),i;for(o=0;o=0;o--)this.removeListener(t,r[o]);return this};function gW(e,t,r){var n=e._events;if(n===void 0)return[];var o=n[t];return o===void 0?[]:typeof o=="function"?r?[o.listener||o]:[o]:r?LCe(o):wW(o,o.length)}Ar.prototype.listeners=function(t){return gW(this,t,!0)};Ar.prototype.rawListeners=function(t){return gW(this,t,!1)};Ar.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):yW.call(e,t)};Ar.prototype.listenerCount=yW;function yW(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ar.prototype.eventNames=function(){return this._eventsCount>0?oA(this._events):[]};function wW(e,t){for(var r=new Array(t),n=0;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new jCe:typeof navigator<"u"?AW(navigator.userAgent):YCe()}function ZCe(e){return e!==""&&KCe.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var s=o.exec(e);return!!s&&[n,s]},!1)}function AW(e){var t=ZCe(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new VCe;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length{l();xW=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;nWN,__asyncDelegator:()=>uSe,__asyncGenerator:()=>lSe,__asyncValues:()=>dSe,__await:()=>Jx,__awaiter:()=>nSe,__classPrivateFieldGet:()=>mSe,__classPrivateFieldSet:()=>gSe,__createBinding:()=>sSe,__decorate:()=>eSe,__exportStar:()=>iSe,__extends:()=>QCe,__generator:()=>oSe,__importDefault:()=>hSe,__importStar:()=>pSe,__makeTemplateObject:()=>fSe,__metadata:()=>rSe,__param:()=>tSe,__read:()=>CW,__rest:()=>XCe,__spread:()=>aSe,__spreadArrays:()=>cSe,__values:()=>KN});function QCe(e,t){qN(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function XCe(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(e);o=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s}function tSe(e,t){return function(r,n){t(r,n,e)}}function rSe(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function nSe(e,t,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(d){try{u(n.next(d))}catch(f){i(f)}}function c(d){try{u(n.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(a,c)}u((n=n.apply(e,t||[])).next())})}function oSe(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(d){return c([u,d])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function CW(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function aSe(){for(var e=[],t=0;t1||a(p,h)})})}function a(p,h){try{c(n[p](h))}catch(y){f(s[0][3],y)}}function c(p){p.value instanceof Jx?Promise.resolve(p.value.v).then(u,d):f(s[0][2],p)}function u(p){a("next",p)}function d(p){a("throw",p)}function f(p,h){p(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function uSe(e){var t,r;return t={},n("next"),n("throw",function(o){throw o}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(o,s){t[o]=e[o]?function(i){return(r=!r)?{value:Jx(e[o](i)),done:o==="return"}:s?s(i):i}:s}}function dSe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof KN=="function"?KN(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=e[s]&&function(i){return new Promise(function(a,c){i=e[s](i),o(a,c,i.done,i.value)})}}function o(s,i,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},i)}}function fSe(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function pSe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function hSe(e){return e&&e.__esModule?e:{default:e}}function mSe(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function gSe(e,t,r){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,r),r}var qN,WN,b2=b(()=>{l();qN=function(e,t){return qN=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},qN(e,t)};WN=function(){return WN=Object.assign||function(t){for(var r,n=1,o=arguments.length;n{"use strict";l();Object.defineProperty(aA,"__esModule",{value:!0});aA.delay=void 0;function ySe(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}aA.delay=ySe});var IW=_e(x2=>{"use strict";l();Object.defineProperty(x2,"__esModule",{value:!0});x2.ONE_THOUSAND=x2.ONE_HUNDRED=void 0;x2.ONE_HUNDRED=100;x2.ONE_THOUSAND=1e3});var TW=_e(Ue=>{"use strict";l();Object.defineProperty(Ue,"__esModule",{value:!0});Ue.ONE_YEAR=Ue.FOUR_WEEKS=Ue.THREE_WEEKS=Ue.TWO_WEEKS=Ue.ONE_WEEK=Ue.THIRTY_DAYS=Ue.SEVEN_DAYS=Ue.FIVE_DAYS=Ue.THREE_DAYS=Ue.ONE_DAY=Ue.TWENTY_FOUR_HOURS=Ue.TWELVE_HOURS=Ue.SIX_HOURS=Ue.THREE_HOURS=Ue.ONE_HOUR=Ue.SIXTY_MINUTES=Ue.THIRTY_MINUTES=Ue.TEN_MINUTES=Ue.FIVE_MINUTES=Ue.ONE_MINUTE=Ue.SIXTY_SECONDS=Ue.THIRTY_SECONDS=Ue.TEN_SECONDS=Ue.FIVE_SECONDS=Ue.ONE_SECOND=void 0;Ue.ONE_SECOND=1;Ue.FIVE_SECONDS=5;Ue.TEN_SECONDS=10;Ue.THIRTY_SECONDS=30;Ue.SIXTY_SECONDS=60;Ue.ONE_MINUTE=Ue.SIXTY_SECONDS;Ue.FIVE_MINUTES=Ue.ONE_MINUTE*5;Ue.TEN_MINUTES=Ue.ONE_MINUTE*10;Ue.THIRTY_MINUTES=Ue.ONE_MINUTE*30;Ue.SIXTY_MINUTES=Ue.ONE_MINUTE*60;Ue.ONE_HOUR=Ue.SIXTY_MINUTES;Ue.THREE_HOURS=Ue.ONE_HOUR*3;Ue.SIX_HOURS=Ue.ONE_HOUR*6;Ue.TWELVE_HOURS=Ue.ONE_HOUR*12;Ue.TWENTY_FOUR_HOURS=Ue.ONE_HOUR*24;Ue.ONE_DAY=Ue.TWENTY_FOUR_HOURS;Ue.THREE_DAYS=Ue.ONE_DAY*3;Ue.FIVE_DAYS=Ue.ONE_DAY*5;Ue.SEVEN_DAYS=Ue.ONE_DAY*7;Ue.THIRTY_DAYS=Ue.ONE_DAY*30;Ue.ONE_WEEK=Ue.SEVEN_DAYS;Ue.TWO_WEEKS=Ue.ONE_WEEK*2;Ue.THREE_WEEKS=Ue.ONE_WEEK*3;Ue.FOUR_WEEKS=Ue.ONE_WEEK*4;Ue.ONE_YEAR=Ue.ONE_DAY*365});var ZN=_e(cA=>{"use strict";l();Object.defineProperty(cA,"__esModule",{value:!0});var _W=(b2(),Yx(w2));_W.__exportStar(IW(),cA);_W.__exportStar(TW(),cA)});var NW=_e(v2=>{"use strict";l();Object.defineProperty(v2,"__esModule",{value:!0});v2.fromMiliseconds=v2.toMiliseconds=void 0;var PW=ZN();function wSe(e){return e*PW.ONE_THOUSAND}v2.toMiliseconds=wSe;function bSe(e){return Math.floor(e/PW.ONE_THOUSAND)}v2.fromMiliseconds=bSe});var OW=_e(lA=>{"use strict";l();Object.defineProperty(lA,"__esModule",{value:!0});var RW=(b2(),Yx(w2));RW.__exportStar(SW(),lA);RW.__exportStar(NW(),lA)});var BW=_e(Qx=>{"use strict";l();Object.defineProperty(Qx,"__esModule",{value:!0});Qx.Watch=void 0;var uA=class{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){let r=this.get(t);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);let n=Date.now()-r.started;this.timestamps.set(t,{started:r.started,elapsed:n})}get(t){let r=this.timestamps.get(t);if(typeof r>"u")throw new Error(`No timestamp found for label: ${t}`);return r}elapsed(t){let r=this.get(t);return r.elapsed||Date.now()-r.started}};Qx.Watch=uA;Qx.default=uA});var kW=_e(dA=>{"use strict";l();Object.defineProperty(dA,"__esModule",{value:!0});dA.IWatch=void 0;var GN=class{};dA.IWatch=GN});var UW=_e(YN=>{"use strict";l();Object.defineProperty(YN,"__esModule",{value:!0});var xSe=(b2(),Yx(w2));xSe.__exportStar(kW(),YN)});var jd=_e(E2=>{"use strict";l();Object.defineProperty(E2,"__esModule",{value:!0});var fA=(b2(),Yx(w2));fA.__exportStar(OW(),E2);fA.__exportStar(BW(),E2);fA.__exportStar(UW(),E2);fA.__exportStar(ZN(),E2)});var C2=_e(Ur=>{"use strict";l();Object.defineProperty(Ur,"__esModule",{value:!0});Ur.getLocalStorage=Ur.getLocalStorageOrThrow=Ur.getCrypto=Ur.getCryptoOrThrow=Ur.getLocation=Ur.getLocationOrThrow=Ur.getNavigator=Ur.getNavigatorOrThrow=Ur.getDocument=Ur.getDocumentOrThrow=Ur.getFromWindowOrThrow=Ur.getFromWindow=void 0;function l1(e){let t;return typeof window<"u"&&typeof window[e]<"u"&&(t=window[e]),t}Ur.getFromWindow=l1;function A2(e){let t=l1(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Ur.getFromWindowOrThrow=A2;function vSe(){return A2("document")}Ur.getDocumentOrThrow=vSe;function ESe(){return l1("document")}Ur.getDocument=ESe;function ASe(){return A2("navigator")}Ur.getNavigatorOrThrow=ASe;function CSe(){return l1("navigator")}Ur.getNavigator=CSe;function SSe(){return A2("location")}Ur.getLocationOrThrow=SSe;function ISe(){return l1("location")}Ur.getLocation=ISe;function TSe(){return A2("crypto")}Ur.getCryptoOrThrow=TSe;function _Se(){return l1("crypto")}Ur.getCrypto=_Se;function PSe(){return A2("localStorage")}Ur.getLocalStorageOrThrow=PSe;function NSe(){return l1("localStorage")}Ur.getLocalStorage=NSe});var JN=_e(pA=>{"use strict";l();Object.defineProperty(pA,"__esModule",{value:!0});pA.getWindowMetadata=void 0;var DW=C2();function RSe(){let e,t;try{e=DW.getDocumentOrThrow(),t=DW.getLocationOrThrow()}catch{return null}function r(){let f=e.getElementsByTagName("link"),p=[];for(let h=0;h-1){let x=y.getAttribute("href");if(x)if(x.toLowerCase().indexOf("https:")===-1&&x.toLowerCase().indexOf("http:")===-1&&x.indexOf("//")!==0){let v=t.protocol+"//"+t.host;if(x.indexOf("/")===0)v+=x;else{let T=t.pathname.split("/");T.pop();let E=T.join("/");v+=E+"/"+x}p.push(v)}else if(x.indexOf("//")===0){let v=t.protocol+x;p.push(v)}else p.push(x)}}return p}function n(...f){let p=e.getElementsByTagName("meta");for(let h=0;hy.getAttribute(x)).filter(x=>x?f.includes(x):!1);if(w.length&&w){let x=y.getAttribute("content");if(x)return x}}return""}function o(){let f=n("name","og:site_name","og:title","twitter:title");return f||(f=e.title),f}function s(){return n("description","og:description","twitter:description","keywords")}let i=o(),a=s(),c=t.origin,u=r();return{description:a,url:c,icons:u,name:i}}pA.getWindowMetadata=RSe});var UIe,DIe,LIe,MIe,uZ,dZ,fZ,HIe,$Ie,Qit,Xit,eat,tat,pZ=b(()=>{l();UIe=44032,DIe=4352,LIe=4449,MIe=4519,uZ=19,dZ=21,fZ=28,HIe=dZ*fZ,$Ie=uZ*HIe,Qit=UIe+$Ie,Xit=DIe+uZ,eat=LIe+dZ,tat=MIe+fZ});function gZ(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function yZ(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(r=>typeof r=="string"):t.every(r=>Number.isSafeInteger(r)):!1}function VA(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function p8(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function jA(e){if(!Array.isArray(e))throw new Error("array expected")}function qA(e,t){if(!yZ(!0,t))throw new Error(`${e}: array of strings expected`)}function wZ(e,t){if(!yZ(!1,t))throw new Error(`${e}: array of numbers expected`)}function bZ(...e){let t=s=>s,r=(s,i)=>a=>s(i(a)),n=e.map(s=>s.encode).reduceRight(r,t),o=e.map(s=>s.decode).reduce(r,t);return{encode:n,decode:o}}function xZ(e){let t=typeof e=="string"?e.split(""):e,r=t.length;qA("alphabet",t);let n=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(jA(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:o=>(jA(o),o.map(s=>{VA("alphabet.decode",s);let i=n.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function vZ(e=""){return VA("join",e),{encode:t=>(qA("join.decode",t),t.join(e)),decode:t=>(VA("join.decode",t),t.split(e))}}function FIe(e,t="="){return p8(e),VA("padding",t),{encode(r){for(qA("padding.encode",r);r.length*e%8;)r.push(t);return r},decode(r){qA("padding.decode",r);let n=r.length;if(n*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if((n-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}function hZ(e,t,r){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(jA(e),!e.length)return[];let n=0,o=[],s=Array.from(e,a=>{if(p8(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),i=s.length;for(;;){let a=0,c=!0;for(let u=n;u32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(WA(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${WA(t,r)}`);let o=0,s=0,i=YR[t],a=YR[r]-1,c=[];for(let u of e){if(p8(u),u>=i)throw new Error(`convertRadix2: invalid data word=${u} from=${t}`);if(o=o<32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=r;s-=r)c.push((o>>s-r&a)>>>0);let d=YR[s];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<=t)throw new Error("Excess padding");if(!n&&o>0)throw new Error(`Non-zero padding: ${o}`);return n&&s>0&&c.push(o>>>0),c}function zIe(e){p8(e);let t=2**8;return{encode:r=>{if(!gZ(r))throw new Error("radix.encode input should be Uint8Array");return hZ(Array.from(r),t,e)},decode:r=>(wZ("radix.decode",r),Uint8Array.from(hZ(r,e,t)))}}function VIe(e,t=!1){if(p8(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(WA(8,e)>32||WA(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!gZ(r))throw new Error("radix2.encode input should be Uint8Array");return mZ(Array.from(r),8,e,!t)},decode:r=>(wZ("radix2.decode",r),Uint8Array.from(mZ(r,e,8,t)))}}var EZ,WA,YR,KA,jIe,B2,JR=b(()=>{l();EZ=(e,t)=>t===0?e:EZ(t,e%t),WA=(e,t)=>e+(t-EZ(e,t)),YR=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();KA=bZ(VIe(5),xZ("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),FIe(5),vZ("")),jIe=e=>bZ(zIe(58),xZ(e),vZ("")),B2=jIe("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")});function PZ(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function GA(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function YA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function rs(e,...t){if(!PZ(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function QR(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function NZ(e,t){rs(e);let r=t.outputLen;if(e.length>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function BZ(e,t,r){GA(r);let n=new Uint8Array(16),o=JIe(n);return _Z(o,0,BigInt(t),r),_Z(o,8,BigInt(e),r),n}function e9e(e){return e.byteOffset%4===0}function QA(e){return Uint8Array.from(e)}var QIe,XR,XA=b(()=>{l();QIe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;XR=(e,t)=>{function r(n,...o){if(rs(n),!QIe)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let d=o[0];if(!d)throw new Error("nonce / iv required");e.varSizeNonce?rs(d):rs(d,e.nonceLength)}let s=e.tagLength;s&&o[1]!==void 0&&rs(o[1]);let i=t(n,...o),a=(d,f)=>{if(f!==void 0){if(d!==2)throw new Error("cipher output not supported");rs(f)}},c=!1;return{encrypt(d,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,rs(d),a(i.encrypt.length,f),i.encrypt(d,f)},decrypt(d,f){if(rs(d),s&&d.length{l();LZ=Ht(DZ(),1)});var KZ=b(()=>{l()});function I1(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}var b8=b(()=>{l()});function x8(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?I1(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}var aC=b(()=>{l();b8()});function Ms(e,t){t||(t=e.reduce((o,s)=>o+s.length,0));let r=x8(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return I1(r)}var ZZ=b(()=>{l();aC();b8()});var GZ=b(()=>{l()});function T9e(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}var _9e,P9e,YZ,JZ=b(()=>{l();_9e=T9e,P9e=_9e,YZ=P9e});var Rlt,QZ,rf,XZ,eG,rh=b(()=>{l();Rlt=new Uint8Array(0),QZ=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},XZ=e=>new TextEncoder().encode(e),eG=e=>new TextDecoder().decode(e)});var cO,lO,uO,rG,dO,U2,nh,N9e,R9e,mn,Bc=b(()=>{l();JZ();rh();cO=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},lO=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return rG(this,t)}},uO=class{constructor(t){this.decoders=t}or(t){return rG(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},rG=(e,t)=>new uO({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),dO=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new cO(t,r,n),this.decoder=new lO(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},U2=({name:e,prefix:t,encode:r,decode:n})=>new dO(e,t,r,n),nh=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=YZ(r,t);return U2({prefix:e,name:t,encode:n,decode:s=>rf(o(s))})},N9e=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},R9e=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<U2({prefix:t,name:e,encode(o){return R9e(o,n,r)},decode(o){return N9e(o,n,r,e)}})});var fO={};Te(fO,{identity:()=>O9e});var O9e,nG=b(()=>{l();Bc();rh();O9e=U2({prefix:"\0",name:"identity",encode:e=>eG(e),decode:e=>XZ(e)})});var pO={};Te(pO,{base2:()=>B9e});var B9e,oG=b(()=>{l();Bc();B9e=mn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var hO={};Te(hO,{base8:()=>k9e});var k9e,sG=b(()=>{l();Bc();k9e=mn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var mO={};Te(mO,{base10:()=>U9e});var U9e,iG=b(()=>{l();Bc();U9e=nh({prefix:"9",name:"base10",alphabet:"0123456789"})});var gO={};Te(gO,{base16:()=>D9e,base16upper:()=>L9e});var D9e,L9e,aG=b(()=>{l();Bc();D9e=mn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L9e=mn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var yO={};Te(yO,{base32:()=>D2,base32hex:()=>F9e,base32hexpad:()=>V9e,base32hexpadupper:()=>j9e,base32hexupper:()=>z9e,base32pad:()=>H9e,base32padupper:()=>$9e,base32upper:()=>M9e,base32z:()=>q9e});var D2,M9e,H9e,$9e,F9e,z9e,V9e,j9e,q9e,wO=b(()=>{l();Bc();D2=mn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),M9e=mn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),H9e=mn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$9e=mn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),F9e=mn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z9e=mn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),V9e=mn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),j9e=mn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),q9e=mn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bO={};Te(bO,{base36:()=>W9e,base36upper:()=>K9e});var W9e,K9e,cG=b(()=>{l();Bc();W9e=nh({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),K9e=nh({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var xO={};Te(xO,{base58btc:()=>Dl,base58flickr:()=>Z9e});var Dl,Z9e,vO=b(()=>{l();Bc();Dl=nh({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Z9e=nh({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var EO={};Te(EO,{base64:()=>G9e,base64pad:()=>Y9e,base64url:()=>J9e,base64urlpad:()=>Q9e});var G9e,Y9e,J9e,Q9e,lG=b(()=>{l();Bc();G9e=mn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Y9e=mn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J9e=mn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Q9e=mn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var AO={};Te(AO,{base256emoji:()=>nTe});function tTe(e){return e.reduce((t,r)=>(t+=X9e[r],t),"")}function rTe(e){let t=[];for(let r of e){let n=eTe[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}var uG,X9e,eTe,nTe,dG=b(()=>{l();Bc();uG=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),X9e=uG.reduce((e,t,r)=>(e[r]=t,e),[]),eTe=uG.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);nTe=U2({prefix:"\u{1F680}",name:"base256emoji",encode:tTe,decode:rTe})});function hG(e,t,r){t=t||[],r=r||0;for(var n=r;e>=aTe;)t[r++]=e&255|fG,e/=128;for(;e&iTe;)t[r++]=e&255|fG,e>>>=7;return t[r]=e|0,hG.bytes=r-n+1,t}function CO(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw CO.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&pG)<=lTe);return CO.bytes=s-n,r}var oTe,fG,sTe,iTe,aTe,cTe,lTe,pG,uTe,dTe,fTe,pTe,hTe,mTe,gTe,yTe,wTe,bTe,xTe,vTe,v8,mG=b(()=>{l();oTe=hG,fG=128,sTe=127,iTe=~sTe,aTe=Math.pow(2,31);cTe=CO,lTe=128,pG=127;uTe=Math.pow(2,7),dTe=Math.pow(2,14),fTe=Math.pow(2,21),pTe=Math.pow(2,28),hTe=Math.pow(2,35),mTe=Math.pow(2,42),gTe=Math.pow(2,49),yTe=Math.pow(2,56),wTe=Math.pow(2,63),bTe=function(e){return e{l();mG();E8=(e,t=0)=>[v8.decode(e,t),v8.decode.bytes],L2=(e,t,r=0)=>(v8.encode(e,t,r),t),M2=e=>v8.encodingLength(e)});var T1,gG,yG,H2,C8=b(()=>{l();rh();lC();T1=(e,t)=>{let r=t.byteLength,n=M2(e),o=n+M2(r),s=new Uint8Array(o+r);return L2(e,s,0),L2(r,s,n),s.set(t,o),new H2(e,r,t,s)},gG=e=>{let t=rf(e),[r,n]=E8(t),[o,s]=E8(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new H2(r,o,i,t)},yG=(e,t)=>e===t?!0:e.code===t.code&&e.size===t.size&&QZ(e.bytes,t.bytes),H2=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}});var IO,SO,TO=b(()=>{l();C8();IO=({name:e,code:t,encode:r})=>new SO(e,t,r),SO=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?T1(this.code,r):r.then(n=>T1(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var _O={};Te(_O,{sha256:()=>ETe,sha512:()=>ATe});var bG,ETe,ATe,xG=b(()=>{l();TO();bG=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),ETe=IO({name:"sha2-256",code:18,encode:bG("SHA-256")}),ATe=IO({name:"sha2-512",code:19,encode:bG("SHA-512")})});var PO={};Te(PO,{identity:()=>ITe});var vG,CTe,EG,STe,ITe,AG=b(()=>{l();rh();C8();vG=0,CTe="identity",EG=rf,STe=e=>T1(vG,EG(e)),ITe={code:vG,name:CTe,encode:EG,digest:STe}});var CG=b(()=>{l();rh()});var yut,wut,SG=b(()=>{l();yut=new TextEncoder,wut=new TextDecoder});var fC,PTe,NTe,RTe,S8,OTe,IG,TG,uC,dC,BTe,kTe,UTe,_G=b(()=>{l();lC();C8();vO();wO();rh();fC=class e{constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this.byteOffset=o.byteOffset,this.byteLength=o.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:dC,byteLength:dC,code:uC,version:uC,multihash:uC,bytes:uC,_baseCache:dC,asCID:dC})}toV0(){switch(this.version){case 0:return this;default:{let{code:t,multihash:r}=this;if(t!==S8)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==OTe)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=T1(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(t){return t&&this.code===t.code&&this.version===t.version&&yG(this.multihash,t.multihash)}toString(t){let{bytes:r,version:n,_baseCache:o}=this;return n===0?NTe(r,o,t||Dl.encoder):RTe(r,o,t||D2.encoder)}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(t){return kTe(/^0\.0/,UTe),!!(t&&(t[TG]||t.asCID===t))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(t){if(t instanceof e)return t;if(t!=null&&t.asCID===t){let{version:r,code:n,multihash:o,bytes:s}=t;return new e(r,n,o,s||IG(r,n,o.bytes))}else if(t!=null&&t[TG]===!0){let{version:r,multihash:n,code:o}=t,s=gG(n);return e.create(r,o,s)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(t){case 0:{if(r!==S8)throw new Error(`Version 0 CID must use dag-pb (code: ${S8}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=IG(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,S8,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=rf(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new H2(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[f,p]=E8(t.subarray(r));return r+=p,f},o=n(),s=S8;if(o===18?(o=0,r=0):o===1&&(s=n()),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,d=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:u}}static parse(t,r){let[n,o]=PTe(t,r),s=e.decode(o);return s._baseCache.set(n,t),s}},PTe=(e,t)=>{switch(e[0]){case"Q":{let r=t||Dl;return[Dl.prefix,r.decode(`${Dl.prefix}${e}`)]}case Dl.prefix:{let r=t||Dl;return[Dl.prefix,r.decode(e)]}case D2.prefix:{let r=t||D2;return[D2.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},NTe=(e,t,r)=>{let{prefix:n}=r;if(n!==Dl.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o},RTe=(e,t,r)=>{let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o},S8=112,OTe=18,IG=(e,t,r)=>{let n=M2(e),o=n+M2(t),s=new Uint8Array(o+r.byteLength);return L2(e,s,0),L2(t,s,n),s.set(r,o),s},TG=Symbol.for("@ipld/js-cid/CID"),uC={writable:!1,configurable:!1,enumerable:!0},dC={writable:!1,enumerable:!1,configurable:!1},BTe="0.0.0-dev",kTe=(e,t)=>{if(e.test(BTe))console.warn(t);else throw new Error(t)},UTe=`CID.isCID(v) is deprecated and will be removed in the next major release. +var PCe=Object.create;var nA=Object.defineProperty;var NCe=Object.getOwnPropertyDescriptor;var RCe=Object.getOwnPropertyNames;var OCe=Object.getPrototypeOf,BCe=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var _e=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Te=(e,t)=>{for(var r in t)nA(e,r,{get:t[r],enumerable:!0})},rA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of RCe(t))!BCe.call(e,o)&&o!==r&&nA(e,o,{get:()=>t[o],enumerable:!(n=NCe(t,o))||n.enumerable});return e},Bo=(e,t,r)=>(rA(e,t,"default"),r&&rA(r,t,"default")),Ht=(e,t,r)=>(r=e!=null?PCe(OCe(e)):{},rA(t||!e||!e.__esModule?nA(r,"default",{value:e,enumerable:!0}):r,e)),Yx=e=>rA(nA({},"__esModule",{value:!0}),e);function g(e){zN=e}var zN,m,l=b(()=>{m=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;readyState=0;bufferedAmount=0;protocol="";extensions="";constructor(t){if(super(),!zN)throw new Error("WalletConnect Runtime transport is unavailable.");let r=zN;this.url="Runtime WalletConnect relay";let n=r.WebSocket||globalThis.WebSocket,o=this.socket=new n(r.url);o.onopen=async()=>{try{let s=r.authorize?(await r.authorize()).token:r.token;this.readyState===0&&o.send(JSON.stringify({token:s,relay:t}))}catch{this.fail(),this.close()}},o.onmessage=s=>{if(this.readyState===0){if(s.data!=='{"ready":true}'){this.close();return}this.readyState=1,this.emit("open",new Event("open"))}else this.emit("message",new MessageEvent("message",{data:s.data}))},o.onerror=()=>this.fail(),o.onclose=()=>{this.readyState===0&&this.fail(),this.readyState=3,this.emit("close",new Event("close"))}}fail(){this.failed||(this.failed=!0,this.emit("error",new Event("error")))}emit(t,r){this[`on${t}`]?.(r),this.dispatchEvent(r)}send(t){if(this.readyState!==1)throw new Error("WalletConnect connection is closed.");this.socket.send(t)}close(){this.readyState===0&&this.fail(),this.readyState=2,this.socket.close()}}});var ks=_e((ent,VN)=>{"use strict";l();var y2=typeof Reflect=="object"?Reflect:null,uW=y2&&typeof y2.apply=="function"?y2.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},oA;y2&&typeof y2.ownKeys=="function"?oA=y2.ownKeys:Object.getOwnPropertySymbols?oA=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:oA=function(t){return Object.getOwnPropertyNames(t)};function kCe(e){console&&console.warn&&console.warn(e)}var fW=Number.isNaN||function(t){return t!==t};function Ar(){Ar.init.call(this)}VN.exports=Ar;VN.exports.once=MCe;Ar.EventEmitter=Ar;Ar.prototype._events=void 0;Ar.prototype._eventsCount=0;Ar.prototype._maxListeners=void 0;var dW=10;function sA(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(Ar,"defaultMaxListeners",{enumerable:!0,get:function(){return dW},set:function(e){if(typeof e!="number"||e<0||fW(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");dW=e}});Ar.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Ar.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||fW(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function pW(e){return e._maxListeners===void 0?Ar.defaultMaxListeners:e._maxListeners}Ar.prototype.getMaxListeners=function(){return pW(this)};Ar.prototype.emit=function(t){for(var r=[],n=1;n0&&(i=r[0]),i instanceof Error)throw i;var a=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw a.context=i,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")uW(c,this,r);else for(var u=c.length,d=wW(c,u),n=0;n0&&i.length>o&&!i.warned){i.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+i.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=i.length,kCe(a)}return e}Ar.prototype.addListener=function(t,r){return hW(this,t,r,!1)};Ar.prototype.on=Ar.prototype.addListener;Ar.prototype.prependListener=function(t,r){return hW(this,t,r,!0)};function UCe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function mW(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},o=UCe.bind(n);return o.listener=r,n.wrapFn=o,o}Ar.prototype.once=function(t,r){return sA(r),this.on(t,mW(this,t,r)),this};Ar.prototype.prependOnceListener=function(t,r){return sA(r),this.prependListener(t,mW(this,t,r)),this};Ar.prototype.removeListener=function(t,r){var n,o,s,i,a;if(sA(r),o=this._events,o===void 0)return this;if(n=o[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(s=-1,i=n.length-1;i>=0;i--)if(n[i]===r||n[i].listener===r){a=n[i].listener,s=i;break}if(s<0)return this;s===0?n.shift():DCe(n,s),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,a||r)}return this};Ar.prototype.off=Ar.prototype.removeListener;Ar.prototype.removeAllListeners=function(t){var r,n,o;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),i;for(o=0;o=0;o--)this.removeListener(t,r[o]);return this};function gW(e,t,r){var n=e._events;if(n===void 0)return[];var o=n[t];return o===void 0?[]:typeof o=="function"?r?[o.listener||o]:[o]:r?LCe(o):wW(o,o.length)}Ar.prototype.listeners=function(t){return gW(this,t,!0)};Ar.prototype.rawListeners=function(t){return gW(this,t,!1)};Ar.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):yW.call(e,t)};Ar.prototype.listenerCount=yW;function yW(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ar.prototype.eventNames=function(){return this._eventsCount>0?oA(this._events):[]};function wW(e,t){for(var r=new Array(t),n=0;n"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new jCe:typeof navigator<"u"?AW(navigator.userAgent):YCe()}function ZCe(e){return e!==""&&KCe.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var s=o.exec(e);return!!s&&[n,s]},!1)}function AW(e){var t=ZCe(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new VCe;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length{l();xW=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;nWN,__asyncDelegator:()=>uSe,__asyncGenerator:()=>lSe,__asyncValues:()=>dSe,__await:()=>Jx,__awaiter:()=>nSe,__classPrivateFieldGet:()=>mSe,__classPrivateFieldSet:()=>gSe,__createBinding:()=>sSe,__decorate:()=>eSe,__exportStar:()=>iSe,__extends:()=>QCe,__generator:()=>oSe,__importDefault:()=>hSe,__importStar:()=>pSe,__makeTemplateObject:()=>fSe,__metadata:()=>rSe,__param:()=>tSe,__read:()=>CW,__rest:()=>XCe,__spread:()=>aSe,__spreadArrays:()=>cSe,__values:()=>KN});function QCe(e,t){qN(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function XCe(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(e);o=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s}function tSe(e,t){return function(r,n){t(r,n,e)}}function rSe(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}function nSe(e,t,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(d){try{u(n.next(d))}catch(f){i(f)}}function c(d){try{u(n.throw(d))}catch(f){i(f)}}function u(d){d.done?s(d.value):o(d.value).then(a,c)}u((n=n.apply(e,t||[])).next())})}function oSe(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(d){return c([u,d])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function CW(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function aSe(){for(var e=[],t=0;t1||a(p,h)})})}function a(p,h){try{c(n[p](h))}catch(y){f(s[0][3],y)}}function c(p){p.value instanceof Jx?Promise.resolve(p.value.v).then(u,d):f(s[0][2],p)}function u(p){a("next",p)}function d(p){a("throw",p)}function f(p,h){p(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function uSe(e){var t,r;return t={},n("next"),n("throw",function(o){throw o}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(o,s){t[o]=e[o]?function(i){return(r=!r)?{value:Jx(e[o](i)),done:o==="return"}:s?s(i):i}:s}}function dSe(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof KN=="function"?KN(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=e[s]&&function(i){return new Promise(function(a,c){i=e[s](i),o(a,c,i.done,i.value)})}}function o(s,i,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},i)}}function fSe(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function pSe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function hSe(e){return e&&e.__esModule?e:{default:e}}function mSe(e,t){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return t.get(e)}function gSe(e,t,r){if(!t.has(e))throw new TypeError("attempted to set private field on non-instance");return t.set(e,r),r}var qN,WN,b2=b(()=>{l();qN=function(e,t){return qN=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},qN(e,t)};WN=function(){return WN=Object.assign||function(t){for(var r,n=1,o=arguments.length;n{"use strict";l();Object.defineProperty(aA,"__esModule",{value:!0});aA.delay=void 0;function ySe(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}aA.delay=ySe});var IW=_e(x2=>{"use strict";l();Object.defineProperty(x2,"__esModule",{value:!0});x2.ONE_THOUSAND=x2.ONE_HUNDRED=void 0;x2.ONE_HUNDRED=100;x2.ONE_THOUSAND=1e3});var TW=_e(Ue=>{"use strict";l();Object.defineProperty(Ue,"__esModule",{value:!0});Ue.ONE_YEAR=Ue.FOUR_WEEKS=Ue.THREE_WEEKS=Ue.TWO_WEEKS=Ue.ONE_WEEK=Ue.THIRTY_DAYS=Ue.SEVEN_DAYS=Ue.FIVE_DAYS=Ue.THREE_DAYS=Ue.ONE_DAY=Ue.TWENTY_FOUR_HOURS=Ue.TWELVE_HOURS=Ue.SIX_HOURS=Ue.THREE_HOURS=Ue.ONE_HOUR=Ue.SIXTY_MINUTES=Ue.THIRTY_MINUTES=Ue.TEN_MINUTES=Ue.FIVE_MINUTES=Ue.ONE_MINUTE=Ue.SIXTY_SECONDS=Ue.THIRTY_SECONDS=Ue.TEN_SECONDS=Ue.FIVE_SECONDS=Ue.ONE_SECOND=void 0;Ue.ONE_SECOND=1;Ue.FIVE_SECONDS=5;Ue.TEN_SECONDS=10;Ue.THIRTY_SECONDS=30;Ue.SIXTY_SECONDS=60;Ue.ONE_MINUTE=Ue.SIXTY_SECONDS;Ue.FIVE_MINUTES=Ue.ONE_MINUTE*5;Ue.TEN_MINUTES=Ue.ONE_MINUTE*10;Ue.THIRTY_MINUTES=Ue.ONE_MINUTE*30;Ue.SIXTY_MINUTES=Ue.ONE_MINUTE*60;Ue.ONE_HOUR=Ue.SIXTY_MINUTES;Ue.THREE_HOURS=Ue.ONE_HOUR*3;Ue.SIX_HOURS=Ue.ONE_HOUR*6;Ue.TWELVE_HOURS=Ue.ONE_HOUR*12;Ue.TWENTY_FOUR_HOURS=Ue.ONE_HOUR*24;Ue.ONE_DAY=Ue.TWENTY_FOUR_HOURS;Ue.THREE_DAYS=Ue.ONE_DAY*3;Ue.FIVE_DAYS=Ue.ONE_DAY*5;Ue.SEVEN_DAYS=Ue.ONE_DAY*7;Ue.THIRTY_DAYS=Ue.ONE_DAY*30;Ue.ONE_WEEK=Ue.SEVEN_DAYS;Ue.TWO_WEEKS=Ue.ONE_WEEK*2;Ue.THREE_WEEKS=Ue.ONE_WEEK*3;Ue.FOUR_WEEKS=Ue.ONE_WEEK*4;Ue.ONE_YEAR=Ue.ONE_DAY*365});var ZN=_e(cA=>{"use strict";l();Object.defineProperty(cA,"__esModule",{value:!0});var _W=(b2(),Yx(w2));_W.__exportStar(IW(),cA);_W.__exportStar(TW(),cA)});var NW=_e(v2=>{"use strict";l();Object.defineProperty(v2,"__esModule",{value:!0});v2.fromMiliseconds=v2.toMiliseconds=void 0;var PW=ZN();function wSe(e){return e*PW.ONE_THOUSAND}v2.toMiliseconds=wSe;function bSe(e){return Math.floor(e/PW.ONE_THOUSAND)}v2.fromMiliseconds=bSe});var OW=_e(lA=>{"use strict";l();Object.defineProperty(lA,"__esModule",{value:!0});var RW=(b2(),Yx(w2));RW.__exportStar(SW(),lA);RW.__exportStar(NW(),lA)});var BW=_e(Qx=>{"use strict";l();Object.defineProperty(Qx,"__esModule",{value:!0});Qx.Watch=void 0;var uA=class{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){let r=this.get(t);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);let n=Date.now()-r.started;this.timestamps.set(t,{started:r.started,elapsed:n})}get(t){let r=this.timestamps.get(t);if(typeof r>"u")throw new Error(`No timestamp found for label: ${t}`);return r}elapsed(t){let r=this.get(t);return r.elapsed||Date.now()-r.started}};Qx.Watch=uA;Qx.default=uA});var kW=_e(dA=>{"use strict";l();Object.defineProperty(dA,"__esModule",{value:!0});dA.IWatch=void 0;var GN=class{};dA.IWatch=GN});var UW=_e(YN=>{"use strict";l();Object.defineProperty(YN,"__esModule",{value:!0});var xSe=(b2(),Yx(w2));xSe.__exportStar(kW(),YN)});var jd=_e(E2=>{"use strict";l();Object.defineProperty(E2,"__esModule",{value:!0});var fA=(b2(),Yx(w2));fA.__exportStar(OW(),E2);fA.__exportStar(BW(),E2);fA.__exportStar(UW(),E2);fA.__exportStar(ZN(),E2)});var C2=_e(Ur=>{"use strict";l();Object.defineProperty(Ur,"__esModule",{value:!0});Ur.getLocalStorage=Ur.getLocalStorageOrThrow=Ur.getCrypto=Ur.getCryptoOrThrow=Ur.getLocation=Ur.getLocationOrThrow=Ur.getNavigator=Ur.getNavigatorOrThrow=Ur.getDocument=Ur.getDocumentOrThrow=Ur.getFromWindowOrThrow=Ur.getFromWindow=void 0;function l1(e){let t;return typeof window<"u"&&typeof window[e]<"u"&&(t=window[e]),t}Ur.getFromWindow=l1;function A2(e){let t=l1(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Ur.getFromWindowOrThrow=A2;function vSe(){return A2("document")}Ur.getDocumentOrThrow=vSe;function ESe(){return l1("document")}Ur.getDocument=ESe;function ASe(){return A2("navigator")}Ur.getNavigatorOrThrow=ASe;function CSe(){return l1("navigator")}Ur.getNavigator=CSe;function SSe(){return A2("location")}Ur.getLocationOrThrow=SSe;function ISe(){return l1("location")}Ur.getLocation=ISe;function TSe(){return A2("crypto")}Ur.getCryptoOrThrow=TSe;function _Se(){return l1("crypto")}Ur.getCrypto=_Se;function PSe(){return A2("localStorage")}Ur.getLocalStorageOrThrow=PSe;function NSe(){return l1("localStorage")}Ur.getLocalStorage=NSe});var JN=_e(pA=>{"use strict";l();Object.defineProperty(pA,"__esModule",{value:!0});pA.getWindowMetadata=void 0;var DW=C2();function RSe(){let e,t;try{e=DW.getDocumentOrThrow(),t=DW.getLocationOrThrow()}catch{return null}function r(){let f=e.getElementsByTagName("link"),p=[];for(let h=0;h-1){let x=y.getAttribute("href");if(x)if(x.toLowerCase().indexOf("https:")===-1&&x.toLowerCase().indexOf("http:")===-1&&x.indexOf("//")!==0){let v=t.protocol+"//"+t.host;if(x.indexOf("/")===0)v+=x;else{let T=t.pathname.split("/");T.pop();let E=T.join("/");v+=E+"/"+x}p.push(v)}else if(x.indexOf("//")===0){let v=t.protocol+x;p.push(v)}else p.push(x)}}return p}function n(...f){let p=e.getElementsByTagName("meta");for(let h=0;hy.getAttribute(x)).filter(x=>x?f.includes(x):!1);if(w.length&&w){let x=y.getAttribute("content");if(x)return x}}return""}function o(){let f=n("name","og:site_name","og:title","twitter:title");return f||(f=e.title),f}function s(){return n("description","og:description","twitter:description","keywords")}let i=o(),a=s(),c=t.origin,u=r();return{description:a,url:c,icons:u,name:i}}pA.getWindowMetadata=RSe});var UIe,DIe,LIe,MIe,uZ,dZ,fZ,HIe,$Ie,Qit,Xit,eat,tat,pZ=b(()=>{l();UIe=44032,DIe=4352,LIe=4449,MIe=4519,uZ=19,dZ=21,fZ=28,HIe=dZ*fZ,$Ie=uZ*HIe,Qit=UIe+$Ie,Xit=DIe+uZ,eat=LIe+dZ,tat=MIe+fZ});function gZ(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function yZ(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(r=>typeof r=="string"):t.every(r=>Number.isSafeInteger(r)):!1}function VA(e,t){if(typeof t!="string")throw new Error(`${e}: string expected`);return!0}function p8(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function jA(e){if(!Array.isArray(e))throw new Error("array expected")}function qA(e,t){if(!yZ(!0,t))throw new Error(`${e}: array of strings expected`)}function wZ(e,t){if(!yZ(!1,t))throw new Error(`${e}: array of numbers expected`)}function bZ(...e){let t=s=>s,r=(s,i)=>a=>s(i(a)),n=e.map(s=>s.encode).reduceRight(r,t),o=e.map(s=>s.decode).reduce(r,t);return{encode:n,decode:o}}function xZ(e){let t=typeof e=="string"?e.split(""):e,r=t.length;qA("alphabet",t);let n=new Map(t.map((o,s)=>[o,s]));return{encode:o=>(jA(o),o.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]})),decode:o=>(jA(o),o.map(s=>{VA("alphabet.decode",s);let i=n.get(s);if(i===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${e}`);return i}))}}function vZ(e=""){return VA("join",e),{encode:t=>(qA("join.decode",t),t.join(e)),decode:t=>(VA("join.decode",t),t.split(e))}}function FIe(e,t="="){return p8(e),VA("padding",t),{encode(r){for(qA("padding.encode",r);r.length*e%8;)r.push(t);return r},decode(r){qA("padding.decode",r);let n=r.length;if(n*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if((n-1)*e%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}function hZ(e,t,r){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(jA(e),!e.length)return[];let n=0,o=[],s=Array.from(e,a=>{if(p8(a),a<0||a>=t)throw new Error(`invalid integer: ${a}`);return a}),i=s.length;for(;;){let a=0,c=!0;for(let u=n;u32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(WA(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${WA(t,r)}`);let o=0,s=0,i=YR[t],a=YR[r]-1,c=[];for(let u of e){if(p8(u),u>=i)throw new Error(`convertRadix2: invalid data word=${u} from=${t}`);if(o=o<32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=r;s-=r)c.push((o>>s-r&a)>>>0);let d=YR[s];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<=t)throw new Error("Excess padding");if(!n&&o>0)throw new Error(`Non-zero padding: ${o}`);return n&&s>0&&c.push(o>>>0),c}function zIe(e){p8(e);let t=2**8;return{encode:r=>{if(!gZ(r))throw new Error("radix.encode input should be Uint8Array");return hZ(Array.from(r),t,e)},decode:r=>(wZ("radix.decode",r),Uint8Array.from(hZ(r,e,t)))}}function VIe(e,t=!1){if(p8(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(WA(8,e)>32||WA(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!gZ(r))throw new Error("radix2.encode input should be Uint8Array");return mZ(Array.from(r),8,e,!t)},decode:r=>(wZ("radix2.decode",r),Uint8Array.from(mZ(r,e,8,t)))}}var EZ,WA,YR,KA,jIe,B2,JR=b(()=>{l();EZ=(e,t)=>t===0?e:EZ(t,e%t),WA=(e,t)=>e+(t-EZ(e,t)),YR=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();KA=bZ(VIe(5),xZ("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),FIe(5),vZ("")),jIe=e=>bZ(zIe(58),xZ(e),vZ("")),B2=jIe("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")});function PZ(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function GA(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function YA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function rs(e,...t){if(!PZ(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function QR(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function NZ(e,t){rs(e);let r=t.outputLen;if(e.length>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function BZ(e,t,r){GA(r);let n=new Uint8Array(16),o=JIe(n);return _Z(o,0,BigInt(t),r),_Z(o,8,BigInt(e),r),n}function e9e(e){return e.byteOffset%4===0}function QA(e){return Uint8Array.from(e)}var QIe,XR,XA=b(()=>{l();QIe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;XR=(e,t)=>{function r(n,...o){if(rs(n),!QIe)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let d=o[0];if(!d)throw new Error("nonce / iv required");e.varSizeNonce?rs(d):rs(d,e.nonceLength)}let s=e.tagLength;s&&o[1]!==void 0&&rs(o[1]);let i=t(n,...o),a=(d,f)=>{if(f!==void 0){if(d!==2)throw new Error("cipher output not supported");rs(f)}},c=!1;return{encrypt(d,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,rs(d),a(i.encrypt.length,f),i.encrypt(d,f)},decrypt(d,f){if(rs(d),s&&d.length{l();LZ=Ht(DZ(),1)});var KZ=b(()=>{l()});function I1(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}var b8=b(()=>{l()});function x8(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?I1(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}var aC=b(()=>{l();b8()});function Ms(e,t){t||(t=e.reduce((o,s)=>o+s.length,0));let r=x8(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return I1(r)}var ZZ=b(()=>{l();aC();b8()});var GZ=b(()=>{l()});function T9e(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}var _9e,P9e,YZ,JZ=b(()=>{l();_9e=T9e,P9e=_9e,YZ=P9e});var Rlt,QZ,rf,XZ,eG,rh=b(()=>{l();Rlt=new Uint8Array(0),QZ=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},XZ=e=>new TextEncoder().encode(e),eG=e=>new TextDecoder().decode(e)});var cO,lO,uO,rG,dO,U2,nh,N9e,R9e,mn,Bc=b(()=>{l();JZ();rh();cO=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},lO=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return rG(this,t)}},uO=class{constructor(t){this.decoders=t}or(t){return rG(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},rG=(e,t)=>new uO({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),dO=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new cO(t,r,n),this.decoder=new lO(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},U2=({name:e,prefix:t,encode:r,decode:n})=>new dO(e,t,r,n),nh=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=YZ(r,t);return U2({prefix:e,name:t,encode:n,decode:s=>rf(o(s))})},N9e=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},R9e=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<U2({prefix:t,name:e,encode(o){return R9e(o,n,r)},decode(o){return N9e(o,n,r,e)}})});var fO={};Te(fO,{identity:()=>O9e});var O9e,nG=b(()=>{l();Bc();rh();O9e=U2({prefix:"\0",name:"identity",encode:e=>eG(e),decode:e=>XZ(e)})});var pO={};Te(pO,{base2:()=>B9e});var B9e,oG=b(()=>{l();Bc();B9e=mn({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var hO={};Te(hO,{base8:()=>k9e});var k9e,sG=b(()=>{l();Bc();k9e=mn({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var mO={};Te(mO,{base10:()=>U9e});var U9e,iG=b(()=>{l();Bc();U9e=nh({prefix:"9",name:"base10",alphabet:"0123456789"})});var gO={};Te(gO,{base16:()=>D9e,base16upper:()=>L9e});var D9e,L9e,aG=b(()=>{l();Bc();D9e=mn({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L9e=mn({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var yO={};Te(yO,{base32:()=>D2,base32hex:()=>F9e,base32hexpad:()=>V9e,base32hexpadupper:()=>j9e,base32hexupper:()=>z9e,base32pad:()=>H9e,base32padupper:()=>$9e,base32upper:()=>M9e,base32z:()=>q9e});var D2,M9e,H9e,$9e,F9e,z9e,V9e,j9e,q9e,wO=b(()=>{l();Bc();D2=mn({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),M9e=mn({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),H9e=mn({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$9e=mn({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),F9e=mn({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z9e=mn({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),V9e=mn({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),j9e=mn({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),q9e=mn({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var bO={};Te(bO,{base36:()=>W9e,base36upper:()=>K9e});var W9e,K9e,cG=b(()=>{l();Bc();W9e=nh({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),K9e=nh({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var xO={};Te(xO,{base58btc:()=>Dl,base58flickr:()=>Z9e});var Dl,Z9e,vO=b(()=>{l();Bc();Dl=nh({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Z9e=nh({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var EO={};Te(EO,{base64:()=>G9e,base64pad:()=>Y9e,base64url:()=>J9e,base64urlpad:()=>Q9e});var G9e,Y9e,J9e,Q9e,lG=b(()=>{l();Bc();G9e=mn({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Y9e=mn({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J9e=mn({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Q9e=mn({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var AO={};Te(AO,{base256emoji:()=>nTe});function tTe(e){return e.reduce((t,r)=>(t+=X9e[r],t),"")}function rTe(e){let t=[];for(let r of e){let n=eTe[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}var uG,X9e,eTe,nTe,dG=b(()=>{l();Bc();uG=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),X9e=uG.reduce((e,t,r)=>(e[r]=t,e),[]),eTe=uG.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);nTe=U2({prefix:"\u{1F680}",name:"base256emoji",encode:tTe,decode:rTe})});function hG(e,t,r){t=t||[],r=r||0;for(var n=r;e>=aTe;)t[r++]=e&255|fG,e/=128;for(;e&iTe;)t[r++]=e&255|fG,e>>>=7;return t[r]=e|0,hG.bytes=r-n+1,t}function CO(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw CO.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&pG)<=lTe);return CO.bytes=s-n,r}var oTe,fG,sTe,iTe,aTe,cTe,lTe,pG,uTe,dTe,fTe,pTe,hTe,mTe,gTe,yTe,wTe,bTe,xTe,vTe,v8,mG=b(()=>{l();oTe=hG,fG=128,sTe=127,iTe=~sTe,aTe=Math.pow(2,31);cTe=CO,lTe=128,pG=127;uTe=Math.pow(2,7),dTe=Math.pow(2,14),fTe=Math.pow(2,21),pTe=Math.pow(2,28),hTe=Math.pow(2,35),mTe=Math.pow(2,42),gTe=Math.pow(2,49),yTe=Math.pow(2,56),wTe=Math.pow(2,63),bTe=function(e){return e{l();mG();E8=(e,t=0)=>[v8.decode(e,t),v8.decode.bytes],L2=(e,t,r=0)=>(v8.encode(e,t,r),t),M2=e=>v8.encodingLength(e)});var T1,gG,yG,H2,C8=b(()=>{l();rh();lC();T1=(e,t)=>{let r=t.byteLength,n=M2(e),o=n+M2(r),s=new Uint8Array(o+r);return L2(e,s,0),L2(r,s,n),s.set(t,o),new H2(e,r,t,s)},gG=e=>{let t=rf(e),[r,n]=E8(t),[o,s]=E8(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new H2(r,o,i,t)},yG=(e,t)=>e===t?!0:e.code===t.code&&e.size===t.size&&QZ(e.bytes,t.bytes),H2=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}}});var IO,SO,TO=b(()=>{l();C8();IO=({name:e,code:t,encode:r})=>new SO(e,t,r),SO=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?T1(this.code,r):r.then(n=>T1(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var _O={};Te(_O,{sha256:()=>ETe,sha512:()=>ATe});var bG,ETe,ATe,xG=b(()=>{l();TO();bG=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),ETe=IO({name:"sha2-256",code:18,encode:bG("SHA-256")}),ATe=IO({name:"sha2-512",code:19,encode:bG("SHA-512")})});var PO={};Te(PO,{identity:()=>ITe});var vG,CTe,EG,STe,ITe,AG=b(()=>{l();rh();C8();vG=0,CTe="identity",EG=rf,STe=e=>T1(vG,EG(e)),ITe={code:vG,name:CTe,encode:EG,digest:STe}});var CG=b(()=>{l();rh()});var yut,wut,SG=b(()=>{l();yut=new TextEncoder,wut=new TextDecoder});var fC,PTe,NTe,RTe,S8,OTe,IG,TG,uC,dC,BTe,kTe,UTe,_G=b(()=>{l();lC();C8();vO();wO();rh();fC=class e{constructor(t,r,n,o){this.code=r,this.version=t,this.multihash=n,this.bytes=o,this.byteOffset=o.byteOffset,this.byteLength=o.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:dC,byteLength:dC,code:uC,version:uC,multihash:uC,bytes:uC,_baseCache:dC,asCID:dC})}toV0(){switch(this.version){case 0:return this;default:{let{code:t,multihash:r}=this;if(t!==S8)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==OTe)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=T1(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(t){return t&&this.code===t.code&&this.version===t.version&&yG(this.multihash,t.multihash)}toString(t){let{bytes:r,version:n,_baseCache:o}=this;return n===0?NTe(r,o,t||Dl.encoder):RTe(r,o,t||D2.encoder)}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(t){return kTe(/^0\.0/,UTe),!!(t&&(t[TG]||t.asCID===t))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(t){if(t instanceof e)return t;if(t!=null&&t.asCID===t){let{version:r,code:n,multihash:o,bytes:s}=t;return new e(r,n,o,s||IG(r,n,o.bytes))}else if(t!=null&&t[TG]===!0){let{version:r,multihash:n,code:o}=t,s=gG(n);return e.create(r,o,s)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");switch(t){case 0:{if(r!==S8)throw new Error(`Version 0 CID must use dag-pb (code: ${S8}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=IG(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,S8,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=rf(t.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new H2(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[f,p]=E8(t.subarray(r));return r+=p,f},o=n(),s=S8;if(o===18?(o=0,r=0):o===1&&(s=n()),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,d=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:u}}static parse(t,r){let[n,o]=PTe(t,r),s=e.decode(o);return s._baseCache.set(n,t),s}},PTe=(e,t)=>{switch(e[0]){case"Q":{let r=t||Dl;return[Dl.prefix,r.decode(`${Dl.prefix}${e}`)]}case Dl.prefix:{let r=t||Dl;return[Dl.prefix,r.decode(e)]}case D2.prefix:{let r=t||D2;return[D2.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},NTe=(e,t,r)=>{let{prefix:n}=r;if(n!==Dl.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o},RTe=(e,t,r)=>{let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o},S8=112,OTe=18,IG=(e,t,r)=>{let n=M2(e),o=n+M2(t),s=new Uint8Array(o+r.byteLength);return L2(e,s,0),L2(t,s,n),s.set(r,o),s},TG=Symbol.for("@ipld/js-cid/CID"),uC={writable:!1,configurable:!1,enumerable:!0},dC={writable:!1,enumerable:!1,configurable:!1},BTe="0.0.0-dev",kTe=(e,t)=>{if(e.test(BTe))console.warn(t);else throw new Error(t)},UTe=`CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: if (CID.isCID(value)) { @@ -12,18 +12,18 @@ if (cid) { // Make sure to use cid instead of value doSomethingWithCID(cid) } -`});var PG=b(()=>{l();_G();lC();rh();TO();C8()});var NO,Put,NG=b(()=>{l();nG();oG();sG();iG();aG();wO();cG();vO();lG();dG();xG();AG();CG();SG();PG();NO={...fO,...pO,...hO,...mO,...gO,...yO,...bO,...xO,...EO,...AO},Put={..._O,...PO}});function OG(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var RG,RO,DTe,pC,OO=b(()=>{l();NG();aC();RG=OG("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),RO=OG("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=x8(e.length);for(let r=0;r{l();OO();b8()});function Ut(e,t="utf8"){let r=pC[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var BG=b(()=>{l();OO()});var kG=b(()=>{l();aC();b8()});var I8=b(()=>{l();KZ();ZZ();GZ();BO();BG();kG()});function Fs(e){if(typeof e!="string")throw new Error(`Cannot safe json parse value of type ${typeof e}`);try{return L_e(e)}catch{return e}}function yi(e){return typeof e=="string"?e:D_e(e)||""}var D_e,L_e,R1=b(()=>{l();D_e=e=>JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString()+"n":r),L_e=e=>{let t=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=e.replace(t,'$1"$2n"$3');return JSON.parse(r,(n,o)=>typeof o=="string"&&o.match(/^\d+n$/)?BigInt(o.substring(0,o.length-1)):o)}});function M_e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ZY(e,...t){if(!M_e(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function PY(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function H_e(e,t){ZY(e);let r=t.outputLen;if(e.lengthe().update(GY(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function YY(e=32){if(G2&&typeof G2.getRandomValues=="function")return G2.getRandomValues(new Uint8Array(e));if(G2&&typeof G2.randomBytes=="function")return G2.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function z_e(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function JY(e,t=!1){return t?{h:Number(e&CC),l:Number(e>>hB&CC)}:{h:Number(e>>hB&CC)|0,l:Number(e&CC)|0}}function V_e(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;o>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}function TB(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function _B(e){if(!TB(e))throw new Error("Uint8Array expected")}function sB(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function PB(e){_B(e);let t="";for(let r=0;r=ff._0&&e<=ff._9)return e-ff._0;if(e>=ff.A&&e<=ff.F)return e-(ff.A-10);if(e>=ff.a&&e<=ff.f)return e-(ff.a-10)}function eJ(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oIB;e>>=QY,t+=1);return t}function NB(e,t,r={}){let n=(o,s,i)=>{let a=b7e[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function OY(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}function eo(e,t){let r=e%t;return r>=go?r:t+r}function v7e(e,t,r){if(tgo;)t&Sn&&(n=n*e%r),e=e*e%r,t>>=Sn;return n}function Ml(e,t,r){let n=e;for(;t-- >go;)n*=n,n%=r;return n}function UY(e,t){if(e===go)throw new Error("invert: expected non-zero number");if(t<=go)throw new Error("invert: expected positive modulus, got "+t);let r=eo(e,t),n=t,o=go,s=Sn;for(;r!==go;){let i=n/r,a=n%r,c=o-s*i;n=r,r=a,o=s,s=c}if(n!==Sn)throw new Error("invert: does not exist");return eo(o,t)}function E7e(e){let t=(e-Sn)/O1,r,n,o;for(r=e-Sn,n=0;r%O1===go;r/=O1,n++);for(o=O1;o1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(e+Sn)/yB;return function(a,c){let u=a.pow(c,i);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}let s=(r+Sn)/O1;return function(i,a){if(i.pow(a,t)===i.neg(i.ONE))throw new Error("Cannot find square root");let c=n,u=i.pow(i.mul(i.ONE,o),r),d=i.pow(a,s),f=i.pow(a,r);for(;!i.eql(f,i.ONE);){if(i.eql(f,i.ZERO))return i.ZERO;let p=1;for(let y=i.sqr(f);p(n[o]="function",n),t);return NB(e,r)}function T7e(e,t,r){if(rgo;)r&Sn&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Sn;return n}function _7e(e,t){let r=new Array(t.length),n=t.reduce((s,i,a)=>e.is0(i)?s:(r[a]=s,e.mul(s,i)),e.ONE),o=e.inv(n);return t.reduceRight((s,i,a)=>e.is0(i)?s:(r[a]=e.mul(s,r[a]),e.mul(s,i)),o),r}function rJ(e,t){let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function nJ(e,t,r=!1,n={}){if(e<=go)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=rJ(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:w7e(o),ZERO:go,ONE:Sn,create:c=>eo(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return go<=c&&cc===go,isOdd:c=>(c&Sn)===Sn,neg:c=>eo(-c,e),eql:(c,u)=>c===u,sqr:c=>eo(c*c,e),add:(c,u)=>eo(c+u,e),sub:(c,u)=>eo(c-u,e),mul:(c,u)=>eo(c*u,e),pow:(c,u)=>T7e(a,c,u),div:(c,u)=>eo(c*UY(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>UY(c,e),sqrt:n.sqrt||(c=>(i||(i=A7e(e)),i(a,c))),invertBatch:c=>_7e(a,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?gB(c,s):tJ(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?TC(c):m7e(c)}});return Object.freeze(a)}function aB(e,t){let r=t.negate();return e?r:t}function oJ(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function cB(e,t){oJ(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1);return{windows:r,windowSize:n}}function P7e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function N7e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function uB(e){return sJ.get(e)||1}function R7e(e,t){return{constTimeNegate:aB,hasPrecomputes(r){return uB(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>DY;)n&SC&&(o=o.add(s)),s=s.double(),n>>=SC;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=cB(n,t),i=[],a=r,c=a;for(let u=0;u>=f,y>i&&(y-=d,o+=SC);let w=h,x=h+Math.abs(y)-1,v=p%2!==0,T=y<0;y===0?c=c.add(aB(v,n[w])):a=a.add(aB(T,n[x]))}return{p:a,f:c}},wNAFUnsafe(r,n,o,s=e.ZERO){let{windows:i,windowSize:a}=cB(r,t),c=BigInt(2**r-1),u=2**r,d=BigInt(r);for(let f=0;f>=d,h>a&&(h-=u,o+=SC),h===0)continue;let y=n[p+Math.abs(h)-1];h<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(r,n,o){let s=lB.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&lB.set(n,o(s))),s},wNAFCached(r,n,o){let s=uB(r);return this.wNAF(s,this.getPrecomputes(s,r,o),n)},wNAFCachedUnsafe(r,n,o,s){let i=uB(r);return i===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,r,o),n,s)},setWindowSize(r,n){oJ(n,t),sJ.set(r,n),lB.delete(r)}}}function O7e(e,t,r,n){if(P7e(r,e),N7e(n,t),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=e.ZERO,s=y7e(BigInt(r.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<=0;f-=i){c.fill(o);for(let h=0;h>BigInt(f)&BigInt(a));c[w]=c[w].add(r[h])}let p=o;for(let h=c.length-1,y=o;h>0;h--)y=y.add(c[h]),p=p.add(y);if(d=d.add(p),f!==0)for(let h=0;h{try{return{isValid:!0,value:r.sqrt(C*r.inv(A))}}catch{return{isValid:!1,value:kc}}}),h=t.adjustScalarBytes||(C=>C),y=t.domain||((C,A,U)=>{if(sB("phflag",U),A.length||U)throw new Error("Contexts/pre-hash are not supported");return C});function w(C,A){B8("coordinate "+C,A,kc,u)}function x(C){if(!(C instanceof E))throw new Error("ExtendedPoint expected")}let v=OY((C,A)=>{let{ex:U,ey:H,ez:k}=C,F=C.is0();A==null&&(A=F?k7e:r.inv(k));let j=d(U*A),W=d(H*A),ae=d(k*A);if(F)return{x:kc,y:wi};if(ae!==wi)throw new Error("invZ was invalid");return{x:j,y:W}}),T=OY(C=>{let{a:A,d:U}=t;if(C.is0())throw new Error("bad point: ZERO");let{ex:H,ey:k,ez:F,et:j}=C,W=d(H*H),ae=d(k*k),te=d(F*F),X=d(te*te),pe=d(W*A),me=d(te*d(pe+ae)),Ne=d(X+d(U*d(W*ae)));if(me!==Ne)throw new Error("bad point: equation left != right (1)");let ye=d(H*k),Re=d(F*j);if(ye!==Re)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(A,U,H,k){this.ex=A,this.ey=U,this.ez=H,this.et=k,w("x",A),w("y",U),w("z",H),w("t",k),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof E)throw new Error("extended point not allowed");let{x:U,y:H}=A||{};return w("x",U),w("y",H),new E(U,H,wi,d(U*H))}static normalizeZ(A){let U=r.invertBatch(A.map(H=>H.ez));return A.map((H,k)=>H.toAffine(U[k])).map(E.fromAffine)}static msm(A,U){return O7e(E,f,A,U)}_setWindowSize(A){O.setWindowSize(this,A)}assertValidity(){T(this)}equals(A){x(A);let{ex:U,ey:H,ez:k}=this,{ex:F,ey:j,ez:W}=A,ae=d(U*W),te=d(F*k),X=d(H*W),pe=d(j*k);return ae===te&&X===pe}is0(){return this.equals(E.ZERO)}negate(){return new E(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:A}=t,{ex:U,ey:H,ez:k}=this,F=d(U*U),j=d(H*H),W=d(IC*d(k*k)),ae=d(A*F),te=U+H,X=d(d(te*te)-F-j),pe=ae+j,me=pe-W,Ne=ae-j,ye=d(X*me),Re=d(pe*Ne),Et=d(X*Ne),kt=d(me*pe);return new E(ye,Re,kt,Et)}add(A){x(A);let{a:U,d:H}=t,{ex:k,ey:F,ez:j,et:W}=this,{ex:ae,ey:te,ez:X,et:pe}=A;if(U===BigInt(-1)){let nW=d((F-k)*(te+ae)),oW=d((F+k)*(te-ae)),FN=d(oW-nW);if(FN===kc)return this.double();let sW=d(j*IC*pe),iW=d(W*IC*X),aW=iW+sW,cW=oW+nW,lW=iW-sW,SCe=d(aW*FN),ICe=d(cW*lW),TCe=d(aW*lW),_Ce=d(FN*cW);return new E(SCe,ICe,_Ce,TCe)}let me=d(k*ae),Ne=d(F*te),ye=d(W*H*pe),Re=d(j*X),Et=d((k+F)*(ae+te)-me-Ne),kt=Re-ye,At=Re+ye,ur=d(Ne-U*me),_r=d(Et*kt),Pl=d(At*ur),ACe=d(Et*ur),CCe=d(kt*At);return new E(_r,Pl,CCe,ACe)}subtract(A){return this.add(A.negate())}wNAF(A){return O.wNAFCached(this,A,E.normalizeZ)}multiply(A){let U=A;B8("scalar",U,wi,n);let{p:H,f:k}=this.wNAF(U);return E.normalizeZ([H,k])[0]}multiplyUnsafe(A,U=E.ZERO){let H=A;return B8("scalar",H,kc,n),H===kc?_:this.is0()||H===wi?this:O.wNAFCachedUnsafe(this,H,E.normalizeZ,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(A){return v(this,A)}clearCofactor(){let{h:A}=t;return A===wi?this:this.multiplyUnsafe(A)}static fromHex(A,U=!1){let{d:H,a:k}=t,F=r.BYTES;A=pf("pointHex",A,F),sB("zip215",U);let j=A.slice(),W=A[F-1];j[F-1]=W&-129;let ae=TC(j),te=U?u:r.ORDER;B8("pointHex.y",ae,kc,te);let X=d(ae*ae),pe=d(X-wi),me=d(H*X-k),{isValid:Ne,value:ye}=p(pe,me);if(!Ne)throw new Error("Point.fromHex: invalid y coordinate");let Re=(ye&wi)===wi,Et=(W&128)!==0;if(!U&&ye===kc&&Et)throw new Error("Point.fromHex: x=0 and x_0=1");return Et!==Re&&(ye=d(-ye)),E.fromAffine({x:ye,y:ae})}static fromPrivateKey(A){return N(A).point}toRawBytes(){let{x:A,y:U}=this.toAffine(),H=gB(U,r.BYTES);return H[H.length-1]|=A&wi?128:0,H}toHex(){return PB(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,wi,d(t.Gx*t.Gy)),E.ZERO=new E(kc,wi,wi,kc);let{BASE:S,ZERO:_}=E,O=R7e(E,a*8);function D(C){return eo(C,n)}function M(C){return D(TC(C))}function N(C){let A=r.BYTES;C=pf("private key",C,A);let U=pf("hashed private key",s(C),2*A),H=h(U.slice(0,A)),k=U.slice(A,2*A),F=M(H),j=S.multiply(F),W=j.toRawBytes();return{head:H,prefix:k,scalar:F,point:j,pointBytes:W}}function L(C){return N(C).pointBytes}function P(C=new Uint8Array,...A){let U=RY(...A);return M(s(y(U,pf("context",C),!!o)))}function R(C,A,U={}){C=pf("message",C),o&&(C=o(C));let{prefix:H,scalar:k,pointBytes:F}=N(A),j=P(U.context,H,C),W=S.multiply(j).toRawBytes(),ae=P(U.context,W,F,C),te=D(j+ae*k);B8("signature.s",te,kc,n);let X=RY(W,gB(te,r.BYTES));return pf("result",X,r.BYTES*2)}let I=U7e;function B(C,A,U,H=I){let{context:k,zip215:F}=H,j=r.BYTES;C=pf("signature",C,2*j),A=pf("message",A),U=pf("publicKey",U,j),F!==void 0&&sB("zip215",F),o&&(A=o(A));let W=TC(C.slice(j,2*j)),ae,te,X;try{ae=E.fromHex(U,F),te=E.fromHex(C.slice(0,j),F),X=S.multiplyUnsafe(W)}catch{return!1}if(!F&&ae.isSmallOrder())return!1;let pe=P(k,te.toRawBytes(),ae.toRawBytes(),A);return te.add(ae.multiplyUnsafe(pe)).subtract(X).clearCofactor().equals(E.ZERO)}return S._setWindowSize(8),{CURVE:t,getPublicKey:L,sign:R,verify:B,ExtendedPoint:E,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(r.BYTES),precompute(C=8,A=E.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}}}}function F7e(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=RB,i=e*e%s*e%s,a=Ml(i,MY,s)*i%s,c=Ml(a,M7e,s)*e%s,u=Ml(c,H7e,s)*c%s,d=Ml(u,t,s)*u%s,f=Ml(d,r,s)*d%s,p=Ml(f,n,s)*f%s,h=Ml(p,o,s)*p%s,y=Ml(h,o,s)*p%s,w=Ml(y,t,s)*u%s;return{pow_p_5_8:Ml(w,MY,s)*e%s,b2:i}}function z7e(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function V7e(e,t){let r=RB,n=eo(t*t*t,r),o=eo(n*n*t,r),s=F7e(e*o).pow_p_5_8,i=eo(e*n*s,r),a=eo(t*i*i,r),c=i,u=eo(i*LY,r),d=a===e,f=a===eo(-e,r),p=a===eo(-e*LY,r);return d&&(i=c),(f||p)&&(i=u),C7e(i,r)&&(i=eo(-i,r)),{isValid:d||f,value:i}}function OB(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function lJ(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?OB(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function uJ(e,t){t||(t=e.reduce((o,s)=>o+s.length,0));let r=lJ(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return OB(r)}function ePe(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}function FPe(e){return e.reduce((t,r)=>(t+=HPe[r],t),"")}function zPe(e){let t=[];for(let r of e){let n=$Pe[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}function hJ(e,t,r){t=t||[],r=r||0;for(var n=r;e>=ZPe;)t[r++]=e&255|$Y,e/=128;for(;e&KPe;)t[r++]=e&255|$Y,e>>>=7;return t[r]=e|0,hJ.bytes=r-n+1,t}function EB(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw EB.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&FY)<=YPe);return EB.bytes=s-n,r}function xJ(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}function OC(e,t="utf8"){let r=vJ[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}function Y2(e,t="utf8"){let r=vJ[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?OB(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function WY(e){return Fs(OC(Y2(e,NC),aJ))}function PC(e){return OC(Y2(yi(e),aJ),NC)}function U8(e){let t=Y2(Q7e,HY),r=J7e+OC(uJ([t,e]),HY);return[G7e,Y7e,r].join(Z7e)}function mNe(e){return OC(e,NC)}function gNe(e){return Y2(e,NC)}function yNe(e){return Y2([PC(e.header),PC(e.payload)].join(_C),cJ)}function wNe(e){return[PC(e.header),PC(e.payload),mNe(e.signature)].join(_C)}function Hl(e){let t=e.split(_C),r=WY(t[0]),n=WY(t[1]),o=gNe(t[2]),s=Y2(t.slice(0,2).join(_C),cJ);return{header:r,payload:n,signature:o,data:s}}function J2(e=YY(X7e)){let t=iJ.getPublicKey(e);return{secretKey:uJ([e,t]),publicKey:t}}async function BC(e,t,r,n,o=(0,KY.fromMiliseconds)(Date.now())){let s={alg:W7e,typ:K7e},i=U8(n.publicKey),a=o+r,c={iss:i,sub:e,aud:t,iat:o,exp:a},u=yNe({header:s,payload:c}),d=iJ.sign(u,n.secretKey.slice(0,32));return wNe({header:s,payload:c,signature:d})}var KY,G2,oB,fB,pB,CC,hB,j_e,q_e,W_e,K_e,Z_e,G_e,Y_e,J_e,Q_e,X_e,e7e,t7e,r7e,o7e,s7e,i7e,a7e,c7e,l7e,Ct,u7e,d7e,ah,ch,mB,f7e,IB,QY,p7e,h7e,ff,iB,w7e,b7e,go,Sn,O1,x7e,yB,BY,kY,C7e,S7e,DY,SC,lB,sJ,kc,wi,IC,k7e,U7e,RB,LY,M7e,MY,H7e,$7e,j7e,q7e,iJ,W7e,K7e,_C,NC,aJ,cJ,Z7e,G7e,Y7e,HY,J7e,Q7e,X7e,tPe,rPe,dJ,nPe,oPe,wB,bB,xB,fJ,vB,RC,k8,sPe,iPe,Mo,aPe,cPe,lPe,uPe,dPe,fPe,pPe,hPe,mPe,gPe,yPe,wPe,bPe,xPe,vPe,EPe,APe,CPe,SPe,IPe,TPe,_Pe,PPe,NPe,RPe,OPe,BPe,kPe,UPe,DPe,LPe,MPe,pJ,HPe,$Pe,VPe,jPe,qPe,$Y,WPe,KPe,ZPe,GPe,YPe,FY,JPe,QPe,XPe,eNe,tNe,rNe,nNe,oNe,sNe,iNe,aNe,mJ,zY,VY,AB,CB,gJ,SB,yJ,cNe,lNe,uNe,wJ,dNe,bJ,fNe,pNe,hNe,jY,qY,dB,vJ,B1=b(()=>{l();KY=Ht(jd());R1();G2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;oB=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);fB=class{clone(){return this._cloneInto()}};pB=class extends fB{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=oB(this.buffer)}update(t){PY(this);let{view:r,buffer:n,blockLen:o}=this;t=GY(t);let s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fBigInt(e>>>0)<>>0),q_e=(e,t,r)=>e>>>r,W_e=(e,t,r)=>e<<32-r|t>>>r,K_e=(e,t,r)=>e>>>r|t<<32-r,Z_e=(e,t,r)=>e<<32-r|t>>>r,G_e=(e,t,r)=>e<<64-r|t>>>r-32,Y_e=(e,t,r)=>e>>>r-32|t<<64-r,J_e=(e,t)=>t,Q_e=(e,t)=>e,X_e=(e,t,r)=>e<>>32-r,e7e=(e,t,r)=>t<>>32-r,t7e=(e,t,r)=>t<>>64-r,r7e=(e,t,r)=>e<>>64-r;o7e=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),s7e=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,i7e=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),a7e=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,c7e=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),l7e=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,Ct={fromBig:JY,split:V_e,toBig:j_e,shrSH:q_e,shrSL:W_e,rotrSH:K_e,rotrSL:Z_e,rotrBH:G_e,rotrBL:Y_e,rotr32H:J_e,rotr32L:Q_e,rotlSH:X_e,rotlSL:e7e,rotlBH:t7e,rotlBL:r7e,add:n7e,add3L:o7e,add3H:s7e,add4L:i7e,add4H:a7e,add5H:l7e,add5L:c7e},[u7e,d7e]=Ct.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),ah=new Uint32Array(80),ch=new Uint32Array(80),mB=class extends pB{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)ah[E]=t.getUint32(r),ch[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=ah[E-15]|0,_=ch[E-15]|0,O=Ct.rotrSH(S,_,1)^Ct.rotrSH(S,_,8)^Ct.shrSH(S,_,7),D=Ct.rotrSL(S,_,1)^Ct.rotrSL(S,_,8)^Ct.shrSL(S,_,7),M=ah[E-2]|0,N=ch[E-2]|0,L=Ct.rotrSH(M,N,19)^Ct.rotrBH(M,N,61)^Ct.shrSH(M,N,6),P=Ct.rotrSL(M,N,19)^Ct.rotrBL(M,N,61)^Ct.shrSL(M,N,6),R=Ct.add4L(D,P,ch[E-7],ch[E-16]),I=Ct.add4H(R,O,L,ah[E-7],ah[E-16]);ah[E]=I|0,ch[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Ct.rotrSH(f,p,14)^Ct.rotrSH(f,p,18)^Ct.rotrBH(f,p,41),_=Ct.rotrSL(f,p,14)^Ct.rotrSL(f,p,18)^Ct.rotrBL(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=Ct.add5L(T,_,D,d7e[E],ch[E]),N=Ct.add5H(M,v,S,O,u7e[E],ah[E]),L=M|0,P=Ct.rotrSH(n,o,28)^Ct.rotrBH(n,o,34)^Ct.rotrBH(n,o,39),R=Ct.rotrSL(n,o,28)^Ct.rotrBL(n,o,34)^Ct.rotrBL(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=Ct.add(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Ct.add3L(L,R,B);n=Ct.add3H(C,N,P,I),o=C|0}({h:n,l:o}=Ct.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ct.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ct.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=Ct.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=Ct.add(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=Ct.add(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=Ct.add(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=Ct.add(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){ah.fill(0),ch.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},f7e=F_e(()=>new mB);IB=BigInt(0),QY=BigInt(1),p7e=BigInt(2);h7e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));ff={_0:48,_9:57,A:65,F:70,a:97,f:102};iB=e=>typeof e=="bigint"&&IB<=e;w7e=e=>(p7e<typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||TB(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};go=BigInt(0),Sn=BigInt(1),O1=BigInt(2),x7e=BigInt(3),yB=BigInt(4),BY=BigInt(5),kY=BigInt(8);C7e=(e,t)=>(eo(e,t)&Sn)===Sn,S7e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];DY=BigInt(0),SC=BigInt(1);lB=new WeakMap,sJ=new WeakMap;kc=BigInt(0),wi=BigInt(1),IC=BigInt(2),k7e=BigInt(8),U7e={zip215:!0};BigInt(0),BigInt(1);RB=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),LY=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);M7e=BigInt(1),MY=BigInt(2);BigInt(3);H7e=BigInt(5),$7e=BigInt(8);j7e=nJ(RB,void 0,!0),q7e={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:j7e,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$7e,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:f7e,randomBytes:YY,adjustScalarBytes:z7e,uvRatio:V7e},iJ=L7e(q7e),W7e="EdDSA",K7e="JWT",_C=".",NC="base64url",aJ="utf8",cJ="utf8",Z7e=":",G7e="did",Y7e="key",HY="base58btc",J7e="z",Q7e="K36",X7e=32;tPe=ePe,rPe=tPe,dJ=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},nPe=e=>new TextEncoder().encode(e),oPe=e=>new TextDecoder().decode(e),wB=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},bB=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return fJ(this,t)}},xB=class{constructor(t){this.decoders=t}or(t){return fJ(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},fJ=(e,t)=>new xB({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),vB=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new wB(t,r,n),this.decoder=new bB(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},RC=({name:e,prefix:t,encode:r,decode:n})=>new vB(e,t,r,n),k8=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=rPe(r,t);return RC({prefix:e,name:t,encode:n,decode:s=>dJ(o(s))})},sPe=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},iPe=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<RC({prefix:t,name:e,encode(o){return iPe(o,n,r)},decode(o){return sPe(o,n,r,e)}}),aPe=RC({prefix:"\0",name:"identity",encode:e=>oPe(e),decode:e=>nPe(e)}),cPe=Object.freeze({__proto__:null,identity:aPe}),lPe=Mo({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),uPe=Object.freeze({__proto__:null,base2:lPe}),dPe=Mo({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fPe=Object.freeze({__proto__:null,base8:dPe}),pPe=k8({prefix:"9",name:"base10",alphabet:"0123456789"}),hPe=Object.freeze({__proto__:null,base10:pPe}),mPe=Mo({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gPe=Mo({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),yPe=Object.freeze({__proto__:null,base16:mPe,base16upper:gPe}),wPe=Mo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bPe=Mo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xPe=Mo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vPe=Mo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EPe=Mo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),APe=Mo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CPe=Mo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SPe=Mo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IPe=Mo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),TPe=Object.freeze({__proto__:null,base32:wPe,base32upper:bPe,base32pad:xPe,base32padupper:vPe,base32hex:EPe,base32hexupper:APe,base32hexpad:CPe,base32hexpadupper:SPe,base32z:IPe}),_Pe=k8({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),PPe=k8({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),NPe=Object.freeze({__proto__:null,base36:_Pe,base36upper:PPe}),RPe=k8({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OPe=k8({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),BPe=Object.freeze({__proto__:null,base58btc:RPe,base58flickr:OPe}),kPe=Mo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),UPe=Mo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),DPe=Mo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),LPe=Mo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),MPe=Object.freeze({__proto__:null,base64:kPe,base64pad:UPe,base64url:DPe,base64urlpad:LPe}),pJ=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),HPe=pJ.reduce((e,t,r)=>(e[r]=t,e),[]),$Pe=pJ.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);VPe=RC({prefix:"\u{1F680}",name:"base256emoji",encode:FPe,decode:zPe}),jPe=Object.freeze({__proto__:null,base256emoji:VPe}),qPe=hJ,$Y=128,WPe=127,KPe=~WPe,ZPe=Math.pow(2,31);GPe=EB,YPe=128,FY=127;JPe=Math.pow(2,7),QPe=Math.pow(2,14),XPe=Math.pow(2,21),eNe=Math.pow(2,28),tNe=Math.pow(2,35),rNe=Math.pow(2,42),nNe=Math.pow(2,49),oNe=Math.pow(2,56),sNe=Math.pow(2,63),iNe=function(e){return e(mJ.encode(e,t,r),t),VY=e=>mJ.encodingLength(e),AB=(e,t)=>{let r=t.byteLength,n=VY(e),o=n+VY(r),s=new Uint8Array(o+r);return zY(e,s,0),zY(r,s,n),s.set(t,o),new CB(e,r,t,s)},CB=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}},gJ=({name:e,code:t,encode:r})=>new SB(e,t,r),SB=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?AB(this.code,r):r.then(n=>AB(this.code,n))}else throw Error("Unknown type, must be binary type")}},yJ=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cNe=gJ({name:"sha2-256",code:18,encode:yJ("SHA-256")}),lNe=gJ({name:"sha2-512",code:19,encode:yJ("SHA-512")}),uNe=Object.freeze({__proto__:null,sha256:cNe,sha512:lNe}),wJ=0,dNe="identity",bJ=dJ,fNe=e=>AB(wJ,bJ(e)),pNe={code:wJ,name:dNe,encode:bJ,digest:fNe},hNe=Object.freeze({__proto__:null,identity:pNe});new TextEncoder,new TextDecoder;jY={...cPe,...uPe,...fPe,...hPe,...yPe,...TPe,...NPe,...BPe,...MPe,...jPe};({...uNe,...hNe});qY=xJ("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),dB=xJ("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=lJ(e.length);for(let r=0;r{l();kC={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var kB=_e((Ift,AJ)=>{l();var bNe="Input must be an string, Buffer or Uint8Array";function xNe(e){let t;if(e instanceof Uint8Array)t=e;else if(typeof e=="string")t=new TextEncoder().encode(e);else throw new Error(bNe);return t}function vNe(e){return Array.prototype.map.call(e,function(t){return(t<16?"0":"")+t.toString(16)}).join("")}function UC(e){return(4294967296+e).toString(16).substring(1)}function ENe(e,t,r){let n=` +`});var PG=b(()=>{l();_G();lC();rh();TO();C8()});var NO,Put,NG=b(()=>{l();nG();oG();sG();iG();aG();wO();cG();vO();lG();dG();xG();AG();CG();SG();PG();NO={...fO,...pO,...hO,...mO,...gO,...yO,...bO,...xO,...EO,...AO},Put={..._O,...PO}});function OG(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var RG,RO,DTe,pC,OO=b(()=>{l();NG();aC();RG=OG("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),RO=OG("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=x8(e.length);for(let r=0;r{l();OO();b8()});function Ut(e,t="utf8"){let r=pC[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var BG=b(()=>{l();OO()});var kG=b(()=>{l();aC();b8()});var I8=b(()=>{l();KZ();ZZ();GZ();BO();BG();kG()});function Fs(e){if(typeof e!="string")throw new Error(`Cannot safe json parse value of type ${typeof e}`);try{return L_e(e)}catch{return e}}function wi(e){return typeof e=="string"?e:D_e(e)||""}var D_e,L_e,R1=b(()=>{l();D_e=e=>JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString()+"n":r),L_e=e=>{let t=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=e.replace(t,'$1"$2n"$3');return JSON.parse(r,(n,o)=>typeof o=="string"&&o.match(/^\d+n$/)?BigInt(o.substring(0,o.length-1)):o)}});function M_e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ZY(e,...t){if(!M_e(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function PY(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function H_e(e,t){ZY(e);let r=t.outputLen;if(e.lengthe().update(GY(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function YY(e=32){if(G2&&typeof G2.getRandomValues=="function")return G2.getRandomValues(new Uint8Array(e));if(G2&&typeof G2.randomBytes=="function")return G2.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function z_e(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function JY(e,t=!1){return t?{h:Number(e&CC),l:Number(e>>hB&CC)}:{h:Number(e>>hB&CC)|0,l:Number(e&CC)|0}}function V_e(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;o>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}function TB(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function _B(e){if(!TB(e))throw new Error("Uint8Array expected")}function sB(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function PB(e){_B(e);let t="";for(let r=0;r=ff._0&&e<=ff._9)return e-ff._0;if(e>=ff.A&&e<=ff.F)return e-(ff.A-10);if(e>=ff.a&&e<=ff.f)return e-(ff.a-10)}function eJ(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oIB;e>>=QY,t+=1);return t}function NB(e,t,r={}){let n=(o,s,i)=>{let a=b7e[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function OY(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}function eo(e,t){let r=e%t;return r>=go?r:t+r}function v7e(e,t,r){if(tgo;)t&Sn&&(n=n*e%r),e=e*e%r,t>>=Sn;return n}function Ml(e,t,r){let n=e;for(;t-- >go;)n*=n,n%=r;return n}function UY(e,t){if(e===go)throw new Error("invert: expected non-zero number");if(t<=go)throw new Error("invert: expected positive modulus, got "+t);let r=eo(e,t),n=t,o=go,s=Sn;for(;r!==go;){let i=n/r,a=n%r,c=o-s*i;n=r,r=a,o=s,s=c}if(n!==Sn)throw new Error("invert: does not exist");return eo(o,t)}function E7e(e){let t=(e-Sn)/O1,r,n,o;for(r=e-Sn,n=0;r%O1===go;r/=O1,n++);for(o=O1;o1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(e+Sn)/yB;return function(a,c){let u=a.pow(c,i);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}let s=(r+Sn)/O1;return function(i,a){if(i.pow(a,t)===i.neg(i.ONE))throw new Error("Cannot find square root");let c=n,u=i.pow(i.mul(i.ONE,o),r),d=i.pow(a,s),f=i.pow(a,r);for(;!i.eql(f,i.ONE);){if(i.eql(f,i.ZERO))return i.ZERO;let p=1;for(let y=i.sqr(f);p(n[o]="function",n),t);return NB(e,r)}function T7e(e,t,r){if(rgo;)r&Sn&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Sn;return n}function _7e(e,t){let r=new Array(t.length),n=t.reduce((s,i,a)=>e.is0(i)?s:(r[a]=s,e.mul(s,i)),e.ONE),o=e.inv(n);return t.reduceRight((s,i,a)=>e.is0(i)?s:(r[a]=e.mul(s,r[a]),e.mul(s,i)),o),r}function rJ(e,t){let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function nJ(e,t,r=!1,n={}){if(e<=go)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=rJ(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:w7e(o),ZERO:go,ONE:Sn,create:c=>eo(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return go<=c&&cc===go,isOdd:c=>(c&Sn)===Sn,neg:c=>eo(-c,e),eql:(c,u)=>c===u,sqr:c=>eo(c*c,e),add:(c,u)=>eo(c+u,e),sub:(c,u)=>eo(c-u,e),mul:(c,u)=>eo(c*u,e),pow:(c,u)=>T7e(a,c,u),div:(c,u)=>eo(c*UY(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>UY(c,e),sqrt:n.sqrt||(c=>(i||(i=A7e(e)),i(a,c))),invertBatch:c=>_7e(a,c),cmov:(c,u,d)=>d?u:c,toBytes:c=>r?gB(c,s):tJ(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?TC(c):m7e(c)}});return Object.freeze(a)}function aB(e,t){let r=t.negate();return e?r:t}function oJ(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function cB(e,t){oJ(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1);return{windows:r,windowSize:n}}function P7e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function N7e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function uB(e){return sJ.get(e)||1}function R7e(e,t){return{constTimeNegate:aB,hasPrecomputes(r){return uB(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>DY;)n&SC&&(o=o.add(s)),s=s.double(),n>>=SC;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=cB(n,t),i=[],a=r,c=a;for(let u=0;u>=f,y>i&&(y-=d,o+=SC);let w=h,x=h+Math.abs(y)-1,v=p%2!==0,T=y<0;y===0?c=c.add(aB(v,n[w])):a=a.add(aB(T,n[x]))}return{p:a,f:c}},wNAFUnsafe(r,n,o,s=e.ZERO){let{windows:i,windowSize:a}=cB(r,t),c=BigInt(2**r-1),u=2**r,d=BigInt(r);for(let f=0;f>=d,h>a&&(h-=u,o+=SC),h===0)continue;let y=n[p+Math.abs(h)-1];h<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(r,n,o){let s=lB.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&lB.set(n,o(s))),s},wNAFCached(r,n,o){let s=uB(r);return this.wNAF(s,this.getPrecomputes(s,r,o),n)},wNAFCachedUnsafe(r,n,o,s){let i=uB(r);return i===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,r,o),n,s)},setWindowSize(r,n){oJ(n,t),sJ.set(r,n),lB.delete(r)}}}function O7e(e,t,r,n){if(P7e(r,e),N7e(n,t),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=e.ZERO,s=y7e(BigInt(r.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<=0;f-=i){c.fill(o);for(let h=0;h>BigInt(f)&BigInt(a));c[w]=c[w].add(r[h])}let p=o;for(let h=c.length-1,y=o;h>0;h--)y=y.add(c[h]),p=p.add(y);if(d=d.add(p),f!==0)for(let h=0;h{try{return{isValid:!0,value:r.sqrt(C*r.inv(A))}}catch{return{isValid:!1,value:kc}}}),h=t.adjustScalarBytes||(C=>C),y=t.domain||((C,A,U)=>{if(sB("phflag",U),A.length||U)throw new Error("Contexts/pre-hash are not supported");return C});function w(C,A){B8("coordinate "+C,A,kc,u)}function x(C){if(!(C instanceof E))throw new Error("ExtendedPoint expected")}let v=OY((C,A)=>{let{ex:U,ey:H,ez:k}=C,F=C.is0();A==null&&(A=F?k7e:r.inv(k));let j=d(U*A),W=d(H*A),ae=d(k*A);if(F)return{x:kc,y:bi};if(ae!==bi)throw new Error("invZ was invalid");return{x:j,y:W}}),T=OY(C=>{let{a:A,d:U}=t;if(C.is0())throw new Error("bad point: ZERO");let{ex:H,ey:k,ez:F,et:j}=C,W=d(H*H),ae=d(k*k),te=d(F*F),X=d(te*te),pe=d(W*A),me=d(te*d(pe+ae)),Ne=d(X+d(U*d(W*ae)));if(me!==Ne)throw new Error("bad point: equation left != right (1)");let ye=d(H*k),Re=d(F*j);if(ye!==Re)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(A,U,H,k){this.ex=A,this.ey=U,this.ez=H,this.et=k,w("x",A),w("y",U),w("z",H),w("t",k),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof E)throw new Error("extended point not allowed");let{x:U,y:H}=A||{};return w("x",U),w("y",H),new E(U,H,bi,d(U*H))}static normalizeZ(A){let U=r.invertBatch(A.map(H=>H.ez));return A.map((H,k)=>H.toAffine(U[k])).map(E.fromAffine)}static msm(A,U){return O7e(E,f,A,U)}_setWindowSize(A){O.setWindowSize(this,A)}assertValidity(){T(this)}equals(A){x(A);let{ex:U,ey:H,ez:k}=this,{ex:F,ey:j,ez:W}=A,ae=d(U*W),te=d(F*k),X=d(H*W),pe=d(j*k);return ae===te&&X===pe}is0(){return this.equals(E.ZERO)}negate(){return new E(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:A}=t,{ex:U,ey:H,ez:k}=this,F=d(U*U),j=d(H*H),W=d(IC*d(k*k)),ae=d(A*F),te=U+H,X=d(d(te*te)-F-j),pe=ae+j,me=pe-W,Ne=ae-j,ye=d(X*me),Re=d(pe*Ne),Et=d(X*Ne),kt=d(me*pe);return new E(ye,Re,kt,Et)}add(A){x(A);let{a:U,d:H}=t,{ex:k,ey:F,ez:j,et:W}=this,{ex:ae,ey:te,ez:X,et:pe}=A;if(U===BigInt(-1)){let nW=d((F-k)*(te+ae)),oW=d((F+k)*(te-ae)),FN=d(oW-nW);if(FN===kc)return this.double();let sW=d(j*IC*pe),iW=d(W*IC*X),aW=iW+sW,cW=oW+nW,lW=iW-sW,SCe=d(aW*FN),ICe=d(cW*lW),TCe=d(aW*lW),_Ce=d(FN*cW);return new E(SCe,ICe,_Ce,TCe)}let me=d(k*ae),Ne=d(F*te),ye=d(W*H*pe),Re=d(j*X),Et=d((k+F)*(ae+te)-me-Ne),kt=Re-ye,At=Re+ye,ur=d(Ne-U*me),_r=d(Et*kt),Pl=d(At*ur),ACe=d(Et*ur),CCe=d(kt*At);return new E(_r,Pl,CCe,ACe)}subtract(A){return this.add(A.negate())}wNAF(A){return O.wNAFCached(this,A,E.normalizeZ)}multiply(A){let U=A;B8("scalar",U,bi,n);let{p:H,f:k}=this.wNAF(U);return E.normalizeZ([H,k])[0]}multiplyUnsafe(A,U=E.ZERO){let H=A;return B8("scalar",H,kc,n),H===kc?_:this.is0()||H===bi?this:O.wNAFCachedUnsafe(this,H,E.normalizeZ,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(A){return v(this,A)}clearCofactor(){let{h:A}=t;return A===bi?this:this.multiplyUnsafe(A)}static fromHex(A,U=!1){let{d:H,a:k}=t,F=r.BYTES;A=pf("pointHex",A,F),sB("zip215",U);let j=A.slice(),W=A[F-1];j[F-1]=W&-129;let ae=TC(j),te=U?u:r.ORDER;B8("pointHex.y",ae,kc,te);let X=d(ae*ae),pe=d(X-bi),me=d(H*X-k),{isValid:Ne,value:ye}=p(pe,me);if(!Ne)throw new Error("Point.fromHex: invalid y coordinate");let Re=(ye&bi)===bi,Et=(W&128)!==0;if(!U&&ye===kc&&Et)throw new Error("Point.fromHex: x=0 and x_0=1");return Et!==Re&&(ye=d(-ye)),E.fromAffine({x:ye,y:ae})}static fromPrivateKey(A){return N(A).point}toRawBytes(){let{x:A,y:U}=this.toAffine(),H=gB(U,r.BYTES);return H[H.length-1]|=A&bi?128:0,H}toHex(){return PB(this.toRawBytes())}}E.BASE=new E(t.Gx,t.Gy,bi,d(t.Gx*t.Gy)),E.ZERO=new E(kc,bi,bi,kc);let{BASE:S,ZERO:_}=E,O=R7e(E,a*8);function D(C){return eo(C,n)}function M(C){return D(TC(C))}function N(C){let A=r.BYTES;C=pf("private key",C,A);let U=pf("hashed private key",s(C),2*A),H=h(U.slice(0,A)),k=U.slice(A,2*A),F=M(H),j=S.multiply(F),W=j.toRawBytes();return{head:H,prefix:k,scalar:F,point:j,pointBytes:W}}function L(C){return N(C).pointBytes}function P(C=new Uint8Array,...A){let U=RY(...A);return M(s(y(U,pf("context",C),!!o)))}function R(C,A,U={}){C=pf("message",C),o&&(C=o(C));let{prefix:H,scalar:k,pointBytes:F}=N(A),j=P(U.context,H,C),W=S.multiply(j).toRawBytes(),ae=P(U.context,W,F,C),te=D(j+ae*k);B8("signature.s",te,kc,n);let X=RY(W,gB(te,r.BYTES));return pf("result",X,r.BYTES*2)}let I=U7e;function B(C,A,U,H=I){let{context:k,zip215:F}=H,j=r.BYTES;C=pf("signature",C,2*j),A=pf("message",A),U=pf("publicKey",U,j),F!==void 0&&sB("zip215",F),o&&(A=o(A));let W=TC(C.slice(j,2*j)),ae,te,X;try{ae=E.fromHex(U,F),te=E.fromHex(C.slice(0,j),F),X=S.multiplyUnsafe(W)}catch{return!1}if(!F&&ae.isSmallOrder())return!1;let pe=P(k,te.toRawBytes(),ae.toRawBytes(),A);return te.add(ae.multiplyUnsafe(pe)).subtract(X).clearCofactor().equals(E.ZERO)}return S._setWindowSize(8),{CURVE:t,getPublicKey:L,sign:R,verify:B,ExtendedPoint:E,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(r.BYTES),precompute(C=8,A=E.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}}}}function F7e(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=RB,i=e*e%s*e%s,a=Ml(i,MY,s)*i%s,c=Ml(a,M7e,s)*e%s,u=Ml(c,H7e,s)*c%s,d=Ml(u,t,s)*u%s,f=Ml(d,r,s)*d%s,p=Ml(f,n,s)*f%s,h=Ml(p,o,s)*p%s,y=Ml(h,o,s)*p%s,w=Ml(y,t,s)*u%s;return{pow_p_5_8:Ml(w,MY,s)*e%s,b2:i}}function z7e(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function V7e(e,t){let r=RB,n=eo(t*t*t,r),o=eo(n*n*t,r),s=F7e(e*o).pow_p_5_8,i=eo(e*n*s,r),a=eo(t*i*i,r),c=i,u=eo(i*LY,r),d=a===e,f=a===eo(-e,r),p=a===eo(-e*LY,r);return d&&(i=c),(f||p)&&(i=u),C7e(i,r)&&(i=eo(-i,r)),{isValid:d||f,value:i}}function OB(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function lJ(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?OB(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function uJ(e,t){t||(t=e.reduce((o,s)=>o+s.length,0));let r=lJ(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return OB(r)}function ePe(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}function FPe(e){return e.reduce((t,r)=>(t+=HPe[r],t),"")}function zPe(e){let t=[];for(let r of e){let n=$Pe[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}function hJ(e,t,r){t=t||[],r=r||0;for(var n=r;e>=ZPe;)t[r++]=e&255|$Y,e/=128;for(;e&KPe;)t[r++]=e&255|$Y,e>>>=7;return t[r]=e|0,hJ.bytes=r-n+1,t}function EB(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw EB.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&FY)<=YPe);return EB.bytes=s-n,r}function xJ(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}function OC(e,t="utf8"){let r=vJ[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}function Y2(e,t="utf8"){let r=vJ[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?OB(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function WY(e){return Fs(OC(Y2(e,NC),aJ))}function PC(e){return OC(Y2(wi(e),aJ),NC)}function U8(e){let t=Y2(Q7e,HY),r=J7e+OC(uJ([t,e]),HY);return[G7e,Y7e,r].join(Z7e)}function mNe(e){return OC(e,NC)}function gNe(e){return Y2(e,NC)}function yNe(e){return Y2([PC(e.header),PC(e.payload)].join(_C),cJ)}function wNe(e){return[PC(e.header),PC(e.payload),mNe(e.signature)].join(_C)}function Hl(e){let t=e.split(_C),r=WY(t[0]),n=WY(t[1]),o=gNe(t[2]),s=Y2(t.slice(0,2).join(_C),cJ);return{header:r,payload:n,signature:o,data:s}}function J2(e=YY(X7e)){let t=iJ.getPublicKey(e);return{secretKey:uJ([e,t]),publicKey:t}}async function BC(e,t,r,n,o=(0,KY.fromMiliseconds)(Date.now())){let s={alg:W7e,typ:K7e},i=U8(n.publicKey),a=o+r,c={iss:i,sub:e,aud:t,iat:o,exp:a},u=yNe({header:s,payload:c}),d=iJ.sign(u,n.secretKey.slice(0,32));return wNe({header:s,payload:c,signature:d})}var KY,G2,oB,fB,pB,CC,hB,j_e,q_e,W_e,K_e,Z_e,G_e,Y_e,J_e,Q_e,X_e,e7e,t7e,r7e,o7e,s7e,i7e,a7e,c7e,l7e,Ct,u7e,d7e,ah,ch,mB,f7e,IB,QY,p7e,h7e,ff,iB,w7e,b7e,go,Sn,O1,x7e,yB,BY,kY,C7e,S7e,DY,SC,lB,sJ,kc,bi,IC,k7e,U7e,RB,LY,M7e,MY,H7e,$7e,j7e,q7e,iJ,W7e,K7e,_C,NC,aJ,cJ,Z7e,G7e,Y7e,HY,J7e,Q7e,X7e,tPe,rPe,dJ,nPe,oPe,wB,bB,xB,fJ,vB,RC,k8,sPe,iPe,Mo,aPe,cPe,lPe,uPe,dPe,fPe,pPe,hPe,mPe,gPe,yPe,wPe,bPe,xPe,vPe,EPe,APe,CPe,SPe,IPe,TPe,_Pe,PPe,NPe,RPe,OPe,BPe,kPe,UPe,DPe,LPe,MPe,pJ,HPe,$Pe,VPe,jPe,qPe,$Y,WPe,KPe,ZPe,GPe,YPe,FY,JPe,QPe,XPe,eNe,tNe,rNe,nNe,oNe,sNe,iNe,aNe,mJ,zY,VY,AB,CB,gJ,SB,yJ,cNe,lNe,uNe,wJ,dNe,bJ,fNe,pNe,hNe,jY,qY,dB,vJ,B1=b(()=>{l();KY=Ht(jd());R1();G2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;oB=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);fB=class{clone(){return this._cloneInto()}};pB=class extends fB{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=oB(this.buffer)}update(t){PY(this);let{view:r,buffer:n,blockLen:o}=this;t=GY(t);let s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;fBigInt(e>>>0)<>>0),q_e=(e,t,r)=>e>>>r,W_e=(e,t,r)=>e<<32-r|t>>>r,K_e=(e,t,r)=>e>>>r|t<<32-r,Z_e=(e,t,r)=>e<<32-r|t>>>r,G_e=(e,t,r)=>e<<64-r|t>>>r-32,Y_e=(e,t,r)=>e>>>r-32|t<<64-r,J_e=(e,t)=>t,Q_e=(e,t)=>e,X_e=(e,t,r)=>e<>>32-r,e7e=(e,t,r)=>t<>>32-r,t7e=(e,t,r)=>t<>>64-r,r7e=(e,t,r)=>e<>>64-r;o7e=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),s7e=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,i7e=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),a7e=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,c7e=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),l7e=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,Ct={fromBig:JY,split:V_e,toBig:j_e,shrSH:q_e,shrSL:W_e,rotrSH:K_e,rotrSL:Z_e,rotrBH:G_e,rotrBL:Y_e,rotr32H:J_e,rotr32L:Q_e,rotlSH:X_e,rotlSL:e7e,rotlBH:t7e,rotlBL:r7e,add:n7e,add3L:o7e,add3H:s7e,add4L:i7e,add4H:a7e,add5H:l7e,add5L:c7e},[u7e,d7e]=Ct.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),ah=new Uint32Array(80),ch=new Uint32Array(80),mB=class extends pB{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)ah[E]=t.getUint32(r),ch[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=ah[E-15]|0,_=ch[E-15]|0,O=Ct.rotrSH(S,_,1)^Ct.rotrSH(S,_,8)^Ct.shrSH(S,_,7),D=Ct.rotrSL(S,_,1)^Ct.rotrSL(S,_,8)^Ct.shrSL(S,_,7),M=ah[E-2]|0,N=ch[E-2]|0,L=Ct.rotrSH(M,N,19)^Ct.rotrBH(M,N,61)^Ct.shrSH(M,N,6),P=Ct.rotrSL(M,N,19)^Ct.rotrBL(M,N,61)^Ct.shrSL(M,N,6),R=Ct.add4L(D,P,ch[E-7],ch[E-16]),I=Ct.add4H(R,O,L,ah[E-7],ah[E-16]);ah[E]=I|0,ch[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Ct.rotrSH(f,p,14)^Ct.rotrSH(f,p,18)^Ct.rotrBH(f,p,41),_=Ct.rotrSL(f,p,14)^Ct.rotrSL(f,p,18)^Ct.rotrBL(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=Ct.add5L(T,_,D,d7e[E],ch[E]),N=Ct.add5H(M,v,S,O,u7e[E],ah[E]),L=M|0,P=Ct.rotrSH(n,o,28)^Ct.rotrBH(n,o,34)^Ct.rotrBH(n,o,39),R=Ct.rotrSL(n,o,28)^Ct.rotrBL(n,o,34)^Ct.rotrBL(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=Ct.add(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Ct.add3L(L,R,B);n=Ct.add3H(C,N,P,I),o=C|0}({h:n,l:o}=Ct.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ct.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ct.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=Ct.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=Ct.add(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=Ct.add(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=Ct.add(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=Ct.add(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){ah.fill(0),ch.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},f7e=F_e(()=>new mB);IB=BigInt(0),QY=BigInt(1),p7e=BigInt(2);h7e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));ff={_0:48,_9:57,A:65,F:70,a:97,f:102};iB=e=>typeof e=="bigint"&&IB<=e;w7e=e=>(p7e<typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||TB(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};go=BigInt(0),Sn=BigInt(1),O1=BigInt(2),x7e=BigInt(3),yB=BigInt(4),BY=BigInt(5),kY=BigInt(8);C7e=(e,t)=>(eo(e,t)&Sn)===Sn,S7e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];DY=BigInt(0),SC=BigInt(1);lB=new WeakMap,sJ=new WeakMap;kc=BigInt(0),bi=BigInt(1),IC=BigInt(2),k7e=BigInt(8),U7e={zip215:!0};BigInt(0),BigInt(1);RB=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),LY=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);M7e=BigInt(1),MY=BigInt(2);BigInt(3);H7e=BigInt(5),$7e=BigInt(8);j7e=nJ(RB,void 0,!0),q7e={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:j7e,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$7e,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:f7e,randomBytes:YY,adjustScalarBytes:z7e,uvRatio:V7e},iJ=L7e(q7e),W7e="EdDSA",K7e="JWT",_C=".",NC="base64url",aJ="utf8",cJ="utf8",Z7e=":",G7e="did",Y7e="key",HY="base58btc",J7e="z",Q7e="K36",X7e=32;tPe=ePe,rPe=tPe,dJ=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},nPe=e=>new TextEncoder().encode(e),oPe=e=>new TextDecoder().decode(e),wB=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},bB=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return fJ(this,t)}},xB=class{constructor(t){this.decoders=t}or(t){return fJ(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},fJ=(e,t)=>new xB({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),vB=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new wB(t,r,n),this.decoder=new bB(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},RC=({name:e,prefix:t,encode:r,decode:n})=>new vB(e,t,r,n),k8=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=rPe(r,t);return RC({prefix:e,name:t,encode:n,decode:s=>dJ(o(s))})},sPe=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},iPe=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<RC({prefix:t,name:e,encode(o){return iPe(o,n,r)},decode(o){return sPe(o,n,r,e)}}),aPe=RC({prefix:"\0",name:"identity",encode:e=>oPe(e),decode:e=>nPe(e)}),cPe=Object.freeze({__proto__:null,identity:aPe}),lPe=Mo({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),uPe=Object.freeze({__proto__:null,base2:lPe}),dPe=Mo({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fPe=Object.freeze({__proto__:null,base8:dPe}),pPe=k8({prefix:"9",name:"base10",alphabet:"0123456789"}),hPe=Object.freeze({__proto__:null,base10:pPe}),mPe=Mo({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gPe=Mo({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),yPe=Object.freeze({__proto__:null,base16:mPe,base16upper:gPe}),wPe=Mo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),bPe=Mo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xPe=Mo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vPe=Mo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EPe=Mo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),APe=Mo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CPe=Mo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SPe=Mo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IPe=Mo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),TPe=Object.freeze({__proto__:null,base32:wPe,base32upper:bPe,base32pad:xPe,base32padupper:vPe,base32hex:EPe,base32hexupper:APe,base32hexpad:CPe,base32hexpadupper:SPe,base32z:IPe}),_Pe=k8({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),PPe=k8({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),NPe=Object.freeze({__proto__:null,base36:_Pe,base36upper:PPe}),RPe=k8({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),OPe=k8({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),BPe=Object.freeze({__proto__:null,base58btc:RPe,base58flickr:OPe}),kPe=Mo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),UPe=Mo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),DPe=Mo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),LPe=Mo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),MPe=Object.freeze({__proto__:null,base64:kPe,base64pad:UPe,base64url:DPe,base64urlpad:LPe}),pJ=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),HPe=pJ.reduce((e,t,r)=>(e[r]=t,e),[]),$Pe=pJ.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);VPe=RC({prefix:"\u{1F680}",name:"base256emoji",encode:FPe,decode:zPe}),jPe=Object.freeze({__proto__:null,base256emoji:VPe}),qPe=hJ,$Y=128,WPe=127,KPe=~WPe,ZPe=Math.pow(2,31);GPe=EB,YPe=128,FY=127;JPe=Math.pow(2,7),QPe=Math.pow(2,14),XPe=Math.pow(2,21),eNe=Math.pow(2,28),tNe=Math.pow(2,35),rNe=Math.pow(2,42),nNe=Math.pow(2,49),oNe=Math.pow(2,56),sNe=Math.pow(2,63),iNe=function(e){return e(mJ.encode(e,t,r),t),VY=e=>mJ.encodingLength(e),AB=(e,t)=>{let r=t.byteLength,n=VY(e),o=n+VY(r),s=new Uint8Array(o+r);return zY(e,s,0),zY(r,s,n),s.set(t,o),new CB(e,r,t,s)},CB=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}},gJ=({name:e,code:t,encode:r})=>new SB(e,t,r),SB=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?AB(this.code,r):r.then(n=>AB(this.code,n))}else throw Error("Unknown type, must be binary type")}},yJ=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),cNe=gJ({name:"sha2-256",code:18,encode:yJ("SHA-256")}),lNe=gJ({name:"sha2-512",code:19,encode:yJ("SHA-512")}),uNe=Object.freeze({__proto__:null,sha256:cNe,sha512:lNe}),wJ=0,dNe="identity",bJ=dJ,fNe=e=>AB(wJ,bJ(e)),pNe={code:wJ,name:dNe,encode:bJ,digest:fNe},hNe=Object.freeze({__proto__:null,identity:pNe});new TextEncoder,new TextDecoder;jY={...cPe,...uPe,...fPe,...hPe,...yPe,...TPe,...NPe,...BPe,...MPe,...jPe};({...uNe,...hNe});qY=xJ("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),dB=xJ("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=lJ(e.length);for(let r=0;r{l();kC={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}}});var kB=_e((Ift,AJ)=>{l();var bNe="Input must be an string, Buffer or Uint8Array";function xNe(e){let t;if(e instanceof Uint8Array)t=e;else if(typeof e=="string")t=new TextEncoder().encode(e);else throw new Error(bNe);return t}function vNe(e){return Array.prototype.map.call(e,function(t){return(t<16?"0":"")+t.toString(16)}).join("")}function UC(e){return(4294967296+e).toString(16).substring(1)}function ENe(e,t,r){let n=` `+e+" = ";for(let o=0;o{l();var LC=kB();function DC(e,t,r){let n=e[t]+e[r],o=e[t+1]+e[r+1];n>=4294967296&&o++,e[t]=n,e[t+1]=o}function CJ(e,t,r,n){let o=e[t]+r;r<0&&(o+=4294967296);let s=e[t+1]+n;o>=4294967296&&s++,e[t]=o,e[t+1]=s}function SJ(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function lh(e,t,r,n,o,s){let i=D8[o],a=D8[o+1],c=D8[s],u=D8[s+1];DC(vt,e,t),CJ(vt,e,i,a);let d=vt[n]^vt[e],f=vt[n+1]^vt[e+1];vt[n]=f,vt[n+1]=d,DC(vt,r,n),d=vt[t]^vt[r],f=vt[t+1]^vt[r+1],vt[t]=d>>>24^f<<8,vt[t+1]=f>>>24^d<<8,DC(vt,e,t),CJ(vt,e,c,u),d=vt[n]^vt[e],f=vt[n+1]^vt[e+1],vt[n]=d>>>16^f<<16,vt[n+1]=f>>>16^d<<16,DC(vt,r,n),d=vt[t]^vt[r],f=vt[t+1]^vt[r+1],vt[t]=f>>>31^d<<1,vt[t+1]=d>>>31^f<<1}var IJ=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),CNe=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],os=new Uint8Array(CNe.map(function(e){return e*2})),vt=new Uint32Array(32),D8=new Uint32Array(32);function TJ(e,t){let r=0;for(r=0;r<16;r++)vt[r]=e.h[r],vt[r+16]=IJ[r];for(vt[24]=vt[24]^e.t,vt[25]=vt[25]^e.t/4294967296,t&&(vt[28]=~vt[28],vt[29]=~vt[29]),r=0;r<32;r++)D8[r]=SJ(e.b,4*r);for(r=0;r<12;r++)lh(0,8,16,24,os[r*16+0],os[r*16+1]),lh(2,10,18,26,os[r*16+2],os[r*16+3]),lh(4,12,20,28,os[r*16+4],os[r*16+5]),lh(6,14,22,30,os[r*16+6],os[r*16+7]),lh(0,10,20,30,os[r*16+8],os[r*16+9]),lh(2,12,22,24,os[r*16+10],os[r*16+11]),lh(4,14,16,26,os[r*16+12],os[r*16+13]),lh(6,8,18,28,os[r*16+14],os[r*16+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^vt[r]^vt[r+16]}var uh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function _J(e,t,r,n){if(e===0||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(n&&n.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");let o={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};uh.fill(0),uh[0]=e,t&&(uh[1]=t.length),uh[2]=1,uh[3]=1,r&&uh.set(r,32),n&&uh.set(n,48);for(let s=0;s<16;s++)o.h[s]=IJ[s]^SJ(uh,s*4);return t&&(UB(o,t),o.c=128),o}function UB(e,t){for(let r=0;r>2]>>8*(r&3);return t}function NJ(e,t,r,n,o){r=r||64,e=LC.normalizeInput(e),n&&(n=LC.normalizeInput(n)),o&&(o=LC.normalizeInput(o));let s=_J(r,t,n,o);return UB(s,e),PJ(s)}function SNe(e,t,r,n,o){let s=NJ(e,t,r,n,o);return LC.toHex(s)}RJ.exports={blake2b:NJ,blake2bHex:SNe,blake2bInit:_J,blake2bUpdate:UB,blake2bFinal:PJ}});var $J=_e((Nft,HJ)=>{l();var BJ=kB();function INe(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function dh(e,t,r,n,o,s){Xt[e]=Xt[e]+Xt[t]+o,Xt[n]=MC(Xt[n]^Xt[e],16),Xt[r]=Xt[r]+Xt[n],Xt[t]=MC(Xt[t]^Xt[r],12),Xt[e]=Xt[e]+Xt[t]+s,Xt[n]=MC(Xt[n]^Xt[e],8),Xt[r]=Xt[r]+Xt[n],Xt[t]=MC(Xt[t]^Xt[r],7)}function MC(e,t){return e>>>t^e<<32-t}var kJ=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ss=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),Xt=new Uint32Array(16),Ho=new Uint32Array(16);function UJ(e,t){let r=0;for(r=0;r<8;r++)Xt[r]=e.h[r],Xt[r+8]=kJ[r];for(Xt[12]^=e.t,Xt[13]^=e.t/4294967296,t&&(Xt[14]=~Xt[14]),r=0;r<16;r++)Ho[r]=INe(e.b,4*r);for(r=0;r<10;r++)dh(0,4,8,12,Ho[ss[r*16+0]],Ho[ss[r*16+1]]),dh(1,5,9,13,Ho[ss[r*16+2]],Ho[ss[r*16+3]]),dh(2,6,10,14,Ho[ss[r*16+4]],Ho[ss[r*16+5]]),dh(3,7,11,15,Ho[ss[r*16+6]],Ho[ss[r*16+7]]),dh(0,5,10,15,Ho[ss[r*16+8]],Ho[ss[r*16+9]]),dh(1,6,11,12,Ho[ss[r*16+10]],Ho[ss[r*16+11]]),dh(2,7,8,13,Ho[ss[r*16+12]],Ho[ss[r*16+13]]),dh(3,4,9,14,Ho[ss[r*16+14]],Ho[ss[r*16+15]]);for(r=0;r<8;r++)e.h[r]^=Xt[r]^Xt[r+8]}function DJ(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");let r=t?t.length:0;if(t&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");let n={h:new Uint32Array(kJ),b:new Uint8Array(64),c:0,t:0,outlen:e};return n.h[0]^=16842752^r<<8^e,r>0&&(DB(n,t),n.c=64),n}function DB(e,t){for(let r=0;r>2]>>8*(r&3)&255;return t}function MJ(e,t,r){r=r||32,e=BJ.normalizeInput(e);let n=DJ(r,t);return DB(n,e),LJ(n)}function TNe(e,t,r){let n=MJ(e,t,r);return BJ.toHex(n)}HJ.exports={blake2s:MJ,blake2sHex:TNe,blake2sInit:DJ,blake2sUpdate:DB,blake2sFinal:LJ}});var LB=_e((Oft,FJ)=>{l();var L8=OJ(),M8=$J();FJ.exports={blake2b:L8.blake2b,blake2bHex:L8.blake2bHex,blake2bInit:L8.blake2bInit,blake2bUpdate:L8.blake2bUpdate,blake2bFinal:L8.blake2bFinal,blake2s:M8.blake2s,blake2sHex:M8.blake2sHex,blake2sInit:M8.blake2sInit,blake2sUpdate:M8.blake2sUpdate,blake2sFinal:M8.blake2sFinal}});function _Ne(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}function NNe(e,t,r){var n=r&&r.stringify||_Ne,o=1;if(typeof e=="object"&&e!==null){var s=t.length+o;if(s===1)return e;var i=new Array(s);i[0]=n(e);for(var a=1;a-1?f:0,e.charCodeAt(h+1)){case 100:case 102:if(d>=c||t[d]==null)break;f=c||t[d]==null)break;f=c||t[d]===void 0)break;f",f=h+2,h++;break}u+=n(t[d]),f=h+2,h++;break;case 115:if(d>=c)break;f{n[o]=r[o]?r[o]:H8[o]||H8[ONe[o]||"log"]||Q2}),e[jB]=n}function kNe(e,t){return Array.isArray(e)?e.filter(function(r){return r!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function hf(e){e=e||{},e.browser=e.browser||{};let t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");let r=e.browser.write||H8;e.browser.write&&(e.browser.asObject=!0);let n=e.serializers||{},o=kNe(e.browser.serialize,n),s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let i=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(i);typeof r=="function"&&a.forEach(function(w){r[w]=r}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");let c=e.level||"info",u=Object.create(r);u.log||(u.log=Q2),BNe(u,a,r),VJ({},u),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:p,set:h});let d={transmit:t,serialize:o,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:zNe(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Q2};u.levels=UNe(e),u.level=c,u.isLevelEnabled=function(w){return this.levels.values[w]?this.levels.values[w]>=this.levels.values[this.level]:!1},u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=Q2,u.serializers=n,u._serialize=o,u._stdErrSerialize=s,u.child=function(...w){return y.call(this,d,...w)},t&&(u._logEvent=$B());function f(){return ph(this.level,this)}function p(){return this._level}function h(w){if(w!=="silent"&&!this.levels.values[w])throw Error("unknown level "+w);this._level=w,k1(this,d,u,"error"),k1(this,d,u,"fatal"),k1(this,d,u,"warn"),k1(this,d,u,"info"),k1(this,d,u,"debug"),k1(this,d,u,"trace"),i.forEach(x=>{k1(this,d,u,x)})}function y(w,x,v){if(!x)throw new Error("missing bindings for child Pino");v=v||{},o&&x.serializers&&(v.serializers=x.serializers);let T=v.serializers;if(o&&T){var E=Object.assign({},n,T),S=e.browser.serialize===!0?Object.keys(E):o;delete x.serializers,qB([x],S,E,this._stdErrSerialize)}function _(D){this._childLevel=(D._childLevel|0)+1,this.bindings=x,E&&(this.serializers=E,this._serialize=S),t&&(this._logEvent=$B([].concat(D._logEvent.bindings,x)))}_.prototype=this;let O=new _(this);return VJ(this,O),O.child=function(...D){return y.call(this,w,...D)},O.level=v.level||this.level,w.onChild(O),O}return u}function UNe(e){let t=e.customLevels||{},r=Object.assign({},hf.levels.values,t),n=Object.assign({},hf.levels.labels,DNe(t));return{values:r,labels:n}}function DNe(e){let t={};return Object.keys(e).forEach(function(r){t[e[r]]=r}),t}function LNe(e){let t=[];e.bindings&&t.push(e.bindings);let r=e[HB];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}function k1(e,t,r,n){if(Object.defineProperty(e,n,{value:ph(e.level,r)>ph(n,r)?Q2:r[jB][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===Q2){if(!t.transmit)return;let s=t.transmit.level||e.level,i=ph(s,r);if(ph(n,r)f}=o.formatters||{},a=r.slice(),c=a[0],u={},d=(e._childLevel|0)+1;if(d<1&&(d=1),n&&(u.time=n),s){let f=s(t,e.levels.values[t]);Object.assign(u,f)}else u.level=e.levels.values[t];if(o.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;d--&&typeof a[0]=="object";)Object.assign(u,a.shift());return[i(u),...a]}else{if(c!==null&&typeof c=="object"){for(;d--&&typeof a[0]=="object";)Object.assign(u,a.shift());c=a.length?zJ(a.shift(),a):void 0}else typeof c=="string"&&(c=zJ(a.shift(),a));return c!==void 0&&(u[o.messageKey]=c),[i(u)]}}function qB(e,t,r,n){for(let o in e)if(n&&e[o]instanceof Error)e[o]=hf.stdSerializers.err(e[o]);else if(typeof e[o]=="object"&&!Array.isArray(e[o])&&t)for(let s in e[o])t.indexOf(s)>-1&&s in r&&(e[o][s]=r[s](e[o][s]))}function FNe(e,t,r,n=!1){let o=t.send,s=t.ts,i=t.methodLevel,a=t.methodValue,c=t.val,u=e._logEvent.bindings;n||qB(r,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=r.filter(function(d){return u.indexOf(d)===-1}),e._logEvent.level.label=i,e._logEvent.level.value=a,o(i,e._logEvent,c),e._logEvent=$B(u)}function $B(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function jJ(e){let t={type:e.constructor.name,msg:e.message,stack:e.stack};for(let r in e)t[r]===void 0&&(t[r]=e[r]);return t}function zNe(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?ZJ:GJ}function HC(){return{}}function MB(e){return e}function Q2(){}function ZJ(){return!1}function GJ(){return Date.now()}function VNe(){return Math.round(Date.now()/1e3)}function jNe(){return new Date(Date.now()).toISOString()}function qNe(){function e(t){return typeof t<"u"&&t}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}function qJ(e){return typeof e=="string"?e:GNe(e)||""}function X2(e){return mh(hh({},e),{level:e?.level||WNe.level})}function lRe(e,t,r=VC){return e[r]=t,e}function sr(e,t=VC){return e[t]||""}function uRe(e,t,r=VC){let n=sr(e,r);return n.trim()?`${n}/${t}`:t}function Cr(e,t,r=VC){let n=uRe(e,t,r),o=e.child({context:n});return lRe(o,n,r)}function dRe(e){var t,r;let n=new zB((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:$l.exports(mh(hh({},e.opts),{level:"trace",browser:mh(hh({},(r=e.opts)==null?void 0:r.browser),{write:o=>n.write(o)})})),chunkLoggerController:n}}function fRe(e){var t,r;let n=new VB((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:$l.exports(mh(hh({},e.opts),{level:"trace",browser:mh(hh({},(r=e.opts)==null?void 0:r.browser),{write:o=>n.write(o)})}),n),chunkLoggerController:n}}function Fl(e){var t;if(typeof e.loggerOverride<"u"&&typeof e.loggerOverride!="string")return{logger:e.loggerOverride,chunkLoggerController:null};let r=mh(hh({},e.opts),{level:typeof e.loggerOverride=="string"?e.loggerOverride:(t=e.opts)==null?void 0:t.level});return typeof window<"u"?dRe(mh(hh({},e),{opts:r})):fRe(mh(hh({},e),{opts:r}))}var $l,PNe,zJ,H8,RNe,jB,HB,ONe,kft,WNe,VC,WB,KNe,ZNe,fh,FB,FC,GNe,YNe,JNe,$C,zC,QNe,XNe,eRe,zB,tRe,rRe,nRe,VB,oRe,sRe,iRe,WJ,aRe,cRe,KJ,hh,mh,gh=b(()=>{l();$l={exports:{}};PNe=NNe;zJ=PNe;$l.exports=hf;H8=qNe().console||{},RNe={mapHttpRequest:HC,mapHttpResponse:HC,wrapRequestSerializer:MB,wrapResponseSerializer:MB,wrapErrorSerializer:MB,req:HC,res:HC,err:jJ,errWithCause:jJ};jB=Symbol("pino.logFuncs"),HB=Symbol("pino.hierarchy"),ONe={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};hf.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},hf.stdSerializers=RNe,hf.stdTimeFunctions=Object.assign({},{nullTime:ZJ,epochTime:GJ,unixTime:VNe,isoTime:jNe});$l.exports.default=hf;kft=$l.exports.pino=hf,WNe={level:"info"},VC="custom_context",WB=1e3*1024,KNe=Object.defineProperty,ZNe=(e,t,r)=>t in e?KNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,fh=(e,t,r)=>ZNe(e,typeof t!="symbol"?t+"":t,r),FB=class{constructor(t){fh(this,"nodeValue"),fh(this,"sizeInBytes"),fh(this,"next"),this.nodeValue=t,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},FC=class{constructor(t){fh(this,"lengthInNodes"),fh(this,"sizeInBytes"),fh(this,"head"),fh(this,"tail"),fh(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=t,this.sizeInBytes=0}append(t){let r=new FB(t);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${t} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let t=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=t.size}toArray(){let t=[],r=this.head;for(;r!==null;)t.push(r.value),r=r.next;return t}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let t=this.head;return{next:()=>{if(!t)return{done:!0,value:null};let r=t.value;return t=t.next,{done:!1,value:r}}}}},GNe=e=>JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString()+"n":r);YNe=Object.defineProperty,JNe=(e,t,r)=>t in e?YNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$C=(e,t,r)=>JNe(e,typeof t!="symbol"?t+"":t,r),zC=class{constructor(t,r=WB){$C(this,"logs"),$C(this,"level"),$C(this,"levelValue"),$C(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=t??"error",this.levelValue=$l.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new FC(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(t,r){r===$l.exports.levels.values.error?console.error(t):r===$l.exports.levels.values.warn?console.warn(t):r===$l.exports.levels.values.debug?console.debug(t):r===$l.exports.levels.values.trace?console.trace(t):console.log(t)}appendToLogs(t){this.logs.append(qJ({timestamp:new Date().toISOString(),log:t}));let r=typeof t=="string"?JSON.parse(t).level:t.level;r>=this.levelValue&&this.forwardToConsole(t,r)}getLogs(){return this.logs}clearLogs(){this.logs=new FC(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(t){let r=this.getLogArray();return r.push(qJ({extraMetadata:t})),new Blob(r,{type:"application/json"})}},QNe=Object.defineProperty,XNe=(e,t,r)=>t in e?QNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,eRe=(e,t,r)=>XNe(e,typeof t!="symbol"?t+"":t,r),zB=class{constructor(t,r=WB){eRe(this,"baseChunkLogger"),this.baseChunkLogger=new zC(t,r)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}downloadLogsBlobInBrowser(t){let r=URL.createObjectURL(this.logsToBlob(t)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},tRe=Object.defineProperty,rRe=(e,t,r)=>t in e?tRe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,nRe=(e,t,r)=>rRe(e,typeof t!="symbol"?t+"":t,r),VB=class{constructor(t,r=WB){nRe(this,"baseChunkLogger"),this.baseChunkLogger=new zC(t,r)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}},oRe=Object.defineProperty,sRe=Object.defineProperties,iRe=Object.getOwnPropertyDescriptors,WJ=Object.getOwnPropertySymbols,aRe=Object.prototype.hasOwnProperty,cRe=Object.prototype.propertyIsEnumerable,KJ=(e,t,r)=>t in e?oRe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,hh=(e,t)=>{for(var r in t||(t={}))aRe.call(t,r)&&KJ(e,r,t[r]);if(WJ)for(var r of WJ(t))cRe.call(t,r)&&KJ(e,r,t[r]);return e},mh=(e,t)=>sRe(e,iRe(t))});var yo,oX=b(()=>{l();yo=class{}});var tS=b(()=>{l();oX()});var iX,rS,xk,sX,Vs,iw,vk=b(()=>{l();iX=Ht(ks()),rS=Ht(jd());tS();xk=class extends yo{constructor(t){super()}},sX=rS.FIVE_SECONDS,Vs={pulse:"heartbeat_pulse"},iw=class e extends xk{constructor(t){super(t),this.events=new iX.EventEmitter,this.interval=sX,this.interval=t?.interval||sX}static async init(t){let r=new e(t);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),(0,rS.toMiliseconds)(this.interval))}pulse(){this.events.emit(Vs.pulse)}}});function vOe(e,t){if(e==="__proto__"||e==="constructor"&&t&&typeof t=="object"&&"prototype"in t){EOe(e);return}return t}function EOe(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}function J8(e,t={}){if(typeof e!="string")return e;if(e[0]==='"'&&e[e.length-1]==='"'&&e.indexOf("\\")===-1)return e.slice(1,-1);let r=e.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!xOe.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(wOe.test(e)||bOe.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,vOe)}return JSON.parse(e)}catch(n){if(t.strict)throw n;return e}}var wOe,bOe,xOe,aX=b(()=>{l();wOe=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,bOe=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,xOe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function AOe(e){return!e||typeof e.then!="function"?Promise.resolve(e):e}function ro(e,...t){try{return AOe(e(...t))}catch(r){return Promise.reject(r)}}function COe(e){let t=typeof e;return e===null||t!=="object"&&t!=="function"}function SOe(e){let t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}function Q8(e){if(COe(e))return String(e);if(SOe(e)||Array.isArray(e))return JSON.stringify(e);if(typeof e.toJSON=="function")return Q8(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function cX(e){return typeof e=="string"?e:Ek+TOe(e)}function lX(e){return typeof e!="string"||!e.startsWith(Ek)?e:IOe(e.slice(Ek.length))}function IOe(e){return globalThis.Buffer?Buffer.from(e,"base64"):Uint8Array.from(globalThis.atob(e),t=>t.codePointAt(0))}function TOe(e){return globalThis.Buffer?Buffer.from(e).toString("base64"):globalThis.btoa(String.fromCodePoint(...e))}function bh(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Ak(e){return e.split(":").some(t=>t==="."||t==="..")}function uX(...e){return bh(e.join(":"))}function Ck(e){return e=bh(e),e?e+":":""}function dX(e,t){if(t===void 0)return!0;let r=0,n=e.indexOf(":");for(;n>-1;)r++,n=e.indexOf(":",n+1);return r<=t}function fX(e,t){return t?e.startsWith(t)&&e[e.length-1]!=="$":e[e.length-1]!=="$"}var Ek,pX=b(()=>{l();Ek="base64:"});function gX(e={}){let t={mounts:{"":e.driver||POe()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=f=>{let p=bh(f);if(!p||Ak(p))throw new Error(`[unstorage] Invalid key: ${JSON.stringify(f)}`);return p},n=f=>{let p=Ck(f);if(Ak(p))throw new Error(`[unstorage] Invalid base: ${JSON.stringify(f)}`);return p},o=f=>{for(let p of t.mountpoints)if(f.startsWith(p))return{base:p,relativeKey:f.slice(p.length),driver:t.mounts[p]};return{base:"",relativeKey:f,driver:t.mounts[""]}},s=(f,p)=>t.mountpoints.filter(h=>h.startsWith(f)||p&&f.startsWith(h)).map(h=>({relativeBase:f.length>h.length?f.slice(h.length):void 0,mountpoint:h,driver:t.mounts[h]})),i=(f,p)=>{if(t.watching){p=bh(p);for(let h of t.watchListeners)h(f,p)}},a=async()=>{if(!t.watching){t.watching=!0;for(let f in t.mounts)t.unwatch[f]=await hX(t.mounts[f],i,f)}},c=async()=>{if(t.watching){for(let f in t.unwatch)await t.unwatch[f]();t.unwatch={},t.watching=!1}},u=(f,p,h)=>{let y=new Map,w=x=>{let v=y.get(x.base);return v||(v={driver:x.driver,base:x.base,items:[]},y.set(x.base,v)),v};for(let x of f){let v=typeof x=="string",T=r(v?x:x.key),E=v?void 0:x.value,S=v||!x.options?p:{...p,...x.options},_=o(T);w(_).items.push({key:T,value:E,relativeKey:_.relativeKey,options:S})}return Promise.all([...y.values()].map(x=>h(x))).then(x=>x.flat())},d={async hasItem(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return ro(y.hasItem,h,p)},async getItem(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return ro(y.getItem,h,p).then(w=>J8(w))},async getItems(f,p={}){return u(f,p,h=>h.driver.getItems?ro(h.driver.getItems,h.items.map(y=>({key:y.relativeKey,options:y.options})),p).then(y=>y.map(w=>({key:uX(h.base,w.key),value:J8(w.value)}))):Promise.all(h.items.map(y=>ro(h.driver.getItem,y.relativeKey,y.options).then(w=>({key:y.key,value:J8(w)})))))},async getItemRaw(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return y.getItemRaw?ro(y.getItemRaw,h,p):ro(y.getItem,h,p).then(w=>lX(w))},async setItem(f,p,h={}){if(p===void 0)return d.removeItem(f);f=r(f);let{relativeKey:y,driver:w}=o(f);w.setItem&&(await ro(w.setItem,y,Q8(p),h),w.watch||i("update",f))},async setItems(f,p){await u(f,p,async h=>{if(h.driver.setItems)return ro(h.driver.setItems,h.items.map(y=>({key:y.relativeKey,value:Q8(y.value),options:y.options})),p);h.driver.setItem&&await Promise.all(h.items.map(y=>ro(h.driver.setItem,y.relativeKey,Q8(y.value),y.options)))})},async setItemRaw(f,p,h={}){if(p===void 0)return d.removeItem(f,h);f=r(f);let{relativeKey:y,driver:w}=o(f);if(w.setItemRaw)await ro(w.setItemRaw,y,p,h);else if(w.setItem)await ro(w.setItem,y,cX(p),h);else return;w.watch||i("update",f)},async removeItem(f,p={}){typeof p=="boolean"&&(p={removeMeta:p}),f=r(f);let{relativeKey:h,driver:y}=o(f);y.removeItem&&(await ro(y.removeItem,h,p),(p.removeMeta||p.removeMata)&&await ro(y.removeItem,h+"$",p),y.watch||i("remove",f))},async getMeta(f,p={}){typeof p=="boolean"&&(p={nativeOnly:p}),f=r(f);let{relativeKey:h,driver:y}=o(f),w=Object.create(null);if(y.getMeta&&Object.assign(w,await ro(y.getMeta,h,p)),!p.nativeOnly){let x=await ro(y.getItem,h+"$",p).then(v=>J8(v));x&&typeof x=="object"&&(typeof x.atime=="string"&&(x.atime=new Date(x.atime)),typeof x.mtime=="string"&&(x.mtime=new Date(x.mtime)),Object.assign(w,x))}return w},async setMeta(f,p,h={}){return this.setItem(r(f)+"$",p,h)},async removeMeta(f,p={}){return this.removeItem(r(f)+"$",p)},async getKeys(f,p={}){f=n(f);let h=s(f,!0),y=[],w=[],x=!0;for(let T of h){T.driver.flags?.maxDepth||(x=!1);let E=await ro(T.driver.getKeys,T.relativeBase,p);for(let S of E){let _=T.mountpoint+bh(S);y.some(O=>_.startsWith(O))||w.push(_)}y=[T.mountpoint,...y.filter(S=>!S.startsWith(T.mountpoint))]}let v=p.maxDepth!==void 0&&!x;return w.filter(T=>(!v||dX(T,p.maxDepth))&&fX(T,f))},async clear(f,p={}){f=n(f),await Promise.all(s(f,!1).map(async h=>{if(h.driver.clear)return ro(h.driver.clear,h.relativeBase,p);if(h.driver.removeItem){let y=await h.driver.getKeys(h.relativeBase||"",p);return Promise.all(y.map(w=>h.driver.removeItem(w,p)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(f=>mX(f)))},async watch(f){return await a(),t.watchListeners.push(f),async()=>{t.watchListeners=t.watchListeners.filter(p=>p!==f),t.watchListeners.length===0&&await c()}},async unwatch(){t.watchListeners=[],await c()},mount(f,p){if(f=n(f),f&&t.mounts[f])throw new Error(`already mounted at ${f}`);return f&&(t.mountpoints.push(f),t.mountpoints.sort((h,y)=>y.length-h.length)),t.mounts[f]=p,t.watching&&Promise.resolve(hX(p,i,f)).then(h=>{t.unwatch[f]=h}).catch(console.error),d},async unmount(f,p=!0){f=Ck(f),!(!f||!t.mounts[f])&&(t.watching&&f in t.unwatch&&(t.unwatch[f]?.(),delete t.unwatch[f]),p&&await mX(t.mounts[f]),t.mountpoints=t.mountpoints.filter(h=>h!==f),delete t.mounts[f])},getMount(f=""){f=bh(f)+":";let p=o(f);return{driver:p.driver,base:p.base}},getMounts(f="",p={}){return f=bh(f),s(f,p.parents).map(y=>({driver:y.driver,base:y.mountpoint}))},keys:(f,p={})=>d.getKeys(f,p),get:(f,p={})=>d.getItem(f,p),set:(f,p,h={})=>d.setItem(f,p,h),has:(f,p={})=>d.hasItem(f,p),del:(f,p={})=>d.removeItem(f,p),remove:(f,p={})=>d.removeItem(f,p)};return d}function hX(e,t,r){return e.watch?e.watch((n,o)=>t(n,r+o)):()=>{}}async function mX(e){typeof e.dispose=="function"&&await ro(e.dispose)}var _Oe,POe,yX=b(()=>{l();aX();pX();_Oe="memory",POe=()=>{let e=new Map;return{name:_Oe,getInstance:()=>e,hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,r){e.set(t,r)},setItemRaw(t,r){e.set(t,r)},removeItem(t){e.delete(t)},getKeys(){return[...e.keys()]},clear(){e.clear()},dispose(){e.clear()}}}});function $1(e){return new Promise((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})}function Ik(e,t){let r=indexedDB.open(e);r.onupgradeneeded=()=>r.result.createObjectStore(t);let n=$1(r);return(o,s)=>n.then(i=>s(i.transaction(t,o).objectStore(t)))}function X8(){return Sk||(Sk=Ik("keyval-store","keyval")),Sk}function Tk(e,t=X8()){return t("readonly",r=>$1(r.get(e)))}function wX(e,t,r=X8()){return r("readwrite",n=>(n.put(t,e),$1(n.transaction)))}function bX(e,t=X8()){return t("readwrite",r=>(r.delete(e),$1(r.transaction)))}function xX(e=X8()){return e("readwrite",t=>(t.clear(),$1(t.transaction)))}function NOe(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},$1(e.transaction)}function vX(e=X8()){return e("readonly",t=>{if(t.getAllKeys)return $1(t.getAllKeys());let r=[];return NOe(t,n=>r.push(n.key)).then(()=>r)})}var Sk,EX=b(()=>{l()});function UOe(e){var t;return[e[0],Fs((t=e[1])!=null?t:"")]}var ROe,OOe,BOe,kOe,Pk,_k,nS,Nk,DOe,AX,LOe,MOe,aw,Rk=b(()=>{l();yX();EX();R1();ROe="idb-keyval",OOe=(e={})=>{let t=e.base&&e.base.length>0?`${e.base}:`:"",r=o=>t+o,n;return e.dbName&&e.storeName&&(n=Ik(e.dbName,e.storeName)),{name:ROe,options:e,async hasItem(o){return!(typeof await Tk(r(o),n)>"u")},async getItem(o){return await Tk(r(o),n)??null},setItem(o,s){return wX(r(o),s,n)},removeItem(o){return bX(r(o),n)},getKeys(){return vX(n)},clear(){return xX(n)}}},BOe="WALLET_CONNECT_V2_INDEXED_DB",kOe="keyvaluestorage",Pk=class{constructor(){this.indexedDb=gX({driver:OOe({dbName:BOe,storeName:kOe})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(t=>[t.key,t.value])}async getItem(t){let r=await this.indexedDb.getItem(t);if(r!==null)return r}async setItem(t,r){await this.indexedDb.setItem(t,yi(r))}async removeItem(t){await this.indexedDb.removeItem(t)}},_k=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},nS={exports:{}};(function(){let e;function t(){}e=t,e.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},e.prototype.setItem=function(r,n){this[r]=String(n)},e.prototype.removeItem=function(r){delete this[r]},e.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},e.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},e.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof _k<"u"&&_k.localStorage?nS.exports=_k.localStorage:typeof window<"u"&&window.localStorage?nS.exports=window.localStorage:nS.exports=new t})();Nk=class{constructor(){this.localStorage=nS.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(UOe)}async getItem(t){let r=this.localStorage.getItem(t);if(r!==null)return Fs(r)}async setItem(t,r){this.localStorage.setItem(t,yi(r))}async removeItem(t){this.localStorage.removeItem(t)}},DOe="wc_storage_version",AX=1,LOe=async(e,t,r)=>{let n=DOe,o=await t.getItem(n);if(o&&o>=AX){r(t);return}let s=await e.getKeys();if(!s.length){r(t);return}let i=[];for(;s.length;){let a=s.shift();if(!a)continue;let c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){let u=await e.getItem(a);await t.setItem(a,u),i.push(a)}}await t.setItem(n,AX),r(t),MOe(e,i)},MOe=async(e,t)=>{t.length&&t.forEach(async r=>{await e.removeItem(r)})},aw=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let t=new Nk;this.storage=t;try{let r=new Pk;LOe(t,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(t){return await this.initialize(),this.storage.getItem(t)}async setItem(t,r){return await this.initialize(),this.storage.setItem(t,r)}async removeItem(t){return await this.initialize(),this.storage.removeItem(t)}async initialize(){this.initialized||await new Promise(t=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),t())},20)})}}});var SX,IX,TX,_X,yS,e4,Ok,wS,xh,t4,bS=b(()=>{l();SX="PARSE_ERROR",IX="INVALID_REQUEST",TX="METHOD_NOT_FOUND",_X="INVALID_PARAMS",yS="INTERNAL_ERROR",e4="SERVER_ERROR",Ok=[-32700,-32600,-32601,-32602,-32603],wS=[-32e3,-32099],xh={[SX]:{code:-32700,message:"Parse error"},[IX]:{code:-32600,message:"Invalid Request"},[TX]:{code:-32601,message:"Method not found"},[_X]:{code:-32602,message:"Invalid params"},[yS]:{code:-32603,message:"Internal error"},[e4]:{code:-32e3,message:"Server error"}},t4=e4});function HOe(e){return e<=wS[0]&&e>=wS[1]}function xS(e){return Ok.includes(e)}function PX(e){return typeof e=="number"}function vS(e){return Object.keys(xh).includes(e)?xh[e]:xh[t4]}function ES(e){let t=Object.values(xh).find(r=>r.code===e);return t||xh[t4]}function $Oe(e){if(typeof e.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof e.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!PX(e.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${e.error.code}`};if(xS(e.error.code)){let t=ES(e.error.code);if(t.message!==xh[t4].message&&e.error.message===t.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${e.error.code}`}}return{valid:!0}}function r4(e,t,r){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${t}`):e}var Bk=b(()=>{l();bS()});var RX=_e(vh=>{"use strict";l();Object.defineProperty(vh,"__esModule",{value:!0});vh.isBrowserCryptoAvailable=vh.getSubtleCrypto=vh.getBrowerCrypto=void 0;function kk(){return(global==null?void 0:global.crypto)||(global==null?void 0:global.msCrypto)||{}}vh.getBrowerCrypto=kk;function NX(){let e=kk();return e.subtle||e.webkitSubtle}vh.getSubtleCrypto=NX;function FOe(){return!!kk()&&!!NX()}vh.isBrowserCryptoAvailable=FOe});var kX=_e(Eh=>{"use strict";l();Object.defineProperty(Eh,"__esModule",{value:!0});Eh.isBrowser=Eh.isNode=Eh.isReactNative=void 0;function OX(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Eh.isReactNative=OX;function BX(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Eh.isNode=BX;function zOe(){return!OX()&&!BX()}Eh.isBrowser=zOe});var Uk=_e(AS=>{"use strict";l();Object.defineProperty(AS,"__esModule",{value:!0});var UX=(b2(),Yx(w2));UX.__exportStar(RX(),AS);UX.__exportStar(kX(),AS)});var wo={};Te(wo,{isNodeJs:()=>LX});var DX,LX,MX=b(()=>{l();DX=Ht(Uk());Bo(wo,Ht(Uk()));LX=DX.isNode});function Tn(e=3){let t=Date.now()*Math.pow(10,e),r=Math.floor(Math.random()*Math.pow(10,e));return t+r}function _n(e=6){return BigInt(Tn(e))}function dr(e,t,r){return{id:r||Tn(),jsonrpc:"2.0",method:e,params:t}}function bo(e,t){return{id:e,jsonrpc:"2.0",result:t}}function la(e,t,r){return{id:e,jsonrpc:"2.0",error:HX(t,r)}}function HX(e,t){return typeof e>"u"?vS(yS):(typeof e=="string"&&(e=Object.assign(Object.assign({},vS(e4)),{message:e})),typeof t<"u"&&(e.data=t),xS(e.code)&&(e=ES(e.code)),e)}var $X=b(()=>{l();Bk();bS()});function VOe(e){return e.includes("*")?SS(e):!/\W/g.test(e)}function CS(e){return e==="*"}function SS(e){return CS(e)?!0:!(!e.includes("*")||e.split("*").length!==2||e.split("*").filter(t=>t.trim()==="").length!==1)}function jOe(e){return!CS(e)&&SS(e)&&!e.split("*")[0].trim()}function qOe(e){return!CS(e)&&SS(e)&&!e.split("*")[1].trim()}var FX=b(()=>{l()});var n4,Dk,IS,o4,zX=b(()=>{l();n4=class{},Dk=class extends n4{constructor(t){super()}},IS=class extends n4{constructor(){super()}},o4=class extends IS{constructor(t){super()}}});var VX=b(()=>{l();zX()});function ZOe(e){let t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function jX(e,t){let r=ZOe(e);return typeof r>"u"?!1:new RegExp(t).test(r)}function TS(e){return jX(e,WOe)}function _S(e){return jX(e,KOe)}function Lk(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}var WOe,KOe,qX=b(()=>{l();WOe="^https?:",KOe="^wss?:"});function Mk(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function Hc(e){return Mk(e)&&"method"in e}function ua(e){return Mk(e)&&(Jr(e)||Ir(e))}function Jr(e){return"result"in e}function Ir(e){return"error"in e}function GOe(e){return"error"in e&&e.valid===!1}var WX=b(()=>{l()});var vi={};Te(vi,{DEFAULT_ERROR:()=>t4,IBaseJsonRpcProvider:()=>IS,IEvents:()=>n4,IJsonRpcConnection:()=>Dk,IJsonRpcProvider:()=>o4,INTERNAL_ERROR:()=>yS,INVALID_PARAMS:()=>_X,INVALID_REQUEST:()=>IX,METHOD_NOT_FOUND:()=>TX,PARSE_ERROR:()=>SX,RESERVED_ERROR_CODES:()=>Ok,SERVER_ERROR:()=>e4,SERVER_ERROR_CODE_RANGE:()=>wS,STANDARD_ERROR_MAP:()=>xh,formatErrorMessage:()=>HX,formatJsonRpcError:()=>la,formatJsonRpcRequest:()=>dr,formatJsonRpcResult:()=>bo,getBigIntRpcId:()=>_n,getError:()=>vS,getErrorByCode:()=>ES,isHttpUrl:()=>TS,isJsonRpcError:()=>Ir,isJsonRpcPayload:()=>Mk,isJsonRpcRequest:()=>Hc,isJsonRpcResponse:()=>ua,isJsonRpcResult:()=>Jr,isJsonRpcValidationInvalid:()=>GOe,isLocalhostUrl:()=>Lk,isNodeJs:()=>LX,isReservedErrorCode:()=>xS,isServerErrorCode:()=>HOe,isValidDefaultRoute:()=>CS,isValidErrorCode:()=>PX,isValidLeadingWildcardRoute:()=>jOe,isValidRoute:()=>VOe,isValidTrailingWildcardRoute:()=>qOe,isValidWildcardRoute:()=>SS,isWsUrl:()=>_S,parseConnectionError:()=>r4,payloadId:()=>Tn,validateJsonRpcError:()=>$Oe});var $c=b(()=>{l();bS();Bk();MX();Bo(vi,wo);$X();FX();VX();qX();WX()});var KX,da,cw=b(()=>{l();KX=Ht(ks());$c();da=class extends o4{constructor(t){super(t),this.events=new KX.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async request(t,r){return this.requestStrict(dr(t.method,t.params||[],t.id||_n().toString()),r)}async requestStrict(t,r){return new Promise(async(n,o)=>{if(!this.connection.connected)try{await this.open()}catch(s){o(s)}this.events.on(`${t.id}`,s=>{Ir(s)?o(s.error):n(s.result)});try{await this.connection.send(t,r)}catch(s){o(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),ua(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}});var GX=_e((hht,ZX)=>{"use strict";l();ZX.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var QX,YOe,JOe,YX,JX,QOe,lw,Hk=b(()=>{l();QX=Ht(ks());R1();$c();YOe=()=>typeof m<"u"?m:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:GX(),JOe=()=>typeof m<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",YX=e=>e.split("?")[0],JX=10,QOe=YOe(),lw=class{constructor(t){if(this.url=t,this.events=new QX.EventEmitter,this.registering=!1,!_S(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(yi(t))}catch(r){this.onError(t.id,r)}}register(t=this.url){if(!_S(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,o)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),o(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return o(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=t,this.registering=!0,new Promise((r,n)=>{let o=(0,vi.isReactNative)()?void 0:{rejectUnauthorized:!Lk(t)},s=new QOe(t,[],o);JOe()?s.onerror=i=>{let a=i;n(this.emitError(a.error))}:s.on("error",i=>{n(this.emitError(i))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(t){t.onmessage=r=>this.onPayload(r),t.onclose=r=>this.onClose(r),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;let r=typeof t.data=="string"?Fs(t.data):t.data;this.events.emit("payload",r)}onError(t,r){let n=this.parseError(r),o=n.message||n.toString(),s=la(t,o);this.events.emit("payload",s)}parseError(t,r=this.url){return r4(t,YX(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>JX&&this.events.setMaxListeners(JX)}emitError(t){let r=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${YX(this.url)}`));return this.events.emit("register_error",r),r}}});var Nee=_e((_h,Pee)=>{l();var eI=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,tI=(function(){function e(){this.fetch=!1,this.DOMException=eI.DOMException}return e.prototype=eI,new e})();(function(e){var t=(function(r){var n=typeof e<"u"&&e||typeof self<"u"&&self||typeof global<"u"&&global||{},o={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function s(P){return P&&DataView.prototype.isPrototypeOf(P)}if(o.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=ArrayBuffer.isView||function(P){return P&&i.indexOf(Object.prototype.toString.call(P))>-1};function c(P){if(typeof P!="string"&&(P=String(P)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(P)||P==="")throw new TypeError('Invalid character in header field name: "'+P+'"');return P.toLowerCase()}function u(P){return typeof P!="string"&&(P=String(P)),P}function d(P){var R={next:function(){var I=P.shift();return{done:I===void 0,value:I}}};return o.iterable&&(R[Symbol.iterator]=function(){return R}),R}function f(P){this.map={},P instanceof f?P.forEach(function(R,I){this.append(I,R)},this):Array.isArray(P)?P.forEach(function(R){if(R.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+R.length);this.append(R[0],R[1])},this):P&&Object.getOwnPropertyNames(P).forEach(function(R){this.append(R,P[R])},this)}f.prototype.append=function(P,R){P=c(P),R=u(R);var I=this.map[P];this.map[P]=I?I+", "+R:R},f.prototype.delete=function(P){delete this.map[c(P)]},f.prototype.get=function(P){return P=c(P),this.has(P)?this.map[P]:null},f.prototype.has=function(P){return this.map.hasOwnProperty(c(P))},f.prototype.set=function(P,R){this.map[c(P)]=u(R)},f.prototype.forEach=function(P,R){for(var I in this.map)this.map.hasOwnProperty(I)&&P.call(R,this.map[I],I,this)},f.prototype.keys=function(){var P=[];return this.forEach(function(R,I){P.push(I)}),d(P)},f.prototype.values=function(){var P=[];return this.forEach(function(R){P.push(R)}),d(P)},f.prototype.entries=function(){var P=[];return this.forEach(function(R,I){P.push([I,R])}),d(P)},o.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);function p(P){if(!P._noBody){if(P.bodyUsed)return Promise.reject(new TypeError("Already read"));P.bodyUsed=!0}}function h(P){return new Promise(function(R,I){P.onload=function(){R(P.result)},P.onerror=function(){I(P.error)}})}function y(P){var R=new FileReader,I=h(R);return R.readAsArrayBuffer(P),I}function w(P){var R=new FileReader,I=h(R),B=/charset=([A-Za-z0-9_-]+)/.exec(P.type),C=B?B[1]:"utf-8";return R.readAsText(P,C),I}function x(P){for(var R=new Uint8Array(P),I=new Array(R.length),B=0;B-1?R:P}function _(P,R){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');R=R||{};var I=R.body;if(P instanceof _){if(P.bodyUsed)throw new TypeError("Already read");this.url=P.url,this.credentials=P.credentials,R.headers||(this.headers=new f(P.headers)),this.method=P.method,this.mode=P.mode,this.signal=P.signal,!I&&P._bodyInit!=null&&(I=P._bodyInit,P.bodyUsed=!0)}else this.url=String(P);if(this.credentials=R.credentials||this.credentials||"same-origin",(R.headers||!this.headers)&&(this.headers=new f(R.headers)),this.method=S(R.method||this.method||"GET"),this.mode=R.mode||this.mode||null,this.signal=R.signal||this.signal||(function(){if("AbortController"in n){var A=new AbortController;return A.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(R.cache==="no-store"||R.cache==="no-cache")){var B=/([?&])_=[^&]*/;if(B.test(this.url))this.url=this.url.replace(B,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function O(P){var R=new FormData;return P.trim().split("&").forEach(function(I){if(I){var B=I.split("="),C=B.shift().replace(/\+/g," "),A=B.join("=").replace(/\+/g," ");R.append(decodeURIComponent(C),decodeURIComponent(A))}}),R}function D(P){var R=new f,I=P.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(B){return B.indexOf(` -`)===0?B.substr(1,B.length):B}).forEach(function(B){var C=B.split(":"),A=C.shift().trim();if(A){var U=C.join(":").trim();try{R.append(A,U)}catch(H){console.warn("Response "+H.message)}}}),R}T.call(_.prototype);function M(P,R){if(!(this instanceof M))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(R||(R={}),this.type="default",this.status=R.status===void 0?200:R.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=R.statusText===void 0?"":""+R.statusText,this.headers=new f(R.headers),this.url=R.url||"",this._initBody(P)}T.call(M.prototype),M.prototype.clone=function(){return new M(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},M.error=function(){var P=new M(null,{status:200,statusText:""});return P.ok=!1,P.status=0,P.type="error",P};var N=[301,302,303,307,308];M.redirect=function(P,R){if(N.indexOf(R)===-1)throw new RangeError("Invalid status code");return new M(null,{status:R,headers:{location:P}})},r.DOMException=n.DOMException;try{new r.DOMException}catch{r.DOMException=function(R,I){this.message=R,this.name=I;var B=Error(R);this.stack=B.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function L(P,R){return new Promise(function(I,B){var C=new _(P,R);if(C.signal&&C.signal.aborted)return B(new r.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function U(){A.abort()}A.onload=function(){var F={statusText:A.statusText,headers:D(A.getAllResponseHeaders()||"")};C.url.indexOf("file://")===0&&(A.status<200||A.status>599)?F.status=200:F.status=A.status,F.url="responseURL"in A?A.responseURL:F.headers.get("X-Request-URL");var j="response"in A?A.response:A.responseText;setTimeout(function(){I(new M(j,F))},0)},A.onerror=function(){setTimeout(function(){B(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){B(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){B(new r.DOMException("Aborted","AbortError"))},0)};function H(F){try{return F===""&&n.location.href?n.location.href:F}catch{return F}}if(A.open(C.method,H(C.url),!0),C.credentials==="include"?A.withCredentials=!0:C.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(o.blob?A.responseType="blob":o.arrayBuffer&&(A.responseType="arraybuffer")),R&&typeof R.headers=="object"&&!(R.headers instanceof f||n.Headers&&R.headers instanceof n.Headers)){var k=[];Object.getOwnPropertyNames(R.headers).forEach(function(F){k.push(c(F)),A.setRequestHeader(F,u(R.headers[F]))}),C.headers.forEach(function(F,j){k.indexOf(j)===-1&&A.setRequestHeader(j,F)})}else C.headers.forEach(function(F,j){A.setRequestHeader(j,F)});C.signal&&(C.signal.addEventListener("abort",U),A.onreadystatechange=function(){A.readyState===4&&C.signal.removeEventListener("abort",U)}),A.send(typeof C._bodyInit>"u"?null:C._bodyInit)})}return L.polyfill=!0,n.fetch||(n.fetch=L,n.Headers=f,n.Request=_,n.Response=M),r.Headers=f,r.Request=_,r.Response=M,r.fetch=L,Object.defineProperty(r,"__esModule",{value:!0}),r})({})})(tI);tI.fetch.ponyfill=!0;delete tI.fetch.polyfill;var bw=eI.fetch?eI:tI;_h=bw.fetch;_h.default=bw.fetch;_h.fetch=bw.fetch;_h.Headers=bw.Headers;_h.Request=bw.Request;_h.Response=bw.Response;Pee.exports=_h});var Lee,yU,KBe,ZBe,GBe,Ree,YBe,JBe,Oee,Bee,kee,QBe,XBe,Uee,Dee,Ja,rI=b(()=>{l();Lee=Ht(ks()),yU=Ht(Nee());R1();$c();KBe=Object.defineProperty,ZBe=Object.defineProperties,GBe=Object.getOwnPropertyDescriptors,Ree=Object.getOwnPropertySymbols,YBe=Object.prototype.hasOwnProperty,JBe=Object.prototype.propertyIsEnumerable,Oee=(e,t,r)=>t in e?KBe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Bee=(e,t)=>{for(var r in t||(t={}))YBe.call(t,r)&&Oee(e,r,t[r]);if(Ree)for(var r of Ree(t))JBe.call(t,r)&&Oee(e,r,t[r]);return e},kee=(e,t)=>ZBe(e,GBe(t)),QBe={Accept:"application/json","Content-Type":"application/json"},XBe="POST",Uee={headers:QBe,method:XBe},Dee=10,Ja=class{constructor(t,r=!1){if(this.url=t,this.disableProviderPing=r,this.events=new Lee.EventEmitter,this.isAvailable=!1,this.registering=!1,!TS(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{let r=yi(t),n=await(await(0,yU.default)(this.url,kee(Bee({},Uee),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(t.id,r)}}async register(t=this.url){if(!TS(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,o)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),o(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return o(new Error("HTTP connection is missing or invalid"));n()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){let r=yi({id:1,jsonrpc:"2.0",method:"test",params:[]});await(0,yU.default)(t,kee(Bee({},Uee),{body:r}))}this.onOpen()}catch(r){let n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;let r=typeof t.data=="string"?Fs(t.data):t.data;this.events.emit("payload",r)}onError(t,r){let n=this.parseError(r),o=n.message||n.toString(),s=la(t,o);this.events.emit("payload",s)}parseError(t,r=this.url){return r4(t,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Dee&&this.events.setMaxListeners(Dee)}}});var l4,ete=b(()=>{l();l4={isLowerCaseMatch(e,t){return e?.toLowerCase()===t?.toLowerCase()}}});var Z,u4=b(()=>{l();Z={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:typeof process<"u"&&!1,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"}});var V1,sI,tte=b(()=>{l();u4();V1={caipNetworkIdToNumber(e){return e?Number(e.split(":")[1]):void 0},parseEvmChainId(e){return typeof e=="string"?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace(e,t){return e?.filter(r=>r.chainNamespace===t)||[]},getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;let r=e.find(o=>o.caipNetworkId===t);if(r)return r.name;let[n]=t.split(":");return Z.CHAIN_NAME_MAP?.[n]||void 0}},sI=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"]});function ote(){function e(t){var r=this;if(!(r instanceof e))return t===Wl?ote():new e(t);if(t instanceof e)r.s=t.s,r.e=t.e,r.c=t.c.slice();else{if(typeof t!="string"){if(e.strict===!0&&typeof t!="bigint")throw TypeError(q1+"value");t=t===0&&1/t<0?"-0":String(t)}Cke(r,t)}r.constructor=e}return e.prototype=yr,e.DP=yke,e.RM=wke,e.NE=bke,e.PE=xke,e.strict=vke,e.roundDown=0,e.roundHalfUp=1,e.roundHalfEven=2,e.roundUp=3,e}function Cke(e,t){var r,n,o;if(!Ake.test(t))throw Error(q1+"number");for(e.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),o=t.length,n=0;n0&&t.charAt(--o)=="0";);for(e.e=r-n-1,e.c=[],r=0;n<=o;)e.c[r++]=+t.charAt(n++)}return e}function W1(e,t,r,n){var o=e.c;if(r===Wl&&(r=e.constructor.RM),r!==0&&r!==1&&r!==2&&r!==3)throw Error(Eke);if(t<1)n=r===3&&(n||!!o[0])||t===0&&(r===1&&o[0]>=5||r===2&&(o[0]>5||o[0]===5&&(n||o[1]!==Wl))),o.length=1,n?(e.e=e.e-t+1,o[0]=1):o[0]=e.e=0;else if(t=5||r===2&&(o[t]>5||o[t]===5&&(n||o[t+1]!==Wl||o[t-1]&1))||r===3&&(n||!!o[0]),o.length=t,n){for(;++o[--t]>9;)if(o[t]=0,t===0){++e.e,o.unshift(1);break}}for(t=o.length;!o[--t];)o.pop()}return e}function K1(e,t,r){var n=e.e,o=e.c.join(""),s=o.length;if(t)o=o.charAt(0)+(s>1?"."+o.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)o="0"+o;o="0."+o}else if(n>0)if(++n>s)for(n-=s;n--;)o+="0";else n1&&(o=o.charAt(0)+"."+o.slice(1));return e.s<0&&r?"-"+o:o}var yke,wke,j1,rte,bke,xke,vke,d4,q1,iI,Eke,nte,yr,Wl,Ake,Ske,Vc,ste=b(()=>{l();yke=20,wke=1,j1=1e6,rte=1e6,bke=-7,xke=21,vke=!1,d4="[big.js] ",q1=d4+"Invalid ",iI=q1+"decimal places",Eke=q1+"rounding mode",nte=d4+"Division by zero",yr={},Wl=void 0,Ake=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;yr.abs=function(){var e=new this.constructor(this);return e.s=1,e};yr.cmp=function(e){var t,r=this,n=r.c,o=(e=new r.constructor(e)).c,s=r.s,i=e.s,a=r.e,c=e.e;if(!n[0]||!o[0])return n[0]?s:o[0]?-i:0;if(s!=i)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(i=(a=n.length)<(c=o.length)?a:c,s=-1;++so[s]^t?1:-1;return a==c?0:a>c^t?1:-1};yr.div=function(e){var t=this,r=t.constructor,n=t.c,o=(e=new r(e)).c,s=t.s==e.s?1:-1,i=r.DP;if(i!==~~i||i<0||i>j1)throw Error(iI);if(!o[0])throw Error(nte);if(!n[0])return e.s=s,e.c=[e.e=0],e;var a,c,u,d,f,p=o.slice(),h=a=o.length,y=n.length,w=n.slice(0,a),x=w.length,v=e,T=v.c=[],E=0,S=i+(v.e=t.e-e.e)+1;for(v.s=s,s=S<0?0:S,p.unshift(0);x++x?1:-1;else for(f=-1,d=0;++fw[f]?1:-1;break}if(d<0){for(c=x==a?o:p;x;){if(w[--x]S&&W1(v,S,r.RM,w[0]!==Wl),v};yr.eq=function(e){return this.cmp(e)===0};yr.gt=function(e){return this.cmp(e)>0};yr.gte=function(e){return this.cmp(e)>-1};yr.lt=function(e){return this.cmp(e)<0};yr.lte=function(e){return this.cmp(e)<1};yr.minus=yr.sub=function(e){var t,r,n,o,s=this,i=s.constructor,a=s.s,c=(e=new i(e)).s;if(a!=c)return e.s=-c,s.plus(e);var u=s.c.slice(),d=s.e,f=e.c,p=e.e;if(!u[0]||!f[0])return f[0]?e.s=-c:u[0]?e=new i(s):e.s=1,e;if(a=d-p){for((o=a<0)?(a=-a,n=u):(p=d,n=f),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(r=((o=u.length0)for(;c--;)u[t++]=0;for(c=t;r>a;){if(u[--r]0?(c=i,n=u):(t=-t,n=a),n.reverse();t--;)n.push(0);n.reverse()}for(a.length-u.length<0&&(n=u,u=a,a=n),t=u.length,r=0;t;a[t]%=10)r=(a[--t]=a[t]+u[t]+r)/10|0;for(r&&(a.unshift(r),++c),t=a.length;a[--t]===0;)a.pop();return e.c=a,e.e=c,e};yr.pow=function(e){var t=this,r=new t.constructor("1"),n=r,o=e<0;if(e!==~~e||e<-rte||e>rte)throw Error(q1+"exponent");for(o&&(e=-e);e&1&&(n=n.times(t)),e>>=1,!!e;)t=t.times(t);return o?r.div(n):n};yr.prec=function(e,t){if(e!==~~e||e<1||e>j1)throw Error(q1+"precision");return W1(new this.constructor(this),e,t)};yr.round=function(e,t){if(e===Wl)e=0;else if(e!==~~e||e<-j1||e>j1)throw Error(iI);return W1(new this.constructor(this),e+this.e+1,t)};yr.sqrt=function(){var e,t,r,n=this,o=n.constructor,s=n.s,i=n.e,a=new o("0.5");if(!n.c[0])return new o(n);if(s<0)throw Error(d4+"No square root");s=Math.sqrt(+K1(n,!0,!0)),s===0||s===1/0?(t=n.c.join(""),t.length+i&1||(t+="0"),s=Math.sqrt(t),i=((i+1)/2|0)-(i<0||i&1),e=new o((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+i)):e=new o(s+""),i=e.e+(o.DP+=4);do r=e,e=a.times(r.plus(n.div(r)));while(r.c.slice(0,i).join("")!==e.c.slice(0,i).join(""));return W1(e,(o.DP-=4)+e.e+1,o.RM)};yr.times=yr.mul=function(e){var t,r=this,n=r.constructor,o=r.c,s=(e=new n(e)).c,i=o.length,a=s.length,c=r.e,u=e.e;if(e.s=r.s==e.s?1:-1,!o[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+u,ic;)a=t[u]+s[c]*o[u-c-1]+a,t[u--]=a%10,a=a/10|0;t[u]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e};yr.toExponential=function(e,t){var r=this,n=r.c[0];if(e!==Wl){if(e!==~~e||e<0||e>j1)throw Error(iI);for(r=W1(new r.constructor(r),++e,t);r.c.lengthj1)throw Error(iI);for(r=W1(new r.constructor(r),e+r.e+1,t),e=e+r.e+1;r.c.length=t.PE,!!e.c[0])};yr.toNumber=function(){var e=+K1(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(e.toString()))throw Error(d4+"Imprecise conversion");return e};yr.toPrecision=function(e,t){var r=this,n=r.constructor,o=r.c[0];if(e!==Wl){if(e!==~~e||e<1||e>j1)throw Error(q1+"precision");for(r=W1(new n(r),e,t);r.c.length=n.PE,!!o)};yr.valueOf=function(){var e=this,t=e.constructor;if(t.strict===!0)throw Error(d4+"valueOf disallowed");return K1(e,e.e<=t.NE||e.e>=t.PE,!0)};Ske=ote(),Vc=Ske});var ht,ite=b(()=>{l();ste();ht={bigNumber(e,t={safe:!1}){try{return e?new Vc(e):new Vc(0)}catch(r){if(t.safe)return new Vc(0);throw r}},formatNumber(e,t){let{decimals:r,round:n=8,safe:o=!0}=t;return ht.bigNumber(e,{safe:o}).div(new Vc(10).pow(r)).round(n)},multiply(e,t){if(e===void 0||t===void 0)return new Vc(0);let r=new Vc(e),n=new Vc(t);return r.times(n)},toFixed(e,t=2){return e===void 0||e===""?new Vc(0).toFixed(t):new Vc(e).toFixed(t)},formatNumberToLocalString(e,t=2){return e===void 0||e===""?"0.00":typeof e=="number"?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"})},parseLocalStringToNumber(e){if(e===void 0||e==="")return 0;let t=e.replace(/,/gu,"");return new Vc(t).toNumber()}}});var ate,cte=b(()=>{l();ate=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]});var lte,ute=b(()=>{l();lte=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]});var dte,fte=b(()=>{l();dte=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]});var f4,pte=b(()=>{l();cte();ute();fte();u4();f4={getERC20Abi:e=>Z.USDT_CONTRACT_ADDRESSES.includes(e)?dte:ate,getSwapAbi:()=>lte}});var Ph,hte=b(()=>{l();u4();Ph={ConnectorExplorerIds:{[Z.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[Z.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[Z.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Z.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Z.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Z.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Z.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Z.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Z.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Z.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Z.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Z.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Z.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Z.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Z.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Z.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"},ConnectorImageIds:{[Z.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[Z.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[Z.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[Z.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[Z.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[Z.CONNECTOR_ID.INJECTED]:"Browser Wallet",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[Z.CONNECTOR_ID.COINBASE]:"Coinbase",[Z.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[Z.CONNECTOR_ID.LEDGER]:"Ledger",[Z.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[Z.CONNECTOR_ID.INJECTED]:"INJECTED",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[Z.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[Z.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]}});var lt,mte=b(()=>{l();lt={validateCaipAddress(e){if(e.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){let t=e.split(":");if(t.length!==3)throw new Error(`Invalid CAIP-10 address: ${e}`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:r,chainId:n,address:o}},parseCaipNetworkId(e){let t=e.split(":");if(t.length!==2)throw new Error(`Invalid CAIP-2 network id: ${e}`);let[r,n]=t;if(!r||!n)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:r,chainId:n}}}});var js,IU,Z1,gte=b(()=>{l();js={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if(typeof e=="object"&&e!==null){let t=e,r=typeof t.message=="string",n=typeof t.code=="number";return r&&n}return!1}catch{return!1}},isUserRejectedMessage(e){return e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled")},isUserRejectedRequestError(e){if(js.isRpcProviderError(e)){let t=e.code===js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,r=e.code===js.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||r||js.isUserRejectedMessage(e.message)}return e instanceof Error?js.isUserRejectedMessage(e.message):!1}},IU=class extends Error{constructor(t,r){super(r.message,{cause:t}),this.name=js.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=r.code}},Z1=class extends IU{constructor(t){super(t,{code:js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}});function p4(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}function G1(){return typeof window<"u"&&typeof localStorage<"u"}var Fe,Le,yte=b(()=>{l();Fe={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};Le={setItem(e,t){G1()&&t!==void 0&&localStorage.setItem(e,t)},getItem(e){if(G1())return localStorage.getItem(e)||void 0},removeItem(e){G1()&&localStorage.removeItem(e)},clear(){G1()&&localStorage.clear()}}});function Y1(e,t){let r=e?.["--apkt-accent"]??e?.["--w3m-accent"];return t==="light"?{"--w3m-accent":r||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":r||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}var wte=b(()=>{l()});var ut=b(()=>{l();ete();tte();ite();pte();u4();hte();mte();gte();yte();wte()});var Ike,bte,TU,Tke,xte,_U,vte=b(()=>{l();Ike=Symbol(),bte=Object.getPrototypeOf,TU=new WeakMap,Tke=e=>e&&(TU.has(e)?TU.get(e):bte(e)===Object.prototype||bte(e)===Array.prototype),xte=e=>Tke(e)&&e[Ike]||null,_U=(e,t=!0)=>{TU.set(e,t)}});function rt(e={}){if(!NU(e))throw new Error("object required");let t=h4.get(e);if(t)return t;let r=aI[0],n=new Set,o=(x,v=++aI[0])=>{r!==v&&(s=r=v,n.forEach(T=>T(x,v)))},s=r,i=(x=aI[0])=>(s!==x&&(s=x,c.forEach(([v])=>{let T=v[1](x);T>r&&(r=T)})),r),a=x=>(v,T)=>{let E=[...v];E[1]=[x,...E[1]],o(E,T)},c=new Map,u=(x,v)=>{let T=!m4.has(v)&&Nh.get(v);if(T){if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&c.has(x))throw new Error("prop listener already exists");if(n.size){let E=T[2](a(x));c.set(x,[T,E])}else c.set(x,[T])}},d=x=>{var v;let T=c.get(x);T&&(c.delete(x),(v=T[1])==null||v.call(T))},f=x=>(n.add(x),n.size===1&&c.forEach(([T,E],S)=>{if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&E)throw new Error("remove already exists");let _=T[2](a(S));c.set(S,[T,_])}),()=>{n.delete(x),n.size===0&&c.forEach(([T,E],S)=>{E&&(E(),c.set(S,[T]))})}),p=!0,h=Bke(()=>p,u,d,o),y=Nke(e,h);h4.set(e,y);let w=[e,i,f];return Nh.set(y,w),Reflect.ownKeys(e).forEach(x=>{let v=Object.getOwnPropertyDescriptor(e,x);"value"in v&&v.writable&&(y[x]=e[x])}),p=!1,y}function Dt(e,t,r){let n=Nh.get(e);(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!n&&console.warn("Please use proxy object");let o,s=[],i=n[2],a=!1,u=i(d=>{if(s.push(d),r){t(s.splice(0));return}o||(o=Promise.resolve().then(()=>{o=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,u()}}function Kl(e){let t=Nh.get(e);(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!t&&console.warn("Please use proxy object");let[r,n]=t;return Oke(r,n())}function vf(e){return m4.add(e),e}function RU(){return{proxyStateMap:Nh,refSet:m4,snapCache:PU,versionHolder:aI,proxyCache:h4}}var NU,_ke,Ate,Pke,Nh,m4,PU,aI,h4,Ete,Nke,Rke,Oke,Bke,Lr=b(()=>{l();vte();NU=e=>typeof e=="object"&&e!==null,_ke=e=>NU(e)&&!m4.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),Ate=(e,t)=>{let r=PU.get(e);if(r?.[0]===t)return r[1];let n=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return _U(n,!0),PU.set(e,[t,n]),Reflect.ownKeys(e).forEach(o=>{if(Object.getOwnPropertyDescriptor(n,o))return;let s=Reflect.get(e,o),{enumerable:i}=Reflect.getOwnPropertyDescriptor(e,o),a={value:s,enumerable:i,configurable:!0};if(m4.has(s))_U(s,!1);else if(Nh.has(s)){let[c,u]=Nh.get(s);a.value=Ate(c,u())}Object.defineProperty(n,o,a)}),Object.preventExtensions(n)},Pke=(e,t,r,n)=>({deleteProperty(o,s){let i=Reflect.get(o,s);r(s);let a=Reflect.deleteProperty(o,s);return a&&n(["delete",[s],i]),a},set(o,s,i,a){let c=!e()&&Reflect.has(o,s),u=Reflect.get(o,s,a);if(c&&(Ete(u,i)||h4.has(i)&&Ete(u,h4.get(i))))return!0;r(s),NU(i)&&(i=xte(i)||i);let d=!Nh.has(i)&&Rke(i)?rt(i):i;return t(s,d),Reflect.set(o,s,d,a),n(["set",[s],i,u]),!0}}),Nh=new WeakMap,m4=new WeakSet,PU=new WeakMap,aI=[1],h4=new WeakMap,Ete=Object.is,Nke=(e,t)=>new Proxy(e,t),Rke=_ke,Oke=Ate,Bke=Pke});function Tt(e,t,r,n){let o=e[t];return Dt(e,()=>{let s=e[t];Object.is(o,s)||r(o=s)},n)}function Cte(e){let t=[],r=0,n=new Map,o=new WeakMap,s=()=>{let u=Uke.get(a),d=u?.[1];if(d&&!o.has(d)){let f=new Map(n);o.set(d,f)}},i=u=>o.get(u)||n;if(e){if(typeof e[Symbol.iterator]!="function")throw new TypeError(`proxyMap: +`+new Array(e.length+4).join(" "):o{l();var LC=kB();function DC(e,t,r){let n=e[t]+e[r],o=e[t+1]+e[r+1];n>=4294967296&&o++,e[t]=n,e[t+1]=o}function CJ(e,t,r,n){let o=e[t]+r;r<0&&(o+=4294967296);let s=e[t+1]+n;o>=4294967296&&s++,e[t]=o,e[t+1]=s}function SJ(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function lh(e,t,r,n,o,s){let i=D8[o],a=D8[o+1],c=D8[s],u=D8[s+1];DC(vt,e,t),CJ(vt,e,i,a);let d=vt[n]^vt[e],f=vt[n+1]^vt[e+1];vt[n]=f,vt[n+1]=d,DC(vt,r,n),d=vt[t]^vt[r],f=vt[t+1]^vt[r+1],vt[t]=d>>>24^f<<8,vt[t+1]=f>>>24^d<<8,DC(vt,e,t),CJ(vt,e,c,u),d=vt[n]^vt[e],f=vt[n+1]^vt[e+1],vt[n]=d>>>16^f<<16,vt[n+1]=f>>>16^d<<16,DC(vt,r,n),d=vt[t]^vt[r],f=vt[t+1]^vt[r+1],vt[t]=f>>>31^d<<1,vt[t+1]=d>>>31^f<<1}var IJ=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),CNe=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],os=new Uint8Array(CNe.map(function(e){return e*2})),vt=new Uint32Array(32),D8=new Uint32Array(32);function TJ(e,t){let r=0;for(r=0;r<16;r++)vt[r]=e.h[r],vt[r+16]=IJ[r];for(vt[24]=vt[24]^e.t,vt[25]=vt[25]^e.t/4294967296,t&&(vt[28]=~vt[28],vt[29]=~vt[29]),r=0;r<32;r++)D8[r]=SJ(e.b,4*r);for(r=0;r<12;r++)lh(0,8,16,24,os[r*16+0],os[r*16+1]),lh(2,10,18,26,os[r*16+2],os[r*16+3]),lh(4,12,20,28,os[r*16+4],os[r*16+5]),lh(6,14,22,30,os[r*16+6],os[r*16+7]),lh(0,10,20,30,os[r*16+8],os[r*16+9]),lh(2,12,22,24,os[r*16+10],os[r*16+11]),lh(4,14,16,26,os[r*16+12],os[r*16+13]),lh(6,8,18,28,os[r*16+14],os[r*16+15]);for(r=0;r<16;r++)e.h[r]=e.h[r]^vt[r]^vt[r+16]}var uh=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function _J(e,t,r,n){if(e===0||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(n&&n.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");let o={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};uh.fill(0),uh[0]=e,t&&(uh[1]=t.length),uh[2]=1,uh[3]=1,r&&uh.set(r,32),n&&uh.set(n,48);for(let s=0;s<16;s++)o.h[s]=IJ[s]^SJ(uh,s*4);return t&&(UB(o,t),o.c=128),o}function UB(e,t){for(let r=0;r>2]>>8*(r&3);return t}function NJ(e,t,r,n,o){r=r||64,e=LC.normalizeInput(e),n&&(n=LC.normalizeInput(n)),o&&(o=LC.normalizeInput(o));let s=_J(r,t,n,o);return UB(s,e),PJ(s)}function SNe(e,t,r,n,o){let s=NJ(e,t,r,n,o);return LC.toHex(s)}RJ.exports={blake2b:NJ,blake2bHex:SNe,blake2bInit:_J,blake2bUpdate:UB,blake2bFinal:PJ}});var $J=_e((Nft,HJ)=>{l();var BJ=kB();function INe(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function dh(e,t,r,n,o,s){Xt[e]=Xt[e]+Xt[t]+o,Xt[n]=MC(Xt[n]^Xt[e],16),Xt[r]=Xt[r]+Xt[n],Xt[t]=MC(Xt[t]^Xt[r],12),Xt[e]=Xt[e]+Xt[t]+s,Xt[n]=MC(Xt[n]^Xt[e],8),Xt[r]=Xt[r]+Xt[n],Xt[t]=MC(Xt[t]^Xt[r],7)}function MC(e,t){return e>>>t^e<<32-t}var kJ=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ss=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),Xt=new Uint32Array(16),Ho=new Uint32Array(16);function UJ(e,t){let r=0;for(r=0;r<8;r++)Xt[r]=e.h[r],Xt[r+8]=kJ[r];for(Xt[12]^=e.t,Xt[13]^=e.t/4294967296,t&&(Xt[14]=~Xt[14]),r=0;r<16;r++)Ho[r]=INe(e.b,4*r);for(r=0;r<10;r++)dh(0,4,8,12,Ho[ss[r*16+0]],Ho[ss[r*16+1]]),dh(1,5,9,13,Ho[ss[r*16+2]],Ho[ss[r*16+3]]),dh(2,6,10,14,Ho[ss[r*16+4]],Ho[ss[r*16+5]]),dh(3,7,11,15,Ho[ss[r*16+6]],Ho[ss[r*16+7]]),dh(0,5,10,15,Ho[ss[r*16+8]],Ho[ss[r*16+9]]),dh(1,6,11,12,Ho[ss[r*16+10]],Ho[ss[r*16+11]]),dh(2,7,8,13,Ho[ss[r*16+12]],Ho[ss[r*16+13]]),dh(3,4,9,14,Ho[ss[r*16+14]],Ho[ss[r*16+15]]);for(r=0;r<8;r++)e.h[r]^=Xt[r]^Xt[r+8]}function DJ(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");let r=t?t.length:0;if(t&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");let n={h:new Uint32Array(kJ),b:new Uint8Array(64),c:0,t:0,outlen:e};return n.h[0]^=16842752^r<<8^e,r>0&&(DB(n,t),n.c=64),n}function DB(e,t){for(let r=0;r>2]>>8*(r&3)&255;return t}function MJ(e,t,r){r=r||32,e=BJ.normalizeInput(e);let n=DJ(r,t);return DB(n,e),LJ(n)}function TNe(e,t,r){let n=MJ(e,t,r);return BJ.toHex(n)}HJ.exports={blake2s:MJ,blake2sHex:TNe,blake2sInit:DJ,blake2sUpdate:DB,blake2sFinal:LJ}});var LB=_e((Oft,FJ)=>{l();var L8=OJ(),M8=$J();FJ.exports={blake2b:L8.blake2b,blake2bHex:L8.blake2bHex,blake2bInit:L8.blake2bInit,blake2bUpdate:L8.blake2bUpdate,blake2bFinal:L8.blake2bFinal,blake2s:M8.blake2s,blake2sHex:M8.blake2sHex,blake2sInit:M8.blake2sInit,blake2sUpdate:M8.blake2sUpdate,blake2sFinal:M8.blake2sFinal}});function _Ne(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}function NNe(e,t,r){var n=r&&r.stringify||_Ne,o=1;if(typeof e=="object"&&e!==null){var s=t.length+o;if(s===1)return e;var i=new Array(s);i[0]=n(e);for(var a=1;a-1?f:0,e.charCodeAt(h+1)){case 100:case 102:if(d>=c||t[d]==null)break;f=c||t[d]==null)break;f=c||t[d]===void 0)break;f",f=h+2,h++;break}u+=n(t[d]),f=h+2,h++;break;case 115:if(d>=c)break;f{n[o]=r[o]?r[o]:H8[o]||H8[ONe[o]||"log"]||Q2}),e[jB]=n}function kNe(e,t){return Array.isArray(e)?e.filter(function(r){return r!=="!stdSerializers.err"}):e===!0?Object.keys(t):!1}function hf(e){e=e||{},e.browser=e.browser||{};let t=e.browser.transmit;if(t&&typeof t.send!="function")throw Error("pino: transmit option must have a send function");let r=e.browser.write||H8;e.browser.write&&(e.browser.asObject=!0);let n=e.serializers||{},o=kNe(e.browser.serialize,n),s=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);let i=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(i);typeof r=="function"&&a.forEach(function(w){r[w]=r}),(e.enabled===!1||e.browser.disabled)&&(e.level="silent");let c=e.level||"info",u=Object.create(r);u.log||(u.log=Q2),BNe(u,a,r),VJ({},u),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:p,set:h});let d={transmit:t,serialize:o,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:zNe(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Q2};u.levels=UNe(e),u.level=c,u.isLevelEnabled=function(w){return this.levels.values[w]?this.levels.values[w]>=this.levels.values[this.level]:!1},u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=Q2,u.serializers=n,u._serialize=o,u._stdErrSerialize=s,u.child=function(...w){return y.call(this,d,...w)},t&&(u._logEvent=$B());function f(){return ph(this.level,this)}function p(){return this._level}function h(w){if(w!=="silent"&&!this.levels.values[w])throw Error("unknown level "+w);this._level=w,k1(this,d,u,"error"),k1(this,d,u,"fatal"),k1(this,d,u,"warn"),k1(this,d,u,"info"),k1(this,d,u,"debug"),k1(this,d,u,"trace"),i.forEach(x=>{k1(this,d,u,x)})}function y(w,x,v){if(!x)throw new Error("missing bindings for child Pino");v=v||{},o&&x.serializers&&(v.serializers=x.serializers);let T=v.serializers;if(o&&T){var E=Object.assign({},n,T),S=e.browser.serialize===!0?Object.keys(E):o;delete x.serializers,qB([x],S,E,this._stdErrSerialize)}function _(D){this._childLevel=(D._childLevel|0)+1,this.bindings=x,E&&(this.serializers=E,this._serialize=S),t&&(this._logEvent=$B([].concat(D._logEvent.bindings,x)))}_.prototype=this;let O=new _(this);return VJ(this,O),O.child=function(...D){return y.call(this,w,...D)},O.level=v.level||this.level,w.onChild(O),O}return u}function UNe(e){let t=e.customLevels||{},r=Object.assign({},hf.levels.values,t),n=Object.assign({},hf.levels.labels,DNe(t));return{values:r,labels:n}}function DNe(e){let t={};return Object.keys(e).forEach(function(r){t[e[r]]=r}),t}function LNe(e){let t=[];e.bindings&&t.push(e.bindings);let r=e[HB];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}function k1(e,t,r,n){if(Object.defineProperty(e,n,{value:ph(e.level,r)>ph(n,r)?Q2:r[jB][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===Q2){if(!t.transmit)return;let s=t.transmit.level||e.level,i=ph(s,r);if(ph(n,r)f}=o.formatters||{},a=r.slice(),c=a[0],u={},d=(e._childLevel|0)+1;if(d<1&&(d=1),n&&(u.time=n),s){let f=s(t,e.levels.values[t]);Object.assign(u,f)}else u.level=e.levels.values[t];if(o.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;d--&&typeof a[0]=="object";)Object.assign(u,a.shift());return[i(u),...a]}else{if(c!==null&&typeof c=="object"){for(;d--&&typeof a[0]=="object";)Object.assign(u,a.shift());c=a.length?zJ(a.shift(),a):void 0}else typeof c=="string"&&(c=zJ(a.shift(),a));return c!==void 0&&(u[o.messageKey]=c),[i(u)]}}function qB(e,t,r,n){for(let o in e)if(n&&e[o]instanceof Error)e[o]=hf.stdSerializers.err(e[o]);else if(typeof e[o]=="object"&&!Array.isArray(e[o])&&t)for(let s in e[o])t.indexOf(s)>-1&&s in r&&(e[o][s]=r[s](e[o][s]))}function FNe(e,t,r,n=!1){let o=t.send,s=t.ts,i=t.methodLevel,a=t.methodValue,c=t.val,u=e._logEvent.bindings;n||qB(r,e._serialize||Object.keys(e.serializers),e.serializers,e._stdErrSerialize===void 0?!0:e._stdErrSerialize),e._logEvent.ts=s,e._logEvent.messages=r.filter(function(d){return u.indexOf(d)===-1}),e._logEvent.level.label=i,e._logEvent.level.value=a,o(i,e._logEvent,c),e._logEvent=$B(u)}function $B(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function jJ(e){let t={type:e.constructor.name,msg:e.message,stack:e.stack};for(let r in e)t[r]===void 0&&(t[r]=e[r]);return t}function zNe(e){return typeof e.timestamp=="function"?e.timestamp:e.timestamp===!1?ZJ:GJ}function HC(){return{}}function MB(e){return e}function Q2(){}function ZJ(){return!1}function GJ(){return Date.now()}function VNe(){return Math.round(Date.now()/1e3)}function jNe(){return new Date(Date.now()).toISOString()}function qNe(){function e(t){return typeof t<"u"&&t}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}function qJ(e){return typeof e=="string"?e:GNe(e)||""}function X2(e){return mh(hh({},e),{level:e?.level||WNe.level})}function lRe(e,t,r=VC){return e[r]=t,e}function sr(e,t=VC){return e[t]||""}function uRe(e,t,r=VC){let n=sr(e,r);return n.trim()?`${n}/${t}`:t}function Cr(e,t,r=VC){let n=uRe(e,t,r),o=e.child({context:n});return lRe(o,n,r)}function dRe(e){var t,r;let n=new zB((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:$l.exports(mh(hh({},e.opts),{level:"trace",browser:mh(hh({},(r=e.opts)==null?void 0:r.browser),{write:o=>n.write(o)})})),chunkLoggerController:n}}function fRe(e){var t,r;let n=new VB((t=e.opts)==null?void 0:t.level,e.maxSizeInBytes);return{logger:$l.exports(mh(hh({},e.opts),{level:"trace",browser:mh(hh({},(r=e.opts)==null?void 0:r.browser),{write:o=>n.write(o)})}),n),chunkLoggerController:n}}function Fl(e){var t;if(typeof e.loggerOverride<"u"&&typeof e.loggerOverride!="string")return{logger:e.loggerOverride,chunkLoggerController:null};let r=mh(hh({},e.opts),{level:typeof e.loggerOverride=="string"?e.loggerOverride:(t=e.opts)==null?void 0:t.level});return typeof window<"u"?dRe(mh(hh({},e),{opts:r})):fRe(mh(hh({},e),{opts:r}))}var $l,PNe,zJ,H8,RNe,jB,HB,ONe,kft,WNe,VC,WB,KNe,ZNe,fh,FB,FC,GNe,YNe,JNe,$C,zC,QNe,XNe,eRe,zB,tRe,rRe,nRe,VB,oRe,sRe,iRe,WJ,aRe,cRe,KJ,hh,mh,gh=b(()=>{l();$l={exports:{}};PNe=NNe;zJ=PNe;$l.exports=hf;H8=qNe().console||{},RNe={mapHttpRequest:HC,mapHttpResponse:HC,wrapRequestSerializer:MB,wrapResponseSerializer:MB,wrapErrorSerializer:MB,req:HC,res:HC,err:jJ,errWithCause:jJ};jB=Symbol("pino.logFuncs"),HB=Symbol("pino.hierarchy"),ONe={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};hf.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},hf.stdSerializers=RNe,hf.stdTimeFunctions=Object.assign({},{nullTime:ZJ,epochTime:GJ,unixTime:VNe,isoTime:jNe});$l.exports.default=hf;kft=$l.exports.pino=hf,WNe={level:"info"},VC="custom_context",WB=1e3*1024,KNe=Object.defineProperty,ZNe=(e,t,r)=>t in e?KNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,fh=(e,t,r)=>ZNe(e,typeof t!="symbol"?t+"":t,r),FB=class{constructor(t){fh(this,"nodeValue"),fh(this,"sizeInBytes"),fh(this,"next"),this.nodeValue=t,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},FC=class{constructor(t){fh(this,"lengthInNodes"),fh(this,"sizeInBytes"),fh(this,"head"),fh(this,"tail"),fh(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=t,this.sizeInBytes=0}append(t){let r=new FB(t);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${t} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;let t=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=t.size}toArray(){let t=[],r=this.head;for(;r!==null;)t.push(r.value),r=r.next;return t}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let t=this.head;return{next:()=>{if(!t)return{done:!0,value:null};let r=t.value;return t=t.next,{done:!1,value:r}}}}},GNe=e=>JSON.stringify(e,(t,r)=>typeof r=="bigint"?r.toString()+"n":r);YNe=Object.defineProperty,JNe=(e,t,r)=>t in e?YNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$C=(e,t,r)=>JNe(e,typeof t!="symbol"?t+"":t,r),zC=class{constructor(t,r=WB){$C(this,"logs"),$C(this,"level"),$C(this,"levelValue"),$C(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=t??"error",this.levelValue=$l.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new FC(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(t,r){r===$l.exports.levels.values.error?console.error(t):r===$l.exports.levels.values.warn?console.warn(t):r===$l.exports.levels.values.debug?console.debug(t):r===$l.exports.levels.values.trace?console.trace(t):console.log(t)}appendToLogs(t){this.logs.append(qJ({timestamp:new Date().toISOString(),log:t}));let r=typeof t=="string"?JSON.parse(t).level:t.level;r>=this.levelValue&&this.forwardToConsole(t,r)}getLogs(){return this.logs}clearLogs(){this.logs=new FC(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(t){let r=this.getLogArray();return r.push(qJ({extraMetadata:t})),new Blob(r,{type:"application/json"})}},QNe=Object.defineProperty,XNe=(e,t,r)=>t in e?QNe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,eRe=(e,t,r)=>XNe(e,typeof t!="symbol"?t+"":t,r),zB=class{constructor(t,r=WB){eRe(this,"baseChunkLogger"),this.baseChunkLogger=new zC(t,r)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}downloadLogsBlobInBrowser(t){let r=URL.createObjectURL(this.logsToBlob(t)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}},tRe=Object.defineProperty,rRe=(e,t,r)=>t in e?tRe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,nRe=(e,t,r)=>rRe(e,typeof t!="symbol"?t+"":t,r),VB=class{constructor(t,r=WB){nRe(this,"baseChunkLogger"),this.baseChunkLogger=new zC(t,r)}write(t){this.baseChunkLogger.appendToLogs(t)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(t){return this.baseChunkLogger.logsToBlob(t)}},oRe=Object.defineProperty,sRe=Object.defineProperties,iRe=Object.getOwnPropertyDescriptors,WJ=Object.getOwnPropertySymbols,aRe=Object.prototype.hasOwnProperty,cRe=Object.prototype.propertyIsEnumerable,KJ=(e,t,r)=>t in e?oRe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,hh=(e,t)=>{for(var r in t||(t={}))aRe.call(t,r)&&KJ(e,r,t[r]);if(WJ)for(var r of WJ(t))cRe.call(t,r)&&KJ(e,r,t[r]);return e},mh=(e,t)=>sRe(e,iRe(t))});var yo,oX=b(()=>{l();yo=class{}});var tS=b(()=>{l();oX()});var iX,rS,xk,sX,Vs,iw,vk=b(()=>{l();iX=Ht(ks()),rS=Ht(jd());tS();xk=class extends yo{constructor(t){super()}},sX=rS.FIVE_SECONDS,Vs={pulse:"heartbeat_pulse"},iw=class e extends xk{constructor(t){super(t),this.events=new iX.EventEmitter,this.interval=sX,this.interval=t?.interval||sX}static async init(t){let r=new e(t);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),(0,rS.toMiliseconds)(this.interval))}pulse(){this.events.emit(Vs.pulse)}}});function vOe(e,t){if(e==="__proto__"||e==="constructor"&&t&&typeof t=="object"&&"prototype"in t){EOe(e);return}return t}function EOe(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}function J8(e,t={}){if(typeof e!="string")return e;if(e[0]==='"'&&e[e.length-1]==='"'&&e.indexOf("\\")===-1)return e.slice(1,-1);let r=e.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!xOe.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(wOe.test(e)||bOe.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,vOe)}return JSON.parse(e)}catch(n){if(t.strict)throw n;return e}}var wOe,bOe,xOe,aX=b(()=>{l();wOe=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,bOe=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,xOe=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/});function AOe(e){return!e||typeof e.then!="function"?Promise.resolve(e):e}function ro(e,...t){try{return AOe(e(...t))}catch(r){return Promise.reject(r)}}function COe(e){let t=typeof e;return e===null||t!=="object"&&t!=="function"}function SOe(e){let t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}function Q8(e){if(COe(e))return String(e);if(SOe(e)||Array.isArray(e))return JSON.stringify(e);if(typeof e.toJSON=="function")return Q8(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function cX(e){return typeof e=="string"?e:Ek+TOe(e)}function lX(e){return typeof e!="string"||!e.startsWith(Ek)?e:IOe(e.slice(Ek.length))}function IOe(e){return globalThis.Buffer?Buffer.from(e,"base64"):Uint8Array.from(globalThis.atob(e),t=>t.codePointAt(0))}function TOe(e){return globalThis.Buffer?Buffer.from(e).toString("base64"):globalThis.btoa(String.fromCodePoint(...e))}function bh(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Ak(e){return e.split(":").some(t=>t==="."||t==="..")}function uX(...e){return bh(e.join(":"))}function Ck(e){return e=bh(e),e?e+":":""}function dX(e,t){if(t===void 0)return!0;let r=0,n=e.indexOf(":");for(;n>-1;)r++,n=e.indexOf(":",n+1);return r<=t}function fX(e,t){return t?e.startsWith(t)&&e[e.length-1]!=="$":e[e.length-1]!=="$"}var Ek,pX=b(()=>{l();Ek="base64:"});function gX(e={}){let t={mounts:{"":e.driver||POe()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=f=>{let p=bh(f);if(!p||Ak(p))throw new Error(`[unstorage] Invalid key: ${JSON.stringify(f)}`);return p},n=f=>{let p=Ck(f);if(Ak(p))throw new Error(`[unstorage] Invalid base: ${JSON.stringify(f)}`);return p},o=f=>{for(let p of t.mountpoints)if(f.startsWith(p))return{base:p,relativeKey:f.slice(p.length),driver:t.mounts[p]};return{base:"",relativeKey:f,driver:t.mounts[""]}},s=(f,p)=>t.mountpoints.filter(h=>h.startsWith(f)||p&&f.startsWith(h)).map(h=>({relativeBase:f.length>h.length?f.slice(h.length):void 0,mountpoint:h,driver:t.mounts[h]})),i=(f,p)=>{if(t.watching){p=bh(p);for(let h of t.watchListeners)h(f,p)}},a=async()=>{if(!t.watching){t.watching=!0;for(let f in t.mounts)t.unwatch[f]=await hX(t.mounts[f],i,f)}},c=async()=>{if(t.watching){for(let f in t.unwatch)await t.unwatch[f]();t.unwatch={},t.watching=!1}},u=(f,p,h)=>{let y=new Map,w=x=>{let v=y.get(x.base);return v||(v={driver:x.driver,base:x.base,items:[]},y.set(x.base,v)),v};for(let x of f){let v=typeof x=="string",T=r(v?x:x.key),E=v?void 0:x.value,S=v||!x.options?p:{...p,...x.options},_=o(T);w(_).items.push({key:T,value:E,relativeKey:_.relativeKey,options:S})}return Promise.all([...y.values()].map(x=>h(x))).then(x=>x.flat())},d={async hasItem(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return ro(y.hasItem,h,p)},async getItem(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return ro(y.getItem,h,p).then(w=>J8(w))},async getItems(f,p={}){return u(f,p,h=>h.driver.getItems?ro(h.driver.getItems,h.items.map(y=>({key:y.relativeKey,options:y.options})),p).then(y=>y.map(w=>({key:uX(h.base,w.key),value:J8(w.value)}))):Promise.all(h.items.map(y=>ro(h.driver.getItem,y.relativeKey,y.options).then(w=>({key:y.key,value:J8(w)})))))},async getItemRaw(f,p={}){f=r(f);let{relativeKey:h,driver:y}=o(f);return y.getItemRaw?ro(y.getItemRaw,h,p):ro(y.getItem,h,p).then(w=>lX(w))},async setItem(f,p,h={}){if(p===void 0)return d.removeItem(f);f=r(f);let{relativeKey:y,driver:w}=o(f);w.setItem&&(await ro(w.setItem,y,Q8(p),h),w.watch||i("update",f))},async setItems(f,p){await u(f,p,async h=>{if(h.driver.setItems)return ro(h.driver.setItems,h.items.map(y=>({key:y.relativeKey,value:Q8(y.value),options:y.options})),p);h.driver.setItem&&await Promise.all(h.items.map(y=>ro(h.driver.setItem,y.relativeKey,Q8(y.value),y.options)))})},async setItemRaw(f,p,h={}){if(p===void 0)return d.removeItem(f,h);f=r(f);let{relativeKey:y,driver:w}=o(f);if(w.setItemRaw)await ro(w.setItemRaw,y,p,h);else if(w.setItem)await ro(w.setItem,y,cX(p),h);else return;w.watch||i("update",f)},async removeItem(f,p={}){typeof p=="boolean"&&(p={removeMeta:p}),f=r(f);let{relativeKey:h,driver:y}=o(f);y.removeItem&&(await ro(y.removeItem,h,p),(p.removeMeta||p.removeMata)&&await ro(y.removeItem,h+"$",p),y.watch||i("remove",f))},async getMeta(f,p={}){typeof p=="boolean"&&(p={nativeOnly:p}),f=r(f);let{relativeKey:h,driver:y}=o(f),w=Object.create(null);if(y.getMeta&&Object.assign(w,await ro(y.getMeta,h,p)),!p.nativeOnly){let x=await ro(y.getItem,h+"$",p).then(v=>J8(v));x&&typeof x=="object"&&(typeof x.atime=="string"&&(x.atime=new Date(x.atime)),typeof x.mtime=="string"&&(x.mtime=new Date(x.mtime)),Object.assign(w,x))}return w},async setMeta(f,p,h={}){return this.setItem(r(f)+"$",p,h)},async removeMeta(f,p={}){return this.removeItem(r(f)+"$",p)},async getKeys(f,p={}){f=n(f);let h=s(f,!0),y=[],w=[],x=!0;for(let T of h){T.driver.flags?.maxDepth||(x=!1);let E=await ro(T.driver.getKeys,T.relativeBase,p);for(let S of E){let _=T.mountpoint+bh(S);y.some(O=>_.startsWith(O))||w.push(_)}y=[T.mountpoint,...y.filter(S=>!S.startsWith(T.mountpoint))]}let v=p.maxDepth!==void 0&&!x;return w.filter(T=>(!v||dX(T,p.maxDepth))&&fX(T,f))},async clear(f,p={}){f=n(f),await Promise.all(s(f,!1).map(async h=>{if(h.driver.clear)return ro(h.driver.clear,h.relativeBase,p);if(h.driver.removeItem){let y=await h.driver.getKeys(h.relativeBase||"",p);return Promise.all(y.map(w=>h.driver.removeItem(w,p)))}}))},async dispose(){await Promise.all(Object.values(t.mounts).map(f=>mX(f)))},async watch(f){return await a(),t.watchListeners.push(f),async()=>{t.watchListeners=t.watchListeners.filter(p=>p!==f),t.watchListeners.length===0&&await c()}},async unwatch(){t.watchListeners=[],await c()},mount(f,p){if(f=n(f),f&&t.mounts[f])throw new Error(`already mounted at ${f}`);return f&&(t.mountpoints.push(f),t.mountpoints.sort((h,y)=>y.length-h.length)),t.mounts[f]=p,t.watching&&Promise.resolve(hX(p,i,f)).then(h=>{t.unwatch[f]=h}).catch(console.error),d},async unmount(f,p=!0){f=Ck(f),!(!f||!t.mounts[f])&&(t.watching&&f in t.unwatch&&(t.unwatch[f]?.(),delete t.unwatch[f]),p&&await mX(t.mounts[f]),t.mountpoints=t.mountpoints.filter(h=>h!==f),delete t.mounts[f])},getMount(f=""){f=bh(f)+":";let p=o(f);return{driver:p.driver,base:p.base}},getMounts(f="",p={}){return f=bh(f),s(f,p.parents).map(y=>({driver:y.driver,base:y.mountpoint}))},keys:(f,p={})=>d.getKeys(f,p),get:(f,p={})=>d.getItem(f,p),set:(f,p,h={})=>d.setItem(f,p,h),has:(f,p={})=>d.hasItem(f,p),del:(f,p={})=>d.removeItem(f,p),remove:(f,p={})=>d.removeItem(f,p)};return d}function hX(e,t,r){return e.watch?e.watch((n,o)=>t(n,r+o)):()=>{}}async function mX(e){typeof e.dispose=="function"&&await ro(e.dispose)}var _Oe,POe,yX=b(()=>{l();aX();pX();_Oe="memory",POe=()=>{let e=new Map;return{name:_Oe,getInstance:()=>e,hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,r){e.set(t,r)},setItemRaw(t,r){e.set(t,r)},removeItem(t){e.delete(t)},getKeys(){return[...e.keys()]},clear(){e.clear()},dispose(){e.clear()}}}});function $1(e){return new Promise((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})}function Ik(e,t){let r=indexedDB.open(e);r.onupgradeneeded=()=>r.result.createObjectStore(t);let n=$1(r);return(o,s)=>n.then(i=>s(i.transaction(t,o).objectStore(t)))}function X8(){return Sk||(Sk=Ik("keyval-store","keyval")),Sk}function Tk(e,t=X8()){return t("readonly",r=>$1(r.get(e)))}function wX(e,t,r=X8()){return r("readwrite",n=>(n.put(t,e),$1(n.transaction)))}function bX(e,t=X8()){return t("readwrite",r=>(r.delete(e),$1(r.transaction)))}function xX(e=X8()){return e("readwrite",t=>(t.clear(),$1(t.transaction)))}function NOe(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},$1(e.transaction)}function vX(e=X8()){return e("readonly",t=>{if(t.getAllKeys)return $1(t.getAllKeys());let r=[];return NOe(t,n=>r.push(n.key)).then(()=>r)})}var Sk,EX=b(()=>{l()});function UOe(e){var t;return[e[0],Fs((t=e[1])!=null?t:"")]}var ROe,OOe,BOe,kOe,Pk,_k,nS,Nk,DOe,AX,LOe,MOe,aw,Rk=b(()=>{l();yX();EX();R1();ROe="idb-keyval",OOe=(e={})=>{let t=e.base&&e.base.length>0?`${e.base}:`:"",r=o=>t+o,n;return e.dbName&&e.storeName&&(n=Ik(e.dbName,e.storeName)),{name:ROe,options:e,async hasItem(o){return!(typeof await Tk(r(o),n)>"u")},async getItem(o){return await Tk(r(o),n)??null},setItem(o,s){return wX(r(o),s,n)},removeItem(o){return bX(r(o),n)},getKeys(){return vX(n)},clear(){return xX(n)}}},BOe="WALLET_CONNECT_V2_INDEXED_DB",kOe="keyvaluestorage",Pk=class{constructor(){this.indexedDb=gX({driver:OOe({dbName:BOe,storeName:kOe})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(t=>[t.key,t.value])}async getItem(t){let r=await this.indexedDb.getItem(t);if(r!==null)return r}async setItem(t,r){await this.indexedDb.setItem(t,wi(r))}async removeItem(t){await this.indexedDb.removeItem(t)}},_k=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},nS={exports:{}};(function(){let e;function t(){}e=t,e.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},e.prototype.setItem=function(r,n){this[r]=String(n)},e.prototype.removeItem=function(r){delete this[r]},e.prototype.clear=function(){let r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},e.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},e.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof _k<"u"&&_k.localStorage?nS.exports=_k.localStorage:typeof window<"u"&&window.localStorage?nS.exports=window.localStorage:nS.exports=new t})();Nk=class{constructor(){this.localStorage=nS.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(UOe)}async getItem(t){let r=this.localStorage.getItem(t);if(r!==null)return Fs(r)}async setItem(t,r){this.localStorage.setItem(t,wi(r))}async removeItem(t){this.localStorage.removeItem(t)}},DOe="wc_storage_version",AX=1,LOe=async(e,t,r)=>{let n=DOe,o=await t.getItem(n);if(o&&o>=AX){r(t);return}let s=await e.getKeys();if(!s.length){r(t);return}let i=[];for(;s.length;){let a=s.shift();if(!a)continue;let c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){let u=await e.getItem(a);await t.setItem(a,u),i.push(a)}}await t.setItem(n,AX),r(t),MOe(e,i)},MOe=async(e,t)=>{t.length&&t.forEach(async r=>{await e.removeItem(r)})},aw=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};let t=new Nk;this.storage=t;try{let r=new Pk;LOe(t,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(t){return await this.initialize(),this.storage.getItem(t)}async setItem(t,r){return await this.initialize(),this.storage.setItem(t,r)}async removeItem(t){return await this.initialize(),this.storage.removeItem(t)}async initialize(){this.initialized||await new Promise(t=>{let r=setInterval(()=>{this.initialized&&(clearInterval(r),t())},20)})}}});var SX,IX,TX,_X,yS,e4,Ok,wS,xh,t4,bS=b(()=>{l();SX="PARSE_ERROR",IX="INVALID_REQUEST",TX="METHOD_NOT_FOUND",_X="INVALID_PARAMS",yS="INTERNAL_ERROR",e4="SERVER_ERROR",Ok=[-32700,-32600,-32601,-32602,-32603],wS=[-32e3,-32099],xh={[SX]:{code:-32700,message:"Parse error"},[IX]:{code:-32600,message:"Invalid Request"},[TX]:{code:-32601,message:"Method not found"},[_X]:{code:-32602,message:"Invalid params"},[yS]:{code:-32603,message:"Internal error"},[e4]:{code:-32e3,message:"Server error"}},t4=e4});function HOe(e){return e<=wS[0]&&e>=wS[1]}function xS(e){return Ok.includes(e)}function PX(e){return typeof e=="number"}function vS(e){return Object.keys(xh).includes(e)?xh[e]:xh[t4]}function ES(e){let t=Object.values(xh).find(r=>r.code===e);return t||xh[t4]}function $Oe(e){if(typeof e.error.code>"u")return{valid:!1,error:"Missing code for JSON-RPC error"};if(typeof e.error.message>"u")return{valid:!1,error:"Missing message for JSON-RPC error"};if(!PX(e.error.code))return{valid:!1,error:`Invalid error code type for JSON-RPC: ${e.error.code}`};if(xS(e.error.code)){let t=ES(e.error.code);if(t.message!==xh[t4].message&&e.error.message===t.message)return{valid:!1,error:`Invalid error code message for JSON-RPC: ${e.error.code}`}}return{valid:!0}}function r4(e,t,r){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${t}`):e}var Bk=b(()=>{l();bS()});var RX=_e(vh=>{"use strict";l();Object.defineProperty(vh,"__esModule",{value:!0});vh.isBrowserCryptoAvailable=vh.getSubtleCrypto=vh.getBrowerCrypto=void 0;function kk(){return(global==null?void 0:global.crypto)||(global==null?void 0:global.msCrypto)||{}}vh.getBrowerCrypto=kk;function NX(){let e=kk();return e.subtle||e.webkitSubtle}vh.getSubtleCrypto=NX;function FOe(){return!!kk()&&!!NX()}vh.isBrowserCryptoAvailable=FOe});var kX=_e(Eh=>{"use strict";l();Object.defineProperty(Eh,"__esModule",{value:!0});Eh.isBrowser=Eh.isNode=Eh.isReactNative=void 0;function OX(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Eh.isReactNative=OX;function BX(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Eh.isNode=BX;function zOe(){return!OX()&&!BX()}Eh.isBrowser=zOe});var Uk=_e(AS=>{"use strict";l();Object.defineProperty(AS,"__esModule",{value:!0});var UX=(b2(),Yx(w2));UX.__exportStar(RX(),AS);UX.__exportStar(kX(),AS)});var wo={};Te(wo,{isNodeJs:()=>LX});var DX,LX,MX=b(()=>{l();DX=Ht(Uk());Bo(wo,Ht(Uk()));LX=DX.isNode});function Tn(e=3){let t=Date.now()*Math.pow(10,e),r=Math.floor(Math.random()*Math.pow(10,e));return t+r}function _n(e=6){return BigInt(Tn(e))}function dr(e,t,r){return{id:r||Tn(),jsonrpc:"2.0",method:e,params:t}}function bo(e,t){return{id:e,jsonrpc:"2.0",result:t}}function la(e,t,r){return{id:e,jsonrpc:"2.0",error:HX(t,r)}}function HX(e,t){return typeof e>"u"?vS(yS):(typeof e=="string"&&(e=Object.assign(Object.assign({},vS(e4)),{message:e})),typeof t<"u"&&(e.data=t),xS(e.code)&&(e=ES(e.code)),e)}var $X=b(()=>{l();Bk();bS()});function VOe(e){return e.includes("*")?SS(e):!/\W/g.test(e)}function CS(e){return e==="*"}function SS(e){return CS(e)?!0:!(!e.includes("*")||e.split("*").length!==2||e.split("*").filter(t=>t.trim()==="").length!==1)}function jOe(e){return!CS(e)&&SS(e)&&!e.split("*")[0].trim()}function qOe(e){return!CS(e)&&SS(e)&&!e.split("*")[1].trim()}var FX=b(()=>{l()});var n4,Dk,IS,o4,zX=b(()=>{l();n4=class{},Dk=class extends n4{constructor(t){super()}},IS=class extends n4{constructor(){super()}},o4=class extends IS{constructor(t){super()}}});var VX=b(()=>{l();zX()});function ZOe(e){let t=e.match(new RegExp(/^\w+:/,"gi"));if(!(!t||!t.length))return t[0]}function jX(e,t){let r=ZOe(e);return typeof r>"u"?!1:new RegExp(t).test(r)}function TS(e){return jX(e,WOe)}function _S(e){return jX(e,KOe)}function Lk(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}var WOe,KOe,qX=b(()=>{l();WOe="^https?:",KOe="^wss?:"});function Mk(e){return typeof e=="object"&&"id"in e&&"jsonrpc"in e&&e.jsonrpc==="2.0"}function Hc(e){return Mk(e)&&"method"in e}function ua(e){return Mk(e)&&(Jr(e)||Ir(e))}function Jr(e){return"result"in e}function Ir(e){return"error"in e}function GOe(e){return"error"in e&&e.valid===!1}var WX=b(()=>{l()});var Ei={};Te(Ei,{DEFAULT_ERROR:()=>t4,IBaseJsonRpcProvider:()=>IS,IEvents:()=>n4,IJsonRpcConnection:()=>Dk,IJsonRpcProvider:()=>o4,INTERNAL_ERROR:()=>yS,INVALID_PARAMS:()=>_X,INVALID_REQUEST:()=>IX,METHOD_NOT_FOUND:()=>TX,PARSE_ERROR:()=>SX,RESERVED_ERROR_CODES:()=>Ok,SERVER_ERROR:()=>e4,SERVER_ERROR_CODE_RANGE:()=>wS,STANDARD_ERROR_MAP:()=>xh,formatErrorMessage:()=>HX,formatJsonRpcError:()=>la,formatJsonRpcRequest:()=>dr,formatJsonRpcResult:()=>bo,getBigIntRpcId:()=>_n,getError:()=>vS,getErrorByCode:()=>ES,isHttpUrl:()=>TS,isJsonRpcError:()=>Ir,isJsonRpcPayload:()=>Mk,isJsonRpcRequest:()=>Hc,isJsonRpcResponse:()=>ua,isJsonRpcResult:()=>Jr,isJsonRpcValidationInvalid:()=>GOe,isLocalhostUrl:()=>Lk,isNodeJs:()=>LX,isReservedErrorCode:()=>xS,isServerErrorCode:()=>HOe,isValidDefaultRoute:()=>CS,isValidErrorCode:()=>PX,isValidLeadingWildcardRoute:()=>jOe,isValidRoute:()=>VOe,isValidTrailingWildcardRoute:()=>qOe,isValidWildcardRoute:()=>SS,isWsUrl:()=>_S,parseConnectionError:()=>r4,payloadId:()=>Tn,validateJsonRpcError:()=>$Oe});var $c=b(()=>{l();bS();Bk();MX();Bo(Ei,wo);$X();FX();VX();qX();WX()});var KX,da,cw=b(()=>{l();KX=Ht(ks());$c();da=class extends o4{constructor(t){super(t),this.events=new KX.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(t=this.connection){await this.open(t)}async disconnect(){await this.close()}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async request(t,r){return this.requestStrict(dr(t.method,t.params||[],t.id||_n().toString()),r)}async requestStrict(t,r){return new Promise(async(n,o)=>{if(!this.connection.connected)try{await this.open()}catch(s){o(s)}this.events.on(`${t.id}`,s=>{Ir(s)?o(s.error):n(s.result)});try{await this.connection.send(t,r)}catch(s){o(s)}})}setConnection(t=this.connection){return t}onPayload(t){this.events.emit("payload",t),ua(t)?this.events.emit(`${t.id}`,t):this.events.emit("message",{type:t.method,data:t.params})}onClose(t){t&&t.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason?`(${t.reason})`:""}`)),this.events.emit("disconnect")}async open(t=this.connection){this.connection===t&&this.connection.connected||(this.connection.connected&&this.close(),typeof t=="string"&&(await this.connection.open(t),t=this.connection),this.connection=this.setConnection(t),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",t=>this.onPayload(t)),this.connection.on("close",t=>this.onClose(t)),this.connection.on("error",t=>this.events.emit("error",t)),this.connection.on("register_error",t=>this.onClose()),this.hasRegisteredEventListeners=!0)}}});var GX=_e((hht,ZX)=>{"use strict";l();ZX.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var QX,YOe,JOe,YX,JX,QOe,lw,Hk=b(()=>{l();QX=Ht(ks());R1();$c();YOe=()=>typeof m<"u"?m:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:GX(),JOe=()=>typeof m<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",YX=e=>e.split("?")[0],JX=10,QOe=YOe(),lw=class{constructor(t){if(this.url=t,this.events=new QX.EventEmitter,this.registering=!1,!_S(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){return new Promise((t,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),t()},this.socket.close()})}async send(t){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(wi(t))}catch(r){this.onError(t.id,r)}}register(t=this.url){if(!_S(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,o)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),o(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return o(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=t,this.registering=!0,new Promise((r,n)=>{let o=(0,Ei.isReactNative)()?void 0:{rejectUnauthorized:!Lk(t)},s=new QOe(t,[],o);JOe()?s.onerror=i=>{let a=i;n(this.emitError(a.error))}:s.on("error",i=>{n(this.emitError(i))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(t){t.onmessage=r=>this.onPayload(r),t.onclose=r=>this.onClose(r),this.socket=t,this.registering=!1,this.events.emit("open")}onClose(t){this.socket=void 0,this.registering=!1,this.events.emit("close",t)}onPayload(t){if(typeof t.data>"u")return;let r=typeof t.data=="string"?Fs(t.data):t.data;this.events.emit("payload",r)}onError(t,r){let n=this.parseError(r),o=n.message||n.toString(),s=la(t,o);this.events.emit("payload",s)}parseError(t,r=this.url){return r4(t,YX(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>JX&&this.events.setMaxListeners(JX)}emitError(t){let r=this.parseError(new Error(t?.message||`WebSocket connection failed for host: ${YX(this.url)}`));return this.events.emit("register_error",r),r}}});var Nee=_e((_h,Pee)=>{l();var eI=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,tI=(function(){function e(){this.fetch=!1,this.DOMException=eI.DOMException}return e.prototype=eI,new e})();(function(e){var t=(function(r){var n=typeof e<"u"&&e||typeof self<"u"&&self||typeof global<"u"&&global||{},o={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function s(P){return P&&DataView.prototype.isPrototypeOf(P)}if(o.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=ArrayBuffer.isView||function(P){return P&&i.indexOf(Object.prototype.toString.call(P))>-1};function c(P){if(typeof P!="string"&&(P=String(P)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(P)||P==="")throw new TypeError('Invalid character in header field name: "'+P+'"');return P.toLowerCase()}function u(P){return typeof P!="string"&&(P=String(P)),P}function d(P){var R={next:function(){var I=P.shift();return{done:I===void 0,value:I}}};return o.iterable&&(R[Symbol.iterator]=function(){return R}),R}function f(P){this.map={},P instanceof f?P.forEach(function(R,I){this.append(I,R)},this):Array.isArray(P)?P.forEach(function(R){if(R.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+R.length);this.append(R[0],R[1])},this):P&&Object.getOwnPropertyNames(P).forEach(function(R){this.append(R,P[R])},this)}f.prototype.append=function(P,R){P=c(P),R=u(R);var I=this.map[P];this.map[P]=I?I+", "+R:R},f.prototype.delete=function(P){delete this.map[c(P)]},f.prototype.get=function(P){return P=c(P),this.has(P)?this.map[P]:null},f.prototype.has=function(P){return this.map.hasOwnProperty(c(P))},f.prototype.set=function(P,R){this.map[c(P)]=u(R)},f.prototype.forEach=function(P,R){for(var I in this.map)this.map.hasOwnProperty(I)&&P.call(R,this.map[I],I,this)},f.prototype.keys=function(){var P=[];return this.forEach(function(R,I){P.push(I)}),d(P)},f.prototype.values=function(){var P=[];return this.forEach(function(R){P.push(R)}),d(P)},f.prototype.entries=function(){var P=[];return this.forEach(function(R,I){P.push([I,R])}),d(P)},o.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);function p(P){if(!P._noBody){if(P.bodyUsed)return Promise.reject(new TypeError("Already read"));P.bodyUsed=!0}}function h(P){return new Promise(function(R,I){P.onload=function(){R(P.result)},P.onerror=function(){I(P.error)}})}function y(P){var R=new FileReader,I=h(R);return R.readAsArrayBuffer(P),I}function w(P){var R=new FileReader,I=h(R),B=/charset=([A-Za-z0-9_-]+)/.exec(P.type),C=B?B[1]:"utf-8";return R.readAsText(P,C),I}function x(P){for(var R=new Uint8Array(P),I=new Array(R.length),B=0;B-1?R:P}function _(P,R){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');R=R||{};var I=R.body;if(P instanceof _){if(P.bodyUsed)throw new TypeError("Already read");this.url=P.url,this.credentials=P.credentials,R.headers||(this.headers=new f(P.headers)),this.method=P.method,this.mode=P.mode,this.signal=P.signal,!I&&P._bodyInit!=null&&(I=P._bodyInit,P.bodyUsed=!0)}else this.url=String(P);if(this.credentials=R.credentials||this.credentials||"same-origin",(R.headers||!this.headers)&&(this.headers=new f(R.headers)),this.method=S(R.method||this.method||"GET"),this.mode=R.mode||this.mode||null,this.signal=R.signal||this.signal||(function(){if("AbortController"in n){var A=new AbortController;return A.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(I),(this.method==="GET"||this.method==="HEAD")&&(R.cache==="no-store"||R.cache==="no-cache")){var B=/([?&])_=[^&]*/;if(B.test(this.url))this.url=this.url.replace(B,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function O(P){var R=new FormData;return P.trim().split("&").forEach(function(I){if(I){var B=I.split("="),C=B.shift().replace(/\+/g," "),A=B.join("=").replace(/\+/g," ");R.append(decodeURIComponent(C),decodeURIComponent(A))}}),R}function D(P){var R=new f,I=P.replace(/\r?\n[\t ]+/g," ");return I.split("\r").map(function(B){return B.indexOf(` +`)===0?B.substr(1,B.length):B}).forEach(function(B){var C=B.split(":"),A=C.shift().trim();if(A){var U=C.join(":").trim();try{R.append(A,U)}catch(H){console.warn("Response "+H.message)}}}),R}T.call(_.prototype);function M(P,R){if(!(this instanceof M))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(R||(R={}),this.type="default",this.status=R.status===void 0?200:R.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=R.statusText===void 0?"":""+R.statusText,this.headers=new f(R.headers),this.url=R.url||"",this._initBody(P)}T.call(M.prototype),M.prototype.clone=function(){return new M(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},M.error=function(){var P=new M(null,{status:200,statusText:""});return P.ok=!1,P.status=0,P.type="error",P};var N=[301,302,303,307,308];M.redirect=function(P,R){if(N.indexOf(R)===-1)throw new RangeError("Invalid status code");return new M(null,{status:R,headers:{location:P}})},r.DOMException=n.DOMException;try{new r.DOMException}catch{r.DOMException=function(R,I){this.message=R,this.name=I;var B=Error(R);this.stack=B.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function L(P,R){return new Promise(function(I,B){var C=new _(P,R);if(C.signal&&C.signal.aborted)return B(new r.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function U(){A.abort()}A.onload=function(){var F={statusText:A.statusText,headers:D(A.getAllResponseHeaders()||"")};C.url.indexOf("file://")===0&&(A.status<200||A.status>599)?F.status=200:F.status=A.status,F.url="responseURL"in A?A.responseURL:F.headers.get("X-Request-URL");var j="response"in A?A.response:A.responseText;setTimeout(function(){I(new M(j,F))},0)},A.onerror=function(){setTimeout(function(){B(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){B(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){B(new r.DOMException("Aborted","AbortError"))},0)};function H(F){try{return F===""&&n.location.href?n.location.href:F}catch{return F}}if(A.open(C.method,H(C.url),!0),C.credentials==="include"?A.withCredentials=!0:C.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(o.blob?A.responseType="blob":o.arrayBuffer&&(A.responseType="arraybuffer")),R&&typeof R.headers=="object"&&!(R.headers instanceof f||n.Headers&&R.headers instanceof n.Headers)){var k=[];Object.getOwnPropertyNames(R.headers).forEach(function(F){k.push(c(F)),A.setRequestHeader(F,u(R.headers[F]))}),C.headers.forEach(function(F,j){k.indexOf(j)===-1&&A.setRequestHeader(j,F)})}else C.headers.forEach(function(F,j){A.setRequestHeader(j,F)});C.signal&&(C.signal.addEventListener("abort",U),A.onreadystatechange=function(){A.readyState===4&&C.signal.removeEventListener("abort",U)}),A.send(typeof C._bodyInit>"u"?null:C._bodyInit)})}return L.polyfill=!0,n.fetch||(n.fetch=L,n.Headers=f,n.Request=_,n.Response=M),r.Headers=f,r.Request=_,r.Response=M,r.fetch=L,Object.defineProperty(r,"__esModule",{value:!0}),r})({})})(tI);tI.fetch.ponyfill=!0;delete tI.fetch.polyfill;var bw=eI.fetch?eI:tI;_h=bw.fetch;_h.default=bw.fetch;_h.fetch=bw.fetch;_h.Headers=bw.Headers;_h.Request=bw.Request;_h.Response=bw.Response;Pee.exports=_h});var Lee,yU,KBe,ZBe,GBe,Ree,YBe,JBe,Oee,Bee,kee,QBe,XBe,Uee,Dee,Ja,rI=b(()=>{l();Lee=Ht(ks()),yU=Ht(Nee());R1();$c();KBe=Object.defineProperty,ZBe=Object.defineProperties,GBe=Object.getOwnPropertyDescriptors,Ree=Object.getOwnPropertySymbols,YBe=Object.prototype.hasOwnProperty,JBe=Object.prototype.propertyIsEnumerable,Oee=(e,t,r)=>t in e?KBe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Bee=(e,t)=>{for(var r in t||(t={}))YBe.call(t,r)&&Oee(e,r,t[r]);if(Ree)for(var r of Ree(t))JBe.call(t,r)&&Oee(e,r,t[r]);return e},kee=(e,t)=>ZBe(e,GBe(t)),QBe={Accept:"application/json","Content-Type":"application/json"},XBe="POST",Uee={headers:QBe,method:XBe},Dee=10,Ja=class{constructor(t,r=!1){if(this.url=t,this.disableProviderPing=r,this.events=new Lee.EventEmitter,this.isAvailable=!1,this.registering=!1,!TS(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async open(t=this.url){await this.register(t)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(t){this.isAvailable||await this.register();try{let r=wi(t),n=await(await(0,yU.default)(this.url,kee(Bee({},Uee),{body:r}))).json();this.onPayload({data:n})}catch(r){this.onError(t.id,r)}}async register(t=this.url){if(!TS(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);if(this.registering){let r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,o)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),o(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return o(new Error("HTTP connection is missing or invalid"));n()})})}this.url=t,this.registering=!0;try{if(!this.disableProviderPing){let r=wi({id:1,jsonrpc:"2.0",method:"test",params:[]});await(0,yU.default)(t,kee(Bee({},Uee),{body:r}))}this.onOpen()}catch(r){let n=this.parseError(r);throw this.events.emit("register_error",n),this.onClose(),n}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(t){if(typeof t.data>"u")return;let r=typeof t.data=="string"?Fs(t.data):t.data;this.events.emit("payload",r)}onError(t,r){let n=this.parseError(r),o=n.message||n.toString(),s=la(t,o);this.events.emit("payload",s)}parseError(t,r=this.url){return r4(t,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Dee&&this.events.setMaxListeners(Dee)}}});var l4,ete=b(()=>{l();l4={isLowerCaseMatch(e,t){return e?.toLowerCase()===t?.toLowerCase()}}});var Z,u4=b(()=>{l();Z={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:typeof process<"u"&&!1,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"}});var V1,sI,tte=b(()=>{l();u4();V1={caipNetworkIdToNumber(e){return e?Number(e.split(":")[1]):void 0},parseEvmChainId(e){return typeof e=="string"?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace(e,t){return e?.filter(r=>r.chainNamespace===t)||[]},getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;let r=e.find(o=>o.caipNetworkId===t);if(r)return r.name;let[n]=t.split(":");return Z.CHAIN_NAME_MAP?.[n]||void 0}},sI=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"]});function ote(){function e(t){var r=this;if(!(r instanceof e))return t===Wl?ote():new e(t);if(t instanceof e)r.s=t.s,r.e=t.e,r.c=t.c.slice();else{if(typeof t!="string"){if(e.strict===!0&&typeof t!="bigint")throw TypeError(q1+"value");t=t===0&&1/t<0?"-0":String(t)}Cke(r,t)}r.constructor=e}return e.prototype=yr,e.DP=yke,e.RM=wke,e.NE=bke,e.PE=xke,e.strict=vke,e.roundDown=0,e.roundHalfUp=1,e.roundHalfEven=2,e.roundUp=3,e}function Cke(e,t){var r,n,o;if(!Ake.test(t))throw Error(q1+"number");for(e.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),o=t.length,n=0;n0&&t.charAt(--o)=="0";);for(e.e=r-n-1,e.c=[],r=0;n<=o;)e.c[r++]=+t.charAt(n++)}return e}function W1(e,t,r,n){var o=e.c;if(r===Wl&&(r=e.constructor.RM),r!==0&&r!==1&&r!==2&&r!==3)throw Error(Eke);if(t<1)n=r===3&&(n||!!o[0])||t===0&&(r===1&&o[0]>=5||r===2&&(o[0]>5||o[0]===5&&(n||o[1]!==Wl))),o.length=1,n?(e.e=e.e-t+1,o[0]=1):o[0]=e.e=0;else if(t=5||r===2&&(o[t]>5||o[t]===5&&(n||o[t+1]!==Wl||o[t-1]&1))||r===3&&(n||!!o[0]),o.length=t,n){for(;++o[--t]>9;)if(o[t]=0,t===0){++e.e,o.unshift(1);break}}for(t=o.length;!o[--t];)o.pop()}return e}function K1(e,t,r){var n=e.e,o=e.c.join(""),s=o.length;if(t)o=o.charAt(0)+(s>1?"."+o.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)o="0"+o;o="0."+o}else if(n>0)if(++n>s)for(n-=s;n--;)o+="0";else n1&&(o=o.charAt(0)+"."+o.slice(1));return e.s<0&&r?"-"+o:o}var yke,wke,j1,rte,bke,xke,vke,d4,q1,iI,Eke,nte,yr,Wl,Ake,Ske,Vc,ste=b(()=>{l();yke=20,wke=1,j1=1e6,rte=1e6,bke=-7,xke=21,vke=!1,d4="[big.js] ",q1=d4+"Invalid ",iI=q1+"decimal places",Eke=q1+"rounding mode",nte=d4+"Division by zero",yr={},Wl=void 0,Ake=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;yr.abs=function(){var e=new this.constructor(this);return e.s=1,e};yr.cmp=function(e){var t,r=this,n=r.c,o=(e=new r.constructor(e)).c,s=r.s,i=e.s,a=r.e,c=e.e;if(!n[0]||!o[0])return n[0]?s:o[0]?-i:0;if(s!=i)return s;if(t=s<0,a!=c)return a>c^t?1:-1;for(i=(a=n.length)<(c=o.length)?a:c,s=-1;++so[s]^t?1:-1;return a==c?0:a>c^t?1:-1};yr.div=function(e){var t=this,r=t.constructor,n=t.c,o=(e=new r(e)).c,s=t.s==e.s?1:-1,i=r.DP;if(i!==~~i||i<0||i>j1)throw Error(iI);if(!o[0])throw Error(nte);if(!n[0])return e.s=s,e.c=[e.e=0],e;var a,c,u,d,f,p=o.slice(),h=a=o.length,y=n.length,w=n.slice(0,a),x=w.length,v=e,T=v.c=[],E=0,S=i+(v.e=t.e-e.e)+1;for(v.s=s,s=S<0?0:S,p.unshift(0);x++x?1:-1;else for(f=-1,d=0;++fw[f]?1:-1;break}if(d<0){for(c=x==a?o:p;x;){if(w[--x]S&&W1(v,S,r.RM,w[0]!==Wl),v};yr.eq=function(e){return this.cmp(e)===0};yr.gt=function(e){return this.cmp(e)>0};yr.gte=function(e){return this.cmp(e)>-1};yr.lt=function(e){return this.cmp(e)<0};yr.lte=function(e){return this.cmp(e)<1};yr.minus=yr.sub=function(e){var t,r,n,o,s=this,i=s.constructor,a=s.s,c=(e=new i(e)).s;if(a!=c)return e.s=-c,s.plus(e);var u=s.c.slice(),d=s.e,f=e.c,p=e.e;if(!u[0]||!f[0])return f[0]?e.s=-c:u[0]?e=new i(s):e.s=1,e;if(a=d-p){for((o=a<0)?(a=-a,n=u):(p=d,n=f),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(r=((o=u.length0)for(;c--;)u[t++]=0;for(c=t;r>a;){if(u[--r]0?(c=i,n=u):(t=-t,n=a),n.reverse();t--;)n.push(0);n.reverse()}for(a.length-u.length<0&&(n=u,u=a,a=n),t=u.length,r=0;t;a[t]%=10)r=(a[--t]=a[t]+u[t]+r)/10|0;for(r&&(a.unshift(r),++c),t=a.length;a[--t]===0;)a.pop();return e.c=a,e.e=c,e};yr.pow=function(e){var t=this,r=new t.constructor("1"),n=r,o=e<0;if(e!==~~e||e<-rte||e>rte)throw Error(q1+"exponent");for(o&&(e=-e);e&1&&(n=n.times(t)),e>>=1,!!e;)t=t.times(t);return o?r.div(n):n};yr.prec=function(e,t){if(e!==~~e||e<1||e>j1)throw Error(q1+"precision");return W1(new this.constructor(this),e,t)};yr.round=function(e,t){if(e===Wl)e=0;else if(e!==~~e||e<-j1||e>j1)throw Error(iI);return W1(new this.constructor(this),e+this.e+1,t)};yr.sqrt=function(){var e,t,r,n=this,o=n.constructor,s=n.s,i=n.e,a=new o("0.5");if(!n.c[0])return new o(n);if(s<0)throw Error(d4+"No square root");s=Math.sqrt(+K1(n,!0,!0)),s===0||s===1/0?(t=n.c.join(""),t.length+i&1||(t+="0"),s=Math.sqrt(t),i=((i+1)/2|0)-(i<0||i&1),e=new o((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+i)):e=new o(s+""),i=e.e+(o.DP+=4);do r=e,e=a.times(r.plus(n.div(r)));while(r.c.slice(0,i).join("")!==e.c.slice(0,i).join(""));return W1(e,(o.DP-=4)+e.e+1,o.RM)};yr.times=yr.mul=function(e){var t,r=this,n=r.constructor,o=r.c,s=(e=new n(e)).c,i=o.length,a=s.length,c=r.e,u=e.e;if(e.s=r.s==e.s?1:-1,!o[0]||!s[0])return e.c=[e.e=0],e;for(e.e=c+u,ic;)a=t[u]+s[c]*o[u-c-1]+a,t[u--]=a%10,a=a/10|0;t[u]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e};yr.toExponential=function(e,t){var r=this,n=r.c[0];if(e!==Wl){if(e!==~~e||e<0||e>j1)throw Error(iI);for(r=W1(new r.constructor(r),++e,t);r.c.lengthj1)throw Error(iI);for(r=W1(new r.constructor(r),e+r.e+1,t),e=e+r.e+1;r.c.length=t.PE,!!e.c[0])};yr.toNumber=function(){var e=+K1(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(e.toString()))throw Error(d4+"Imprecise conversion");return e};yr.toPrecision=function(e,t){var r=this,n=r.constructor,o=r.c[0];if(e!==Wl){if(e!==~~e||e<1||e>j1)throw Error(q1+"precision");for(r=W1(new n(r),e,t);r.c.length=n.PE,!!o)};yr.valueOf=function(){var e=this,t=e.constructor;if(t.strict===!0)throw Error(d4+"valueOf disallowed");return K1(e,e.e<=t.NE||e.e>=t.PE,!0)};Ske=ote(),Vc=Ske});var ht,ite=b(()=>{l();ste();ht={bigNumber(e,t={safe:!1}){try{return e?new Vc(e):new Vc(0)}catch(r){if(t.safe)return new Vc(0);throw r}},formatNumber(e,t){let{decimals:r,round:n=8,safe:o=!0}=t;return ht.bigNumber(e,{safe:o}).div(new Vc(10).pow(r)).round(n)},multiply(e,t){if(e===void 0||t===void 0)return new Vc(0);let r=new Vc(e),n=new Vc(t);return r.times(n)},toFixed(e,t=2){return e===void 0||e===""?new Vc(0).toFixed(t):new Vc(e).toFixed(t)},formatNumberToLocalString(e,t=2){return e===void 0||e===""?"0.00":typeof e=="number"?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"})},parseLocalStringToNumber(e){if(e===void 0||e==="")return 0;let t=e.replace(/,/gu,"");return new Vc(t).toNumber()}}});var ate,cte=b(()=>{l();ate=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]});var lte,ute=b(()=>{l();lte=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]});var dte,fte=b(()=>{l();dte=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}]});var f4,pte=b(()=>{l();cte();ute();fte();u4();f4={getERC20Abi:e=>Z.USDT_CONTRACT_ADDRESSES.includes(e)?dte:ate,getSwapAbi:()=>lte}});var Ph,hte=b(()=>{l();u4();Ph={ConnectorExplorerIds:{[Z.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[Z.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[Z.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[Z.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Z.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Z.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Z.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Z.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Z.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Z.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Z.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Z.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Z.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Z.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Z.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Z.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Z.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"},ConnectorImageIds:{[Z.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[Z.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[Z.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[Z.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[Z.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[Z.CONNECTOR_ID.INJECTED]:"Browser Wallet",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[Z.CONNECTOR_ID.COINBASE]:"Coinbase",[Z.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[Z.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[Z.CONNECTOR_ID.LEDGER]:"Ledger",[Z.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[Z.CONNECTOR_ID.INJECTED]:"INJECTED",[Z.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[Z.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[Z.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]}});var lt,mte=b(()=>{l();lt={validateCaipAddress(e){if(e.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){let t=e.split(":");if(t.length!==3)throw new Error(`Invalid CAIP-10 address: ${e}`);let[r,n,o]=t;if(!r||!n||!o)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:r,chainId:n,address:o}},parseCaipNetworkId(e){let t=e.split(":");if(t.length!==2)throw new Error(`Invalid CAIP-2 network id: ${e}`);let[r,n]=t;if(!r||!n)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:r,chainId:n}}}});var js,IU,Z1,gte=b(()=>{l();js={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if(typeof e=="object"&&e!==null){let t=e,r=typeof t.message=="string",n=typeof t.code=="number";return r&&n}return!1}catch{return!1}},isUserRejectedMessage(e){return e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled")},isUserRejectedRequestError(e){if(js.isRpcProviderError(e)){let t=e.code===js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,r=e.code===js.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||r||js.isUserRejectedMessage(e.message)}return e instanceof Error?js.isUserRejectedMessage(e.message):!1}},IU=class extends Error{constructor(t,r){super(r.message,{cause:t}),this.name=js.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=r.code}},Z1=class extends IU{constructor(t){super(t,{code:js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}});function p4(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}function G1(){return typeof window<"u"&&typeof localStorage<"u"}var Fe,Le,yte=b(()=>{l();Fe={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};Le={setItem(e,t){G1()&&t!==void 0&&localStorage.setItem(e,t)},getItem(e){if(G1())return localStorage.getItem(e)||void 0},removeItem(e){G1()&&localStorage.removeItem(e)},clear(){G1()&&localStorage.clear()}}});function Y1(e,t){let r=e?.["--apkt-accent"]??e?.["--w3m-accent"];return t==="light"?{"--w3m-accent":r||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":r||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}var wte=b(()=>{l()});var ut=b(()=>{l();ete();tte();ite();pte();u4();hte();mte();gte();yte();wte()});var Ike,bte,TU,Tke,xte,_U,vte=b(()=>{l();Ike=Symbol(),bte=Object.getPrototypeOf,TU=new WeakMap,Tke=e=>e&&(TU.has(e)?TU.get(e):bte(e)===Object.prototype||bte(e)===Array.prototype),xte=e=>Tke(e)&&e[Ike]||null,_U=(e,t=!0)=>{TU.set(e,t)}});function rt(e={}){if(!NU(e))throw new Error("object required");let t=h4.get(e);if(t)return t;let r=aI[0],n=new Set,o=(x,v=++aI[0])=>{r!==v&&(s=r=v,n.forEach(T=>T(x,v)))},s=r,i=(x=aI[0])=>(s!==x&&(s=x,c.forEach(([v])=>{let T=v[1](x);T>r&&(r=T)})),r),a=x=>(v,T)=>{let E=[...v];E[1]=[x,...E[1]],o(E,T)},c=new Map,u=(x,v)=>{let T=!m4.has(v)&&Nh.get(v);if(T){if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&c.has(x))throw new Error("prop listener already exists");if(n.size){let E=T[2](a(x));c.set(x,[T,E])}else c.set(x,[T])}},d=x=>{var v;let T=c.get(x);T&&(c.delete(x),(v=T[1])==null||v.call(T))},f=x=>(n.add(x),n.size===1&&c.forEach(([T,E],S)=>{if((import.meta.env?import.meta.env.MODE:void 0)!=="production"&&E)throw new Error("remove already exists");let _=T[2](a(S));c.set(S,[T,_])}),()=>{n.delete(x),n.size===0&&c.forEach(([T,E],S)=>{E&&(E(),c.set(S,[T]))})}),p=!0,h=Bke(()=>p,u,d,o),y=Nke(e,h);h4.set(e,y);let w=[e,i,f];return Nh.set(y,w),Reflect.ownKeys(e).forEach(x=>{let v=Object.getOwnPropertyDescriptor(e,x);"value"in v&&v.writable&&(y[x]=e[x])}),p=!1,y}function Dt(e,t,r){let n=Nh.get(e);(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!n&&console.warn("Please use proxy object");let o,s=[],i=n[2],a=!1,u=i(d=>{if(s.push(d),r){t(s.splice(0));return}o||(o=Promise.resolve().then(()=>{o=void 0,a&&t(s.splice(0))}))});return a=!0,()=>{a=!1,u()}}function Kl(e){let t=Nh.get(e);(import.meta.env?import.meta.env.MODE:void 0)!=="production"&&!t&&console.warn("Please use proxy object");let[r,n]=t;return Oke(r,n())}function vf(e){return m4.add(e),e}function RU(){return{proxyStateMap:Nh,refSet:m4,snapCache:PU,versionHolder:aI,proxyCache:h4}}var NU,_ke,Ate,Pke,Nh,m4,PU,aI,h4,Ete,Nke,Rke,Oke,Bke,Lr=b(()=>{l();vte();NU=e=>typeof e=="object"&&e!==null,_ke=e=>NU(e)&&!m4.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),Ate=(e,t)=>{let r=PU.get(e);if(r?.[0]===t)return r[1];let n=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return _U(n,!0),PU.set(e,[t,n]),Reflect.ownKeys(e).forEach(o=>{if(Object.getOwnPropertyDescriptor(n,o))return;let s=Reflect.get(e,o),{enumerable:i}=Reflect.getOwnPropertyDescriptor(e,o),a={value:s,enumerable:i,configurable:!0};if(m4.has(s))_U(s,!1);else if(Nh.has(s)){let[c,u]=Nh.get(s);a.value=Ate(c,u())}Object.defineProperty(n,o,a)}),Object.preventExtensions(n)},Pke=(e,t,r,n)=>({deleteProperty(o,s){let i=Reflect.get(o,s);r(s);let a=Reflect.deleteProperty(o,s);return a&&n(["delete",[s],i]),a},set(o,s,i,a){let c=!e()&&Reflect.has(o,s),u=Reflect.get(o,s,a);if(c&&(Ete(u,i)||h4.has(i)&&Ete(u,h4.get(i))))return!0;r(s),NU(i)&&(i=xte(i)||i);let d=!Nh.has(i)&&Rke(i)?rt(i):i;return t(s,d),Reflect.set(o,s,d,a),n(["set",[s],i,u]),!0}}),Nh=new WeakMap,m4=new WeakSet,PU=new WeakMap,aI=[1],h4=new WeakMap,Ete=Object.is,Nke=(e,t)=>new Proxy(e,t),Rke=_ke,Oke=Ate,Bke=Pke});function Tt(e,t,r,n){let o=e[t];return Dt(e,()=>{let s=e[t];Object.is(o,s)||r(o=s)},n)}function Cte(e){let t=[],r=0,n=new Map,o=new WeakMap,s=()=>{let u=Uke.get(a),d=u?.[1];if(d&&!o.has(d)){let f=new Map(n);o.set(d,f)}},i=u=>o.get(u)||n;if(e){if(typeof e[Symbol.iterator]!="function")throw new TypeError(`proxyMap: initial state must be iterable tip: structure should be [[key, value]]`);for(let[u,d]of e)n.set(u,r),t[r++]=d}let a={data:t,index:r,epoch:0,get size(){return cI(this)||s(),i(this).size},get(u){let f=i(this).get(u);if(f===void 0){this.epoch;return}return this.data[f]},has(u){let d=i(this);return this.epoch,d.has(u)},set(u,d){if(!cI(this))throw new Error("Cannot perform mutations on a snapshot");let f=n.get(u);return f===void 0?(n.set(u,this.index),this.data[this.index++]=d):this.data[f]=d,this.epoch++,this},delete(u){if(!cI(this))throw new Error("Cannot perform mutations on a snapshot");let d=n.get(u);return d===void 0?!1:(delete this.data[d],n.delete(u),this.epoch++,!0)},clear(){if(!cI(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(u){this.epoch,i(this).forEach((f,p)=>{u(this.data[f],p,this)})},*entries(){this.epoch;let u=i(this);for(let[d,f]of u)yield[d,this.data[f]]},*keys(){this.epoch;let u=i(this);for(let d of u.keys())yield d},*values(){this.epoch;let u=i(this);for(let d of u.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=rt(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}var kke,Uke,cI,U1t,D1t,Hn=b(()=>{l();Lr();({proxyStateMap:kke,snapCache:Uke}=RU()),cI=e=>kke.has(e);({proxyStateMap:U1t,snapCache:D1t}=RU())});var OU,BU,Ste,Ye,ha=b(()=>{l();ut();OU=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",BU=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Ste="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ye={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:OU,SECURE_SITE_DASHBOARD:`${OU}/dashboard`,SECURE_SITE_FAVICON:`${OU}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD\u20AE0"]},BALANCE_SUPPORTED_CHAINS:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[Z.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[Z.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[Z.CHAIN.EVM,Z.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[Ph.ConnectorExplorerIds[Z.CONNECTOR_ID.COINBASE],Ph.ConnectorExplorerIds[Z.CONNECTOR_ID.COINBASE_SDK],Ph.ConnectorExplorerIds[Z.CONNECTOR_ID.BASE_ACCOUNT],Ph.ConnectorExplorerIds[Z.SOLFLARE_CONNECTOR_NAME],Ph.ConnectorExplorerIds[Z.PHANTOM_CONNECTOR_NAME],Ph.ConnectorExplorerIds[Z.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]}});var de,ma=b(()=>{l();ut();de={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired(e,t){return Date.now()-e>t},getActiveNetworkProps(){let e=de.getActiveNamespace(),t=de.getActiveCaipNetworkId(),r=t?t.split(":")[1]:void 0,n=r?isNaN(Number(r))?r:Number(r):void 0;return{namespace:e,caipNetworkId:t,chainId:n}},setWalletConnectDeepLink({name:e,href:t}){try{Le.setItem(Fe.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{let e=Le.getItem(Fe.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Le.removeItem(Fe.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{Le.setItem(Fe.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{Le.setItem(Fe.ACTIVE_CAIP_NETWORK_ID,e),de.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Le.getItem(Fe.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Le.removeItem(Fe.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{let t=p4(e);Le.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{let t=de.getRecentWallets();t.find(n=>n.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Le.setItem(Fe.RECENT_WALLETS,JSON.stringify(t)),Le.setItem(Fe.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{let e=Le.getItem(Fe.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{let e=Le.getItem(Fe.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Le.removeItem(Fe.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{let r=p4(e);Le.setItem(r,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Le.getItem(Fe.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{let t=p4(e);return Le.getItem(t)}catch{console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{Le.setItem(Fe.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Le.getItem(Fe.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Le.removeItem(Fe.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Le.getItem(Fe.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Le.getItem(Fe.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(e){try{Le.setItem(Fe.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Le.getItem(Fe.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{let e=Le.getItem(Fe.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{let t=Array.from(new Set(e));Le.setItem(Fe.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{let t=de.getConnectedNamespaces();t.includes(e)||(t.push(e),de.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{let t=de.getConnectedNamespaces(),r=t.indexOf(e);r>-1&&(t.splice(r,1),de.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Le.getItem(Fe.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{Le.setItem(Fe.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Le.removeItem(Fe.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{let t=Le.getItem(Fe.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{let t=de.getBalanceCache();Le.setItem(Fe.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{let r=de.getBalanceCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.portfolio))return r.balance;de.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{let t=de.getBalanceCache();t[e.caipAddress]=e,Le.setItem(Fe.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{let t=Le.getItem(Fe.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{let t=de.getBalanceCache();Le.setItem(Fe.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{let r=de.getNativeBalanceCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.nativeBalance))return r;console.info("Discarding cache for address",e),de.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{let t=de.getNativeBalanceCache();t[e.caipAddress]=e,Le.setItem(Fe.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{let t=Le.getItem(Fe.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{let r=de.getEnsCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.ens))return r.ens;de.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{let t=de.getEnsCache();t[e.address]=e,Le.setItem(Fe.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{let t=de.getEnsCache();Le.setItem(Fe.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{let t=Le.getItem(Fe.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{let r=de.getIdentityCache()[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.identity))return r.identity;de.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{let t=de.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Le.setItem(Fe.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{let t=de.getIdentityCache();Le.setItem(Fe.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{let e=Le.getItem(Fe.TON_WALLETS_CACHE),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;de.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{let t=de.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=new Date().getTime(),t.wallets=e,Le.setItem(Fe.TON_WALLETS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{Le.removeItem(Fe.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{Le.removeItem(Fe.PORTFOLIO_CACHE),Le.removeItem(Fe.NATIVE_BALANCE_CACHE),Le.removeItem(Fe.ENS_CACHE),Le.removeItem(Fe.IDENTITY_CACHE),Le.removeItem(Fe.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{Le.setItem(Fe.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{let e=Le.getItem(Fe.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{let r=de.getConnections(),n=r[t]??[],o=new Map;for(let i of n)o.set(i.connectorId,{...i});for(let i of e){let a=o.get(i.connectorId),c=i.connectorId===Z.CONNECTOR_ID.AUTH;if(a&&!c){let u=new Set(a.accounts.map(f=>f.address.toLowerCase())),d=i.accounts.filter(f=>!u.has(f.address.toLowerCase()));a.accounts.push(...d)}else o.set(i.connectorId,{...i})}let s={...r,[t]:Array.from(o.values())};Le.setItem(Fe.CONNECTIONS,JSON.stringify(s))}catch(r){console.error("Unable to sync connections to storage",r)}},getConnections(){try{let e=Le.getItem(Fe.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:r}){try{let n=de.getConnections(),o=n[r]??[],s=new Map(o.map(a=>[a.connectorId,a])),i=s.get(e);i&&(i.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase()).length===0?s.delete(e):s.set(e,{...i,accounts:i.accounts.filter(c=>c.address.toLowerCase()!==t.toLowerCase())})),Le.setItem(Fe.CONNECTIONS,JSON.stringify({...n,[r]:Array.from(s.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${r}"`)}},getDisconnectedConnectorIds(){try{let e=Le.getItem(Fe.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{let r=de.getDisconnectedConnectorIds(),n=r[t]??[];n.push(e),Le.setItem(Fe.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...r,[t]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{let r=de.getDisconnectedConnectorIds(),n=r[t]??[];n=n.filter(o=>o.toLowerCase()!==e.toLowerCase()),Le.setItem(Fe.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...r,[t]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{return(de.getDisconnectedConnectorIds()[t]??[]).some(o=>o.toLowerCase()===e.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{let e=Le.getItem(Fe.HISTORY_TRANSACTIONS_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{let n=de.getTransactionsCache()[e]?.[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.transactionsHistory))return n.transactions;de.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:r,transactions:n}){try{let o=de.getTransactionsCache();o[e]={...o[e],[t]:{timestamp:r,transactions:n}},Le.setItem(Fe.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(o))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:r,transactions:n})}},removeTransactionsCache({address:e,chainId:t}){try{let r=de.getTransactionsCache(),n=r?.[e]||{},{[t]:o,...s}=n;Le.setItem(Fe.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...r,[e]:s}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{let e=Le.getItem(Fe.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{let r=de.getTokenPriceCache()[e.join(",")];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.tokenPrice))return r.tokenPrice;de.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{let t=de.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},Le.setItem(Fe.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{let t=de.getTokenPriceCache();Le.setItem(Fe.TOKEN_PRICE_CACHE,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{let e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{let e=Le.getItem(Fe.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{let t=de.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,Le.setItem(Fe.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}}});var se,$n=b(()=>{l();ut();ha();ma();se={getWindow(){if(!(typeof window>"u"))return window},isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(e,t=""){return e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;let e=window?.navigator.userAgent.toLowerCase();return se.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;let e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(e){return e?e-Date.now()<=Ye.TEN_SEC_MS:!0},isAllowedRetry(e,t=Ye.ONE_SEC_MS){return Date.now()-e>=t},copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(se.isClient()&&window.self!==window.top)try{let e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){let r=new URL(e),n=new URL(t);return r.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ye.FOUR_MINUTES_MS},getNetworkId(e){return e?.split(":")[1]},getPlainAddress(e){return e?.split(":")[2]},async wait(e){return new Promise(t=>{setTimeout(t,e)})},debounce(e,t=500){let r;return(...n)=>{function o(){e(...n)}r&&clearTimeout(r),r=setTimeout(o,t)}},isHttpUrl(e){return e.startsWith("http://")||e.startsWith("https://")},formatNativeUrl(e,t,r=null){if(se.isHttpUrl(e))return this.formatUniversalUrl(e,t);let n=e,o=r;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),o&&!o?.endsWith("/")&&(o=`${o}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));let s=encodeURIComponent(t);return{redirect:`${n}wc?uri=${s}`,redirectUniversalLink:o?`${o}wc?uri=${s}`:void 0,href:n}},formatUniversalUrl(e,t){if(!se.isHttpUrl(e))return this.formatNativeUrl(e,t);let r=e;r.endsWith("/")||(r=`${r}/`);let n=encodeURIComponent(t);return{redirect:`${r}wc?uri=${n}`,href:r}},getOpenTargetForPlatform(e){return e==="popupWindow"?e:this.isTelegram()?de.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,r){window?.open(e,this.getOpenTargetForPlatform(t),r||"noreferrer noopener")},returnOpenHref(e,t,r){return window?.open(e,this.getOpenTargetForPlatform(t),r||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;let e=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,t=window?.navigator?.standalone;return!!(e||t)},async preloadImage(e){let t=new Promise((r,n)=>{let o=new Image;o.onload=r,o.onerror=n,o.crossOrigin="anonymous",o.src=e});return Promise.race([t,se.wait(2e3)])},parseBalance(e,t){let r="0.000";if(typeof e=="string"){let c=Number(e);if(!isNaN(c)){let u=(Math.floor(c*1e3)/1e3).toFixed(3);u&&(r=u)}}let[n,o]=r.split("."),s=n||"0",i=o||"000";return{formattedText:`${s}.${i}${t?` ${t}`:""}`,value:s,decimals:i,symbol:t}},getApiUrl(){return Z.W3M_API_URL},getBlockchainApiUrl(){return Z.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return Z.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})},parseError(e){return typeof e=="string"?e:typeof e?.issues?.[0]?.message=="string"?e.issues[0].message:e instanceof Error?e.message:"Unknown error"},sortRequestedNetworks(e,t=[]){let r={};return t&&e&&(e.forEach((n,o)=>{r[n]=o}),t.sort((n,o)=>{let s=r[n.id],i=r[o.id];return s!==void 0&&i!==void 0?s-i:s!==void 0?-1:i!==void 0?1:0})),t},calculateBalance(e){let t=0;for(let r of e)t+=r.value??0;return t},formatTokenBalance(e){let t=e.toFixed(2),[r,n]=t.split(".");return{dollars:r,pennies:n}},isAddress(e,t="eip155"){switch(t){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(e)||/^(?:0x)?[0-9A-F]{40}$/iu.test(e))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);case"bip122":{let r=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),n=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),o=/^bc1[a-z0-9]{39,87}$/u.test(e),s=/^bc1p[a-z0-9]{58}$/u.test(e);return r||n||o||s}default:return!1}},uniqueBy(e,t){let r=new Set;return e.filter(n=>{let o=n[t];return r.has(o)?!1:(r.add(o),!0)})},generateSdkVersion(e,t,r){let o=e.length===0?Ye.ADAPTER_TYPES.UNIVERSAL:e.map(s=>s.adapterType).join(",");return`${t}-${o}-${r}`},createAccount(e,t,r,n,o){return{namespace:e,address:t,type:r,publicKey:n,path:o}},isCaipAddress(e){if(typeof e!="string")return!1;let t=e.split(":"),r=t[0];return t.filter(Boolean).length===3&&r in Z.CHAIN_NAME_MAP},getAccount(e){return e?typeof e=="string"?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0}},isMac(){let e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){let t=`--${encodeURIComponent(window?.location.href)}`,r="state=";if(new URL(e).host==="auth.magic.link"){let o="provider_authorization_url=",s=e.substring(e.indexOf(o)+o.length),i=this.injectIntoUrl(decodeURIComponent(s),r,t);return e.replace(s,encodeURIComponent(i))}return this.injectIntoUrl(e,r,t)},injectIntoUrl(e,t,r){let n=e.indexOf(t);if(n===-1)throw new Error(`${t} parameter not found in the URL: ${e}`);let o=e.indexOf("&",n),s=t.length,i=o!==-1?o:e.length,a=e.substring(0,n+s),c=e.substring(n+s,i),u=e.substring(o),d=c+r;return a+d+u},isNumber(e){return typeof e!="number"&&typeof e!="string"?!1:!isNaN(Number(e))}}});var Dke,Y1t,J1t,Q1t,Qa,Kr,g4=b(()=>{l();Dke="https://secure.walletconnect.org/sdk",Y1t=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL:void 0)||Dke,J1t=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL:void 0)||"error",Q1t=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION:void 0)||"4",Qa={APP_EVENT_KEY:"@w3m-app/",FRAME_EVENT_KEY:"@w3m-frame/",RPC_METHOD_KEY:"RPC_",STORAGE_KEY:"@appkit-wallet/",SESSION_TOKEN_KEY:"SESSION_TOKEN_KEY",EMAIL_LOGIN_USED_KEY:"EMAIL_LOGIN_USED_KEY",LAST_USED_CHAIN_KEY:"LAST_USED_CHAIN_KEY",LAST_EMAIL_LOGIN_TIME:"LAST_EMAIL_LOGIN_TIME",EMAIL:"EMAIL",PREFERRED_ACCOUNT_TYPE:"PREFERRED_ACCOUNT_TYPE",SMART_ACCOUNT_ENABLED:"SMART_ACCOUNT_ENABLED",SMART_ACCOUNT_ENABLED_NETWORKS:"SMART_ACCOUNT_ENABLED_NETWORKS",SOCIAL_USERNAME:"SOCIAL_USERNAME",APP_SWITCH_NETWORK:"@w3m-app/SWITCH_NETWORK",APP_CONNECT_EMAIL:"@w3m-app/CONNECT_EMAIL",APP_CONNECT_DEVICE:"@w3m-app/CONNECT_DEVICE",APP_CONNECT_OTP:"@w3m-app/CONNECT_OTP",APP_CONNECT_SOCIAL:"@w3m-app/CONNECT_SOCIAL",APP_GET_SOCIAL_REDIRECT_URI:"@w3m-app/GET_SOCIAL_REDIRECT_URI",APP_GET_USER:"@w3m-app/GET_USER",APP_SIGN_OUT:"@w3m-app/SIGN_OUT",APP_IS_CONNECTED:"@w3m-app/IS_CONNECTED",APP_GET_CHAIN_ID:"@w3m-app/GET_CHAIN_ID",APP_RPC_REQUEST:"@w3m-app/RPC_REQUEST",APP_UPDATE_EMAIL:"@w3m-app/UPDATE_EMAIL",APP_UPDATE_EMAIL_PRIMARY_OTP:"@w3m-app/UPDATE_EMAIL_PRIMARY_OTP",APP_UPDATE_EMAIL_SECONDARY_OTP:"@w3m-app/UPDATE_EMAIL_SECONDARY_OTP",APP_AWAIT_UPDATE_EMAIL:"@w3m-app/AWAIT_UPDATE_EMAIL",APP_SYNC_THEME:"@w3m-app/SYNC_THEME",APP_SYNC_DAPP_DATA:"@w3m-app/SYNC_DAPP_DATA",APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS:"@w3m-app/GET_SMART_ACCOUNT_ENABLED_NETWORKS",APP_INIT_SMART_ACCOUNT:"@w3m-app/INIT_SMART_ACCOUNT",APP_SET_PREFERRED_ACCOUNT:"@w3m-app/SET_PREFERRED_ACCOUNT",APP_CONNECT_FARCASTER:"@w3m-app/CONNECT_FARCASTER",APP_GET_FARCASTER_URI:"@w3m-app/GET_FARCASTER_URI",APP_RELOAD:"@w3m-app/RELOAD",APP_RPC_ABORT:"@w3m-app/RPC_ABORT",FRAME_SWITCH_NETWORK_ERROR:"@w3m-frame/SWITCH_NETWORK_ERROR",FRAME_SWITCH_NETWORK_SUCCESS:"@w3m-frame/SWITCH_NETWORK_SUCCESS",FRAME_CONNECT_EMAIL_ERROR:"@w3m-frame/CONNECT_EMAIL_ERROR",FRAME_CONNECT_EMAIL_SUCCESS:"@w3m-frame/CONNECT_EMAIL_SUCCESS",FRAME_CONNECT_DEVICE_ERROR:"@w3m-frame/CONNECT_DEVICE_ERROR",FRAME_CONNECT_DEVICE_SUCCESS:"@w3m-frame/CONNECT_DEVICE_SUCCESS",FRAME_CONNECT_OTP_SUCCESS:"@w3m-frame/CONNECT_OTP_SUCCESS",FRAME_CONNECT_OTP_ERROR:"@w3m-frame/CONNECT_OTP_ERROR",FRAME_CONNECT_SOCIAL_SUCCESS:"@w3m-frame/CONNECT_SOCIAL_SUCCESS",FRAME_CONNECT_SOCIAL_ERROR:"@w3m-frame/CONNECT_SOCIAL_ERROR",FRAME_CONNECT_FARCASTER_SUCCESS:"@w3m-frame/CONNECT_FARCASTER_SUCCESS",FRAME_CONNECT_FARCASTER_ERROR:"@w3m-frame/CONNECT_FARCASTER_ERROR",FRAME_GET_FARCASTER_URI_SUCCESS:"@w3m-frame/GET_FARCASTER_URI_SUCCESS",FRAME_GET_FARCASTER_URI_ERROR:"@w3m-frame/GET_FARCASTER_URI_ERROR",FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_SUCCESS",FRAME_GET_SOCIAL_REDIRECT_URI_ERROR:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_ERROR",FRAME_GET_USER_SUCCESS:"@w3m-frame/GET_USER_SUCCESS",FRAME_GET_USER_ERROR:"@w3m-frame/GET_USER_ERROR",FRAME_SIGN_OUT_SUCCESS:"@w3m-frame/SIGN_OUT_SUCCESS",FRAME_SIGN_OUT_ERROR:"@w3m-frame/SIGN_OUT_ERROR",FRAME_IS_CONNECTED_SUCCESS:"@w3m-frame/IS_CONNECTED_SUCCESS",FRAME_IS_CONNECTED_ERROR:"@w3m-frame/IS_CONNECTED_ERROR",FRAME_GET_CHAIN_ID_SUCCESS:"@w3m-frame/GET_CHAIN_ID_SUCCESS",FRAME_GET_CHAIN_ID_ERROR:"@w3m-frame/GET_CHAIN_ID_ERROR",FRAME_RPC_REQUEST_SUCCESS:"@w3m-frame/RPC_REQUEST_SUCCESS",FRAME_RPC_REQUEST_ERROR:"@w3m-frame/RPC_REQUEST_ERROR",FRAME_SESSION_UPDATE:"@w3m-frame/SESSION_UPDATE",FRAME_UPDATE_EMAIL_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SUCCESS",FRAME_UPDATE_EMAIL_ERROR:"@w3m-frame/UPDATE_EMAIL_ERROR",FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_ERROR",FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_ERROR",FRAME_SYNC_THEME_SUCCESS:"@w3m-frame/SYNC_THEME_SUCCESS",FRAME_SYNC_THEME_ERROR:"@w3m-frame/SYNC_THEME_ERROR",FRAME_SYNC_DAPP_DATA_SUCCESS:"@w3m-frame/SYNC_DAPP_DATA_SUCCESS",FRAME_SYNC_DAPP_DATA_ERROR:"@w3m-frame/SYNC_DAPP_DATA_ERROR",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR",FRAME_INIT_SMART_ACCOUNT_SUCCESS:"@w3m-frame/INIT_SMART_ACCOUNT_SUCCESS",FRAME_INIT_SMART_ACCOUNT_ERROR:"@w3m-frame/INIT_SMART_ACCOUNT_ERROR",FRAME_SET_PREFERRED_ACCOUNT_SUCCESS:"@w3m-frame/SET_PREFERRED_ACCOUNT_SUCCESS",FRAME_SET_PREFERRED_ACCOUNT_ERROR:"@w3m-frame/SET_PREFERRED_ACCOUNT_ERROR",FRAME_READY:"@w3m-frame/READY",FRAME_RELOAD_SUCCESS:"@w3m-frame/RELOAD_SUCCESS",FRAME_RELOAD_ERROR:"@w3m-frame/RELOAD_ERROR",FRAME_RPC_ABORT_SUCCESS:"@w3m-frame/RPC_ABORT_SUCCESS",FRAME_RPC_ABORT_ERROR:"@w3m-frame/RPC_ABORT_ERROR",RPC_RESPONSE_TYPE_ERROR:"RPC_RESPONSE_ERROR",RPC_RESPONSE_TYPE_TX:"RPC_RESPONSE_TRANSACTION_HASH",RPC_RESPONSE_TYPE_OBJECT:"RPC_RESPONSE_OBJECT"},Kr={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}}});var kU,Ite=b(()=>{l();kU={address:/^0x(?:[A-Fa-f0-9]{40})$/u,transactionHash:/^0x(?:[A-Fa-f0-9]{64})$/u,signedMessage:/^0x(?:[a-fA-F0-9]{62,})$/u}});var Ew,UU=b(()=>{l();g4();Tte();Ew={set(e,t){lI.isClient&&localStorage.setItem(`${Qa.STORAGE_KEY}${e}`,t)},get(e){return lI.isClient?localStorage.getItem(`${Qa.STORAGE_KEY}${e}`):null},delete(e,t){lI.isClient&&(t?localStorage.removeItem(e):localStorage.removeItem(`${Qa.STORAGE_KEY}${e}`))}}});var uI,lI,Tte=b(()=>{l();Ite();g4();UU();uI=30*1e3,lI={checkIfAllowedToTriggerEmail(){let e=Ew.get(Qa.LAST_EMAIL_LOGIN_TIME);if(e){let t=Date.now()-Number(e);if(t{l();g4();UU()});var Pte,Nte=b(()=>{l();Pte="1.2.3"});var wn,Aw=b(()=>{l();Nte();wn=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: https://abitype.dev${o}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Pte}`].join(` -`);super(s),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.shortMessage=t}}});function ga(e,t){return e.exec(t)?.groups}var DU,LU,dI,y4=b(()=>{l();DU=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,LU=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,dI=/^\(.+?\).*?$/});function fI(e){let t=e.type;if(Rte.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let o=0;o{l();y4();Rte=/^tuple(?(\[(\d*)\])*)$/});function Ef(e){let t="",r=e.length;for(let n=0;n{l();Ote()});function Af(e){return e.type==="function"?`function ${e.name}(${Ef(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Ef(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Ef(e.inputs)})`:e.type==="error"?`error ${e.name}(${Ef(e.inputs)})`:e.type==="constructor"?`constructor(${Ef(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var Bte=b(()=>{l();MU()});function Ute(e){return kte.test(e)}function Dte(e){return ga(kte,e)}function Mte(e){return Lte.test(e)}function Hte(e){return ga(Lte,e)}function Fte(e){return $te.test(e)}function zte(e){return ga($te,e)}function Zl(e){return Vte.test(e)}function jte(e){return ga(Vte,e)}function Wte(e){return qte.test(e)}function Kte(e){return ga(qte,e)}function Gte(e){return Zte.test(e)}function Yte(e){return ga(Zte,e)}function Jte(e){return Lke.test(e)}var kte,Lte,$te,Vte,qte,Zte,Lke,Cw,Qte,pI,J1=b(()=>{l();y4();kte=/^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;Lte=/^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;$te=/^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/;Vte=/^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/;qte=/^constructor\((?.*?)\)(?:\s(?payable{1}))?$/;Zte=/^fallback\(\) external(?:\s(?payable{1}))?$/;Lke=/^receive\(\) external payable$/;Cw=new Set(["memory","indexed","storage","calldata"]),Qte=new Set(["indexed"]),pI=new Set(["calldata","memory","storage"])});var Q1,X1,w4,b4=b(()=>{l();Aw();Q1=class extends wn{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}},X1=class extends wn{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},w4=class extends wn{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}});var eg,tg,rg,ng,og,sg,ig,Sw=b(()=>{l();Aw();eg=class extends wn{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}},tg=class extends wn{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}},rg=class extends wn{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},ng=class extends wn{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},og=class extends wn{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},sg=class extends wn{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},ig=class extends wn{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}});var ya,ag,cg,hI=b(()=>{l();Aw();ya=class extends wn{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},ag=class extends wn{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},cg=class extends wn{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}});var lg,HU=b(()=>{l();Aw();lg=class extends wn{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}});var ug,$U=b(()=>{l();Aw();ug=class extends wn{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}});function Xte(e,t,r){let n="";if(r)for(let o of Object.entries(r)){if(!o)continue;let s="";for(let i of o[1])s+=`[${i.type}${i.name?`:${i.name}`:""}]`;n+=`(${o[0]}{${s}})`}return t?`${t}:${e}${n}`:`${e}${n}`}var mI,ere=b(()=>{l();mI=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});function x4(e,t={}){if(Fte(e))return Mke(e,t);if(Mte(e))return Hke(e,t);if(Ute(e))return $ke(e,t);if(Wte(e))return Fke(e,t);if(Gte(e))return zke(e);if(Jte(e))return{type:"receive",stateMutability:"payable"};throw new ag({signature:e})}function Mke(e,t={}){let r=zte(e);if(!r)throw new ya({signature:e,type:"function"});let n=Ei(r.parameters),o=[],s=n.length;for(let a=0;a{l();y4();b4();Sw();hI();$U();ere();J1();Vke=/^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,jke=/^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,qke=/^u?int$/;Wke=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/});function Rh(e){let t={},r=e.length;for(let i=0;i{l();y4();b4();Sw();hI();HU();J1();dg();Gke=/^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/});function Iw(e){let t=Rh(e),r=[],n=e.length;for(let o=0;o{l();J1();v4();dg()});function Tw(e){let t;if(typeof e=="string")t=x4(e);else{let r=Rh(e),n=e.length;for(let o=0;o{l();b4();J1();v4();dg()});function zU(e){let t;if(typeof e=="string")t=Ai(e,{modifiers:Cw});else{let r=Rh(e),n=e.length;for(let o=0;o{l();Sw();J1();v4();dg()});function _w(e){let t=[];if(typeof e=="string"){let r=Ei(e),n=r.length;for(let o=0;o{l();Sw();J1();v4();dg();dg()});var fg=b(()=>{l();Bte();MU();rre();nre();ore();sre();b4();Sw();hI();$U();HU()});function ue(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let o=e[r];return typeof o=="function"?o:s=>t(e,s)}var _t=b(()=>{l()});function no(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Pw(e.type);return`${e.name}(${E4(e.inputs,{includeName:t})})`}function E4(e,{includeName:t=!1}={}){return e?e.map(r=>Yke(r,{includeName:t})).join(t?", ":","):""}function Yke(e,{includeName:t}){return e.type.startsWith("tuple")?`(${E4(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}var Cf=b(()=>{l();Qr()});function We(e,{even:t=!1,strict:r=!0}={}){return!e||typeof e!="string"||t&&e.length%2!==0?!1:r?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}var qs=b(()=>{l()});function gt(e){return We(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var Fo=b(()=>{l();qs()});var VU,are=b(()=>{l();VU="2.57.19"});function cre(e){gI=e}function lre(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?lre(e.cause,t):t?null:e}var gI,G,nt=b(()=>{l();are();gI={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${VU}`};G=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=gI.getDocsUrl?.({...r,docsPath:o}),i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...gI.version?[`Version: ${gI.version}`]:[]].join(` -`);super(i,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=VU}walk(t){return lre(this,t)}}});var Oh,Gl,yI,Bh,Ci,Nw,Rw,kh,Ow,pg,Uh,Yl,Jl,hg,wa,Dh,Bw,wI,Lh,jc,Ql,kw,Uw,Mh,Pw,Dw,Qr=b(()=>{l();Cf();Fo();nt();Oh=class extends G{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(` +`);super(s),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.shortMessage=t}}});function ga(e,t){return e.exec(t)?.groups}var DU,LU,dI,y4=b(()=>{l();DU=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,LU=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,dI=/^\(.+?\).*?$/});function fI(e){let t=e.type;if(Rte.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let o=0;o{l();y4();Rte=/^tuple(?(\[(\d*)\])*)$/});function Ef(e){let t="",r=e.length;for(let n=0;n{l();Ote()});function Af(e){return e.type==="function"?`function ${e.name}(${Ef(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${Ef(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${Ef(e.inputs)})`:e.type==="error"?`error ${e.name}(${Ef(e.inputs)})`:e.type==="constructor"?`constructor(${Ef(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var Bte=b(()=>{l();MU()});function Ute(e){return kte.test(e)}function Dte(e){return ga(kte,e)}function Mte(e){return Lte.test(e)}function Hte(e){return ga(Lte,e)}function Fte(e){return $te.test(e)}function zte(e){return ga($te,e)}function Zl(e){return Vte.test(e)}function jte(e){return ga(Vte,e)}function Wte(e){return qte.test(e)}function Kte(e){return ga(qte,e)}function Gte(e){return Zte.test(e)}function Yte(e){return ga(Zte,e)}function Jte(e){return Lke.test(e)}var kte,Lte,$te,Vte,qte,Zte,Lke,Cw,Qte,pI,J1=b(()=>{l();y4();kte=/^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;Lte=/^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/;$te=/^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/;Vte=/^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/;qte=/^constructor\((?.*?)\)(?:\s(?payable{1}))?$/;Zte=/^fallback\(\) external(?:\s(?payable{1}))?$/;Lke=/^receive\(\) external payable$/;Cw=new Set(["memory","indexed","storage","calldata"]),Qte=new Set(["indexed"]),pI=new Set(["calldata","memory","storage"])});var Q1,X1,w4,b4=b(()=>{l();Aw();Q1=class extends wn{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}},X1=class extends wn{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},w4=class extends wn{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}});var eg,tg,rg,ng,og,sg,ig,Sw=b(()=>{l();Aw();eg=class extends wn{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}},tg=class extends wn{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}},rg=class extends wn{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},ng=class extends wn{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},og=class extends wn{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},sg=class extends wn{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},ig=class extends wn{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}});var ya,ag,cg,hI=b(()=>{l();Aw();ya=class extends wn{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},ag=class extends wn{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},cg=class extends wn{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}});var lg,HU=b(()=>{l();Aw();lg=class extends wn{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}});var ug,$U=b(()=>{l();Aw();ug=class extends wn{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}});function Xte(e,t,r){let n="";if(r)for(let o of Object.entries(r)){if(!o)continue;let s="";for(let i of o[1])s+=`[${i.type}${i.name?`:${i.name}`:""}]`;n+=`(${o[0]}{${s}})`}return t?`${t}:${e}${n}`:`${e}${n}`}var mI,ere=b(()=>{l();mI=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});function x4(e,t={}){if(Fte(e))return Mke(e,t);if(Mte(e))return Hke(e,t);if(Ute(e))return $ke(e,t);if(Wte(e))return Fke(e,t);if(Gte(e))return zke(e);if(Jte(e))return{type:"receive",stateMutability:"payable"};throw new ag({signature:e})}function Mke(e,t={}){let r=zte(e);if(!r)throw new ya({signature:e,type:"function"});let n=Ai(r.parameters),o=[],s=n.length;for(let a=0;a{l();y4();b4();Sw();hI();$U();ere();J1();Vke=/^(?[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,jke=/^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,qke=/^u?int$/;Wke=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/});function Rh(e){let t={},r=e.length;for(let i=0;i{l();y4();b4();Sw();hI();HU();J1();dg();Gke=/^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/});function Iw(e){let t=Rh(e),r=[],n=e.length;for(let o=0;o{l();J1();v4();dg()});function Tw(e){let t;if(typeof e=="string")t=x4(e);else{let r=Rh(e),n=e.length;for(let o=0;o{l();b4();J1();v4();dg()});function zU(e){let t;if(typeof e=="string")t=Ci(e,{modifiers:Cw});else{let r=Rh(e),n=e.length;for(let o=0;o{l();Sw();J1();v4();dg()});function _w(e){let t=[];if(typeof e=="string"){let r=Ai(e),n=r.length;for(let o=0;o{l();Sw();J1();v4();dg();dg()});var fg=b(()=>{l();Bte();MU();rre();nre();ore();sre();b4();Sw();hI();$U();HU()});function ue(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let o=e[r];return typeof o=="function"?o:s=>t(e,s)}var _t=b(()=>{l()});function no(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new Pw(e.type);return`${e.name}(${E4(e.inputs,{includeName:t})})`}function E4(e,{includeName:t=!1}={}){return e?e.map(r=>Yke(r,{includeName:t})).join(t?", ":","):""}function Yke(e,{includeName:t}){return e.type.startsWith("tuple")?`(${E4(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}var Cf=b(()=>{l();Qr()});function We(e,{even:t=!1,strict:r=!0}={}){return!e||typeof e!="string"||t&&e.length%2!==0?!1:r?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}var qs=b(()=>{l()});function gt(e){return We(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var Fo=b(()=>{l();qs()});var VU,are=b(()=>{l();VU="2.57.19"});function cre(e){gI=e}function lre(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?lre(e.cause,t):t?null:e}var gI,G,nt=b(()=>{l();are();gI={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${VU}`};G=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=gI.getDocsUrl?.({...r,docsPath:o}),i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...gI.version?[`Version: ${gI.version}`]:[]].join(` +`);super(i,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=VU}walk(t){return lre(this,t)}}});var Oh,Gl,yI,Bh,Si,Nw,Rw,kh,Ow,pg,Uh,Yl,Jl,hg,wa,Dh,Bw,wI,Lh,jc,Ql,kw,Uw,Mh,Pw,Dw,Qr=b(()=>{l();Cf();Fo();nt();Oh=class extends G{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(` `),{docsPath:t,name:"AbiConstructorNotFoundError"})}},Gl=class extends G{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(` `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}},yI=class extends G{constructor({data:t,size:r}){super([`Data size of ${r} bytes is invalid.`,"Size must be in increments of 32 bytes (size % 32 === 0)."].join(` `),{metaMessages:[`Data: ${t} (${r} bytes)`],name:"AbiDecodingDataSizeInvalidError"})}},Bh=class extends G{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(` -`),{metaMessages:[`Params: (${E4(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}},Ci=class extends G{constructor({cause:t}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:t})}},Nw=class extends G{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(` +`),{metaMessages:[`Params: (${E4(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}},Si=class extends G{constructor({cause:t}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:t})}},Nw=class extends G{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(` `),{name:"AbiEncodingArrayLengthMismatchError"})}},Rw=class extends G{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${gt(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}},kh=class extends G{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(` `),{name:"AbiEncodingLengthMismatchError"})}},Ow=class extends G{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(` `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}},pg=class extends G{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(` @@ -39,7 +39,7 @@ if (cid) { `),{docsPath:r,name:"InvalidAbiEncodingType"})}},Uw=class extends G{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(` `),{docsPath:r,name:"InvalidAbiDecodingType"})}},Mh=class extends G{constructor(t){super([`Value "${t}" is not a valid array.`].join(` `),{name:"InvalidArrayError"})}},Pw=class extends G{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(` -`),{name:"InvalidDefinitionTypeError"})}},Dw=class extends G{constructor(t){super(`Type "${t}" is not supported for packed encoding.`,{name:"UnsupportedPackedAbiType"})}}});var Lw,jU=b(()=>{l();nt();Lw=class extends G{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}});var mg,gg,A4,C4=b(()=>{l();nt();mg=class extends G{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},gg=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}},A4=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}});function Zr(e,{dir:t,size:r=32}={}){return typeof e=="string"?cs(e,{dir:t,size:r}):qU(e,{dir:t,size:r})}function cs(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new gg({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function qU(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new gg({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let o=0;o{l();C4()});var Xl,Mw,Hw,$w,Fw,zw,Vw,jw,yg=b(()=>{l();nt();Xl=class extends G{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number "${s}" is not in safe ${o?`${o*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},Mw=class extends G{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}},Hw=class extends G{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}},$w=class extends G{constructor(t){super(`Hex value "${t}" is an odd length (${t.length}). It must be an even length.`,{name:"InvalidHexValueError"})}},Fw=class extends G{constructor({limit:t}){super(`RLP depth limit of \`${t}\` exceeded.`,{name:"RlpDepthLimitExceededError"})}},zw=class extends G{constructor({consumed:t,declared:r}){super(`RLP list items consumed \`${t}\` bytes but the list declared a length of \`${r}\`.`,{name:"RlpListBoundaryExceededError"})}},Vw=class extends G{constructor({count:t}){super(`RLP payload encodes a single item, but \`${t}\` trailing ${t===1?"byte remains":"bytes remain"}.`,{name:"RlpTrailingBytesError"})}},jw=class extends G{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}});function bn(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let o=0;o{l()});function Ws(e,{size:t}){if(gt(e)>t)throw new jw({givenSize:gt(e),maxSize:t})}function WU(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?wt(e,r):n==="bigint"?dt(e,r):n==="string"?bI(e,r):n==="boolean"?qw(e,r):qt(e,r)}function dt(e,t={}){let{signed:r}=t;t.size&&Ws(e,{size:t.size});let n=BigInt(e);if(!r)return n;let o=Math.ceil((e.length-2)/2),s=(1n<{l();yg();Fo();Hh();Pr()});function wr(e,t={}){return typeof e=="number"||typeof e=="bigint"?oe(e,t):typeof e=="string"?ec(e,t):typeof e=="boolean"?wg(e,t):yt(e,t)}function wg(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Ws(r,{size:t.size}),Zr(r,{size:t.size})):r}function yt(e,t={}){let r="";for(let o=0;os||o{l();yg();Xa();Xr();Jke=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Qke=new TextEncoder});function un(e,t={}){return typeof e=="number"||typeof e=="bigint"?ZU(e,t):typeof e=="boolean"?KU(e,t):We(e)?qt(e,t):zo(e,t)}function KU(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Ws(r,{size:t.size}),Zr(r,{size:t.size})):r}function ure(e){if(e>=Sf.zero&&e<=Sf.nine)return e-Sf.zero;if(e>=Sf.A&&e<=Sf.F)return e-(Sf.A-10);if(e>=Sf.a&&e<=Sf.f)return e-(Sf.a-10)}function qt(e,t={}){let r=e.slice(2);r.length%2&&(r=`0${r}`),t.size&&(Ws(e,{size:t.size}),r=r.padEnd(t.size*2,"0"));let n=r.length/2,o=new Uint8Array(n);for(let s=0,i=0;s{l();nt();qs();Xa();Xr();qe();Xke=new TextEncoder;Sf={zero:48,nine:57,A:65,F:70,a:97,f:102}});function eUe(e,t=!1){return t?{h:Number(e&xI),l:Number(e>>dre&xI)}:{h:Number(e>>dre&xI)|0,l:Number(e&xI)|0}}function fre(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s{l();xI=BigInt(4294967295),dre=BigInt(32);pre=(e,t,r)=>e<>>32-r,hre=(e,t,r)=>t<>>32-r,mre=(e,t,r)=>t<>>64-r,gre=(e,t,r)=>e<>>64-r});var bg,wre=b(()=>{l();bg=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function tUe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function xg(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function eu(e,...t){if(!tUe(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function bre(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xg(e.outputLen),xg(e.blockLen)}function If(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function vI(e,t){eu(e);let r=t.outputLen;if(e.length>>t}function S4(e,t){return e<>>32-t>>>0}function nUe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function oUe(e){for(let t=0;te().update(vg(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function AI(e=32){if(bg&&typeof bg.getRandomValues=="function")return bg.getRandomValues(new Uint8Array(e));if(bg&&typeof bg.randomBytes=="function")return Uint8Array.from(bg.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var rUe,GU,$h,Tf=b(()=>{l();wre();rUe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;GU=rUe?e=>e:oUe;$h=class{}});function pUe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=Ere(u,d,1)^r[a],p=Are(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=Sre[i],c=Ere(o,s,a),u=Are(o,s,a),d=Cre[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=dUe[n],e[1]^=fUe[n]}ba(r)}var iUe,I4,aUe,cUe,lUe,uUe,Cre,Sre,Ire,Tre,dUe,fUe,Ere,Are,YU,hUe,CI,JU=b(()=>{l();yre();Tf();iUe=BigInt(0),I4=BigInt(1),aUe=BigInt(2),cUe=BigInt(7),lUe=BigInt(256),uUe=BigInt(113),Cre=[],Sre=[],Ire=[];for(let e=0,t=I4,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Cre.push(2*(5*n+r)),Sre.push((e+1)*(e+2)/2%64);let o=iUe;for(let s=0;s<7;s++)t=(t<>cUe)*uUe)%lUe,t&aUe&&(o^=I4<<(I4<r>32?mre(e,t,r):pre(e,t,r),Are=(e,t,r)=>r>32?gre(e,t,r):hre(e,t,r);YU=class e extends $h{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,xg(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return xg(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(vI(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ba(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},hUe=(e,t,r)=>Ww(()=>new YU(t,e,r)),CI=hUe(1,136,256/8)});function Pt(e,t){let r=t||"hex",n=CI(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var Ks=b(()=>{l();JU();qs();Pr();qe()});var xo,_f=b(()=>{l();xo=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&(super.delete(t),super.set(t,r)),r}set(t,r){if(super.has(t)&&super.delete(t),super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=super.keys().next().value;n!==void 0&&super.delete(n)}return this}}});function _re(e){return mUe(e)}var mUe,Pre=b(()=>{l();Pr();Ks();mUe=e=>Pt(un(e))});function Nre(e){let t=!0,r="",n=0,o="",s=!1;for(let i=0;i{l();nt()});var Pf,SI=b(()=>{l();fg();Rre();Pf=e=>{let t=typeof e=="string"?e:Af(e);return Nre(t)}});function Nf(e){let t=typeof e=="string"?e:Af(e),r=Ore.get(t);if(r)return r;let n=_re(Pf(t));return Ore.set(t,n),n}var Ore,T4=b(()=>{l();fg();_f();Pre();SI();Ore=new xo(8192)});var Wc,Kw=b(()=>{l();T4();Wc=Nf});var br,tc=b(()=>{l();nt();br=class extends G{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}});function Kc(e,t){if(QU.has(`${e}.${t}`))return QU.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=Pt(zo(r),"bytes"),o=(t?r.substring(`${t}0x`.length):r).split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&o[i]&&(o[i]=o[i].toUpperCase()),(n[i>>1]&15)>=8&&o[i+1]&&(o[i+1]=o[i+1].toUpperCase());let s=`0x${o.join("")}`;return QU.set(`${e}.${t}`,s),s}function Gr(e,t){if(!Ft(e,{strict:!1}))throw new br({address:e});return Kc(e,t)}var QU,Zs=b(()=>{l();tc();Pr();Ks();_f();Gs();QU=new xo(8192)});function Ft(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(XU.has(n))return XU.get(n);let o=gUe.test(e)?e.toLowerCase()===e?!0:r?Kc(e)===e:!0:!1;return XU.set(n,o),o}var gUe,XU,Gs=b(()=>{l();_f();Zs();gUe=/^0x[a-fA-F0-9]{40}$/,XU=new xo(8192)});function en(e){return typeof e[0]=="string"?fr(e):eD(e)}function eD(e){let t=0;for(let o of e)t+=o.length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function fr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}var Fn=b(()=>{l()});function vo(e,t,r,{strict:n}={}){return We(e,{strict:!1})?xa(e,t,r,{strict:n}):_4(e,t,r,{strict:n})}function Bre(e,t){if(typeof t=="number"&&t>0&&t>gt(e)-1)throw new mg({offset:t,position:"start",size:gt(e)})}function kre(e,t,r){if(typeof t=="number"&&typeof r=="number"&>(e)!==r-t)throw new mg({offset:r,position:"end",size:gt(e)})}function _4(e,t,r,{strict:n}={}){Bre(e,t);let o=e.slice(t,r);return n&&kre(o,t,r),o}function xa(e,t,r,{strict:n}={}){Bre(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&kre(o,t,r),o}var Si=b(()=>{l();C4();qs();Fo()});var Ure,Eg,Rf,P4=b(()=>{l();Ure=/^(.*)\[([0-9]*)\]$/,Eg=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Rf=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/});function oo(e,t){if(e.length!==t.length)throw new kh({expectedLength:e.length,givenLength:t.length});let r=yUe({params:e,values:t});return nD(r)}function yUe({params:e,values:t}){let r=[];for(let n=0;ni))}}function xUe(e,{param:t}){let[,r]=t.type.split("bytes"),n=e.length%2?`0x0${e.slice(2)}`:e,o=gt(n);if(!r){let s=n;return o%32!==0&&(s=cs(s,{dir:"right",size:Math.ceil(o/32)*32})),{dynamic:!0,encoded:fr([cs(oe(o,{size:32})),s])}}if(o!==Number.parseInt(r,10))throw new Rw({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:cs(n,{dir:"right"})}}function vUe(e){if(typeof e!="boolean")throw new G(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(wg(e))}}function EUe(e,{signed:t,size:r=256}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||eo))}}function Of(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function tD(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components.some(tD);let r=Of(t);return r?tD({...e,type:r[1]}):!1}var rc=b(()=>{l();Qr();tc();nt();yg();Gs();Fn();Xa();Fo();Si();qe();P4()});var va,Ag=b(()=>{l();Si();T4();va=e=>vo(Nf(e),0,4)});function ls(e){let{abi:t,args:r=[],name:n}=e,o=We(n,{strict:!1}),s=t.filter(a=>o?a.type==="function"?va(a)===n:a.type==="event"?Wc(a)===n:!1:"name"in a&&a.name===n);if(s.length===0)return;if(s.length===1)return s[0];let i;for(let a of s){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,d)=>{let f="inputs"in a&&a.inputs[d];return f?oD(u,f):!1})){if(i&&"inputs"in i&&i.inputs){let u=sD(a.inputs,i.inputs,r);if(u)throw new wI({abiItem:a,type:u[0]},{abiItem:i,type:u[1]})}i=a}}return i||s[0]}function oD(e,t){let r=typeof e,n=t.type;switch(n){case"address":return Ft(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((s,i)=>r==="object"&&oD(Dre(e,s,i),s));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)){if(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&!Number.isInteger(e))return!1;let s=n.startsWith("int"),i=Number.parseInt(n.replace(/^u?int/,"")||"256",10),a=2n**(BigInt(i)-(s?1n:0n))-1n,c=s?-a-1n:0n;return e>=c&&e<=a}if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)){if(typeof e!="string"&&!(e instanceof Uint8Array))return!1;let s=n.slice(5);return s?typeof e=="string"&&!We(e)?!1:gt(e)===Number.parseInt(s,10):e instanceof Uint8Array||We(e)}let o=Of(n);if(o){let[s,i]=o;return Array.isArray(e)&&(s===null||e.length===s)&&e.every(a=>oD(a,{...t,type:i}))}return!1}}}function sD(e,t,r){for(let n in e){let o=e[n],s=t[n];if(!s)continue;if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s){let f=r[n],p=sD(o.components,s.components,o.components.map((h,y)=>Dre(f,h,y)));if(p)return p;continue}let i=Of(o.type),a=Of(s.type);if(i&&a){let f=sD([{...o,type:i[1]}],[{...s,type:a[1]}],[r[n]?.[0]]);if(f)return f;if(i[1]===a[1]&&o.type!==s.type)return[o.type,s.type];continue}let c=[o.type,s.type],u=r[n];if(c.includes("address")&&(c.includes("string")||c.includes("bytes"))?u===void 0||Ft(u,{strict:!1}):o.type!==s.type)return c}}function Dre(e,t,r){return Array.isArray(e)?e[r]:e?.[t.name]}var Bf=b(()=>{l();Qr();qs();Gs();Fo();Kw();Ag();rc()});function nc(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=ls({abi:t,name:r});if(!c)throw new hg(r,{docsPath:Lre});o=c}if(o.type!=="event")throw new hg(void 0,{docsPath:Lre});let s=[];if(n&&"inputs"in o){let c=o.inputs?.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?c?.map(d=>n[d.name])??[]:[];u.length>0&&(s=c?.map((d,f)=>Array.isArray(u[f])?u[f].map((p,h)=>Mre({param:d,value:u[f][h]})):typeof u[f]<"u"&&u[f]!==null?Mre({param:d,value:u[f]}):null)??[])}if(o.anonymous)return s;let i=no(o);return[Wc(i),...s]}function Mre({param:e,value:t}){if(e.type==="string")return Pt(zo(t));if(e.type==="bytes")return Pt(un(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Lw(e.type);return oo([e],[t])}var Lre,Cg=b(()=>{l();Qr();jU();Pr();Ks();Kw();rc();Cf();Bf();Lre="/docs/contract/encodeEventTopics"});function Fh(e,{method:t}){let r={};return e.transport.type==="fallback"&&e.transport.onResponse?.(({method:n,response:o,status:s,transport:i})=>{s==="success"&&t===n&&(r[o]=i.request)}),(n=>r[n]||e.request)}var N4=b(()=>{l()});async function Zw(e,t){let{address:r,abi:n,args:o,eventName:s,fromBlock:i,strict:a,toBlock:c}=t,u=Fh(e,{method:"eth_newFilter"}),d=s?nc({abi:n,args:o,eventName:s}):void 0,f=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof i=="bigint"?oe(i):i,toBlock:typeof c=="bigint"?oe(c):c,topics:d}]});return{abi:n,args:o,eventName:s,id:f,request:u(f),strict:!!a,type:"event"}}var II=b(()=>{l();Cg();qe();N4()});function ft(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}var tn=b(()=>{l()});function TI(e){let{abi:t,args:r,functionName:n}=e,o=t[0];if(n){let s=ls({abi:t,args:r,name:n});if(!s)throw new wa(n,{docsPath:Hre});o=s}if(o.type!=="function")throw new wa(void 0,{docsPath:Hre});return{abi:[o],functionName:va(no(o))}}var Hre,iD=b(()=>{l();Qr();Ag();Cf();Bf();Hre="/docs/contract/encodeFunctionData"});function Wt(e){let{args:t}=e,{abi:r,functionName:n}=e.abi.length===1&&e.functionName?.startsWith("0x")?e:TI(e),o=r[0],s=n,i="inputs"in o&&o.inputs?oo(o.inputs,t??[]):void 0;return fr([s,i??"0x"])}var us=b(()=>{l();Fn();rc();iD()});var $re,Gw,Fre,R4=b(()=>{l();$re={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},Gw={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Fre={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"}});var O4,Yw,_I,aD=b(()=>{l();nt();O4=class extends G{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},Yw=class extends G{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},_I=class extends G{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}});function Zc(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(SUe);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var SUe,Jw=b(()=>{l();aD();SUe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new _I({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new Yw({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new O4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new O4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}}});function zre(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?Ea(e,r):n==="bigint"?B4(e,r):n==="boolean"?k4(e,r):n==="string"?U4(e,r):yt(e,r)}function B4(e,t={}){typeof t.size<"u"&&Ws(e,{size:t.size});let r=yt(e);return dt(r,t)}function k4(e,t={}){let r=e;if(typeof t.size<"u"&&(Ws(r,{size:t.size}),r=bn(r)),r.length>1||r[0]>1)throw new Mw(r);return!!r[0]}function Ea(e,t={}){typeof t.size<"u"&&Ws(e,{size:t.size});let r=yt(e);return wt(r,t)}function U4(e,t={}){let r=e;return typeof t.size<"u"&&(Ws(r,{size:t.size}),r=bn(r,{dir:"right"})),new TextDecoder().decode(r)}var cD=b(()=>{l();yg();Hh();Xr();qe()});function Ys(e,t){let r=typeof t=="string"?qt(t):t,n=Zc(r);if(gt(r)===0&&e.length>0)throw new Ci;if(gt(t)&>(t)<32)throw new Bh({data:typeof t=="string"?t:yt(t),params:e,size:gt(t)});let o={limit:r.length*32,used:0},s=0,i=[];for(let a=0;ar.limit)throw new Xw({limit:r.limit});return e.setPosition(n+32),[yt(u),32]}return[yt(e.readBytes(Number.parseInt(s,10),32)),32]}function NUe(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?B4(o,{signed:r}):Ea(o,{signed:r}),32]}function RUe(e,t,{budget:r,staticPosition:n}){let o=t.components.length===0||t.components.some(({name:a})=>!a),s=o?[]:{},i=0;if(D4(t)){let a=Ea(e.readBytes(lD)),c=n+a;for(let u=0;ut.limit)throw new Xw({limit:t.limit});let a=U4(i);return e.setPosition(r+32),[a,32]}function D4(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(D4);let r=Of(e.type);return!!(r&&D4({...e,type:r[1]}))}var Vre,lD,Xw,zh=b(()=>{l();Qr();nt();Zs();Jw();Fo();Si();cD();Pr();qe();rc();Vre=32,lD=32;Xw=class extends G{constructor({limit:t}){super(`Decoded \`bytes\` and \`string\` values exceed the size limit of ${t} bytes.`,{name:"AbiDecodingSizeLimitExceededError"})}}});function Vh(e){let{abi:t,data:r,cause:n}=e,o=vo(r,0,4);if(o==="0x")throw new Ci({cause:n});let i=[...t||[],Gw,Fre].find(a=>a.type==="error"&&o===va(no(a)));if(!i)throw new Uh(o,{docsPath:"/docs/contract/decodeErrorResult",cause:n});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Ys(i.inputs,vo(r,4)):void 0,errorName:i.name}}var L4=b(()=>{l();R4();Qr();Si();Ag();zh();Cf()});var bt,so=b(()=>{l();bt=(e,t,r)=>JSON.stringify(e,(n,o)=>{let s=typeof o=="bigint"?o.toString():o;return typeof t=="function"?t(n,s):s},r)});function uD({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((o,s)=>`${n&&o.name?`${o.name}: `:""}${typeof t[s]=="object"?bt(t[s]):t[s]}`).join(", ")})`}var jre=b(()=>{l();so()});function NI(e,t=0){if(!Number.isInteger(t)||t<0)throw new PI({decimals:t});let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[o,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${o||"0"}${s?`.${s}`:""}`}function qre(e,t="wei"){return NI(e,jh.ether-jh[t])}function Wre(e,t="wei"){return NI(e,jh.gwei-jh[t])}function RI(e,t=0){if(!Number.isInteger(t)||t<0)throw new PI({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new dD({value:e});let[r="",n="0"]=e.split("."),o=r.startsWith("-");if(o&&(r=r.slice(1)),r===""&&(r="0"),n=n.replace(/(0+)$/,""),t===0)n.length>0&&Number.parseInt(n[0],10)>=5&&(r=`${BigInt(r)+1n}`),n="";else if(n.length>t){let s=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){let a=BUe(s);a.length>t?(n=a.slice(1),r=`${BigInt(r)+1n}`):n=a}else n=s}else n=n.padEnd(t,"0");return BigInt(`${o?"-":""}${r}${n}`)}function BUe(e){let t=e.split(""),r=t.length-1;for(;r>=0;){let n=Number.parseInt(t[r],10)+1;if(n<10)return t[r]=String(n),t.join("");t[r]="0",r--}return`1${t.join("")}`}function Kre(e,t="wei"){return RI(e,jh.ether-jh[t])}function Zre(e,t="wei"){return RI(e,jh.gwei-jh[t])}var jh,dD,PI,Sg=b(()=>{l();jh={wei:0,gwei:9,szabo:12,finney:15,ether:18};dD=class extends Error{constructor({value:t}){super(`Value \`${t}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}},PI=class extends Error{constructor({decimals:t}){super(`\`decimals\` must be a non-negative integer. Got \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}});function qh(e,t="wei"){return qre(e,t)}var M4=b(()=>{l();Sg()});function Pn(e,t="wei"){return Wre(e,t)}var Ig=b(()=>{l();Sg()});function Gre(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n} +`),{name:"InvalidDefinitionTypeError"})}},Dw=class extends G{constructor(t){super(`Type "${t}" is not supported for packed encoding.`,{name:"UnsupportedPackedAbiType"})}}});var Lw,jU=b(()=>{l();nt();Lw=class extends G{constructor(t){super(`Filter type "${t}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}});var mg,gg,A4,C4=b(()=>{l();nt();mg=class extends G{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},gg=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}},A4=class extends G{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}});function Zr(e,{dir:t,size:r=32}={}){return typeof e=="string"?cs(e,{dir:t,size:r}):qU(e,{dir:t,size:r})}function cs(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new gg({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function qU(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new gg({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let o=0;o{l();C4()});var Xl,Mw,Hw,$w,Fw,zw,Vw,jw,yg=b(()=>{l();nt();Xl=class extends G{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number "${s}" is not in safe ${o?`${o*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},Mw=class extends G{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}},Hw=class extends G{constructor(t){super(`Hex value "${t}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}},$w=class extends G{constructor(t){super(`Hex value "${t}" is an odd length (${t.length}). It must be an even length.`,{name:"InvalidHexValueError"})}},Fw=class extends G{constructor({limit:t}){super(`RLP depth limit of \`${t}\` exceeded.`,{name:"RlpDepthLimitExceededError"})}},zw=class extends G{constructor({consumed:t,declared:r}){super(`RLP list items consumed \`${t}\` bytes but the list declared a length of \`${r}\`.`,{name:"RlpListBoundaryExceededError"})}},Vw=class extends G{constructor({count:t}){super(`RLP payload encodes a single item, but \`${t}\` trailing ${t===1?"byte remains":"bytes remain"}.`,{name:"RlpTrailingBytesError"})}},jw=class extends G{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}});function bn(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let o=0;o{l()});function Ws(e,{size:t}){if(gt(e)>t)throw new jw({givenSize:gt(e),maxSize:t})}function WU(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?wt(e,r):n==="bigint"?dt(e,r):n==="string"?bI(e,r):n==="boolean"?qw(e,r):qt(e,r)}function dt(e,t={}){let{signed:r}=t;t.size&&Ws(e,{size:t.size});let n=BigInt(e);if(!r)return n;let o=Math.ceil((e.length-2)/2),s=(1n<{l();yg();Fo();Hh();Pr()});function wr(e,t={}){return typeof e=="number"||typeof e=="bigint"?oe(e,t):typeof e=="string"?ec(e,t):typeof e=="boolean"?wg(e,t):yt(e,t)}function wg(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Ws(r,{size:t.size}),Zr(r,{size:t.size})):r}function yt(e,t={}){let r="";for(let o=0;os||o{l();yg();Xa();Xr();Jke=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Qke=new TextEncoder});function un(e,t={}){return typeof e=="number"||typeof e=="bigint"?ZU(e,t):typeof e=="boolean"?KU(e,t):We(e)?qt(e,t):zo(e,t)}function KU(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Ws(r,{size:t.size}),Zr(r,{size:t.size})):r}function ure(e){if(e>=Sf.zero&&e<=Sf.nine)return e-Sf.zero;if(e>=Sf.A&&e<=Sf.F)return e-(Sf.A-10);if(e>=Sf.a&&e<=Sf.f)return e-(Sf.a-10)}function qt(e,t={}){let r=e.slice(2);r.length%2&&(r=`0${r}`),t.size&&(Ws(e,{size:t.size}),r=r.padEnd(t.size*2,"0"));let n=r.length/2,o=new Uint8Array(n);for(let s=0,i=0;s{l();nt();qs();Xa();Xr();qe();Xke=new TextEncoder;Sf={zero:48,nine:57,A:65,F:70,a:97,f:102}});function eUe(e,t=!1){return t?{h:Number(e&xI),l:Number(e>>dre&xI)}:{h:Number(e>>dre&xI)|0,l:Number(e&xI)|0}}function fre(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s{l();xI=BigInt(4294967295),dre=BigInt(32);pre=(e,t,r)=>e<>>32-r,hre=(e,t,r)=>t<>>32-r,mre=(e,t,r)=>t<>>64-r,gre=(e,t,r)=>e<>>64-r});var bg,wre=b(()=>{l();bg=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function tUe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function xg(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function eu(e,...t){if(!tUe(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function bre(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xg(e.outputLen),xg(e.blockLen)}function If(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function vI(e,t){eu(e);let r=t.outputLen;if(e.length>>t}function S4(e,t){return e<>>32-t>>>0}function nUe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function oUe(e){for(let t=0;te().update(vg(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function AI(e=32){if(bg&&typeof bg.getRandomValues=="function")return bg.getRandomValues(new Uint8Array(e));if(bg&&typeof bg.randomBytes=="function")return Uint8Array.from(bg.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var rUe,GU,$h,Tf=b(()=>{l();wre();rUe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;GU=rUe?e=>e:oUe;$h=class{}});function pUe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=Ere(u,d,1)^r[a],p=Are(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=Sre[i],c=Ere(o,s,a),u=Are(o,s,a),d=Cre[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=dUe[n],e[1]^=fUe[n]}ba(r)}var iUe,I4,aUe,cUe,lUe,uUe,Cre,Sre,Ire,Tre,dUe,fUe,Ere,Are,YU,hUe,CI,JU=b(()=>{l();yre();Tf();iUe=BigInt(0),I4=BigInt(1),aUe=BigInt(2),cUe=BigInt(7),lUe=BigInt(256),uUe=BigInt(113),Cre=[],Sre=[],Ire=[];for(let e=0,t=I4,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Cre.push(2*(5*n+r)),Sre.push((e+1)*(e+2)/2%64);let o=iUe;for(let s=0;s<7;s++)t=(t<>cUe)*uUe)%lUe,t&aUe&&(o^=I4<<(I4<r>32?mre(e,t,r):pre(e,t,r),Are=(e,t,r)=>r>32?gre(e,t,r):hre(e,t,r);YU=class e extends $h{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,xg(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return xg(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(vI(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ba(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},hUe=(e,t,r)=>Ww(()=>new YU(t,e,r)),CI=hUe(1,136,256/8)});function Pt(e,t){let r=t||"hex",n=CI(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var Ks=b(()=>{l();JU();qs();Pr();qe()});var xo,_f=b(()=>{l();xo=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&(super.delete(t),super.set(t,r)),r}set(t,r){if(super.has(t)&&super.delete(t),super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=super.keys().next().value;n!==void 0&&super.delete(n)}return this}}});function _re(e){return mUe(e)}var mUe,Pre=b(()=>{l();Pr();Ks();mUe=e=>Pt(un(e))});function Nre(e){let t=!0,r="",n=0,o="",s=!1;for(let i=0;i{l();nt()});var Pf,SI=b(()=>{l();fg();Rre();Pf=e=>{let t=typeof e=="string"?e:Af(e);return Nre(t)}});function Nf(e){let t=typeof e=="string"?e:Af(e),r=Ore.get(t);if(r)return r;let n=_re(Pf(t));return Ore.set(t,n),n}var Ore,T4=b(()=>{l();fg();_f();Pre();SI();Ore=new xo(8192)});var Wc,Kw=b(()=>{l();T4();Wc=Nf});var br,tc=b(()=>{l();nt();br=class extends G{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}});function Kc(e,t){if(QU.has(`${e}.${t}`))return QU.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=Pt(zo(r),"bytes"),o=(t?r.substring(`${t}0x`.length):r).split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&o[i]&&(o[i]=o[i].toUpperCase()),(n[i>>1]&15)>=8&&o[i+1]&&(o[i+1]=o[i+1].toUpperCase());let s=`0x${o.join("")}`;return QU.set(`${e}.${t}`,s),s}function Gr(e,t){if(!Ft(e,{strict:!1}))throw new br({address:e});return Kc(e,t)}var QU,Zs=b(()=>{l();tc();Pr();Ks();_f();Gs();QU=new xo(8192)});function Ft(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(XU.has(n))return XU.get(n);let o=gUe.test(e)?e.toLowerCase()===e?!0:r?Kc(e)===e:!0:!1;return XU.set(n,o),o}var gUe,XU,Gs=b(()=>{l();_f();Zs();gUe=/^0x[a-fA-F0-9]{40}$/,XU=new xo(8192)});function en(e){return typeof e[0]=="string"?fr(e):eD(e)}function eD(e){let t=0;for(let o of e)t+=o.length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function fr(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}var Fn=b(()=>{l()});function vo(e,t,r,{strict:n}={}){return We(e,{strict:!1})?xa(e,t,r,{strict:n}):_4(e,t,r,{strict:n})}function Bre(e,t){if(typeof t=="number"&&t>0&&t>gt(e)-1)throw new mg({offset:t,position:"start",size:gt(e)})}function kre(e,t,r){if(typeof t=="number"&&typeof r=="number"&>(e)!==r-t)throw new mg({offset:r,position:"end",size:gt(e)})}function _4(e,t,r,{strict:n}={}){Bre(e,t);let o=e.slice(t,r);return n&&kre(o,t,r),o}function xa(e,t,r,{strict:n}={}){Bre(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&kre(o,t,r),o}var Ii=b(()=>{l();C4();qs();Fo()});var Ure,Eg,Rf,P4=b(()=>{l();Ure=/^(.*)\[([0-9]*)\]$/,Eg=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Rf=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/});function oo(e,t){if(e.length!==t.length)throw new kh({expectedLength:e.length,givenLength:t.length});let r=yUe({params:e,values:t});return nD(r)}function yUe({params:e,values:t}){let r=[];for(let n=0;ni))}}function xUe(e,{param:t}){let[,r]=t.type.split("bytes"),n=e.length%2?`0x0${e.slice(2)}`:e,o=gt(n);if(!r){let s=n;return o%32!==0&&(s=cs(s,{dir:"right",size:Math.ceil(o/32)*32})),{dynamic:!0,encoded:fr([cs(oe(o,{size:32})),s])}}if(o!==Number.parseInt(r,10))throw new Rw({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:cs(n,{dir:"right"})}}function vUe(e){if(typeof e!="boolean")throw new G(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(wg(e))}}function EUe(e,{signed:t,size:r=256}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||eo))}}function Of(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function tD(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components.some(tD);let r=Of(t);return r?tD({...e,type:r[1]}):!1}var rc=b(()=>{l();Qr();tc();nt();yg();Gs();Fn();Xa();Fo();Ii();qe();P4()});var va,Ag=b(()=>{l();Ii();T4();va=e=>vo(Nf(e),0,4)});function ls(e){let{abi:t,args:r=[],name:n}=e,o=We(n,{strict:!1}),s=t.filter(a=>o?a.type==="function"?va(a)===n:a.type==="event"?Wc(a)===n:!1:"name"in a&&a.name===n);if(s.length===0)return;if(s.length===1)return s[0];let i;for(let a of s){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((u,d)=>{let f="inputs"in a&&a.inputs[d];return f?oD(u,f):!1})){if(i&&"inputs"in i&&i.inputs){let u=sD(a.inputs,i.inputs,r);if(u)throw new wI({abiItem:a,type:u[0]},{abiItem:i,type:u[1]})}i=a}}return i||s[0]}function oD(e,t){let r=typeof e,n=t.type;switch(n){case"address":return Ft(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((s,i)=>r==="object"&&oD(Dre(e,s,i),s));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)){if(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&!Number.isInteger(e))return!1;let s=n.startsWith("int"),i=Number.parseInt(n.replace(/^u?int/,"")||"256",10),a=2n**(BigInt(i)-(s?1n:0n))-1n,c=s?-a-1n:0n;return e>=c&&e<=a}if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)){if(typeof e!="string"&&!(e instanceof Uint8Array))return!1;let s=n.slice(5);return s?typeof e=="string"&&!We(e)?!1:gt(e)===Number.parseInt(s,10):e instanceof Uint8Array||We(e)}let o=Of(n);if(o){let[s,i]=o;return Array.isArray(e)&&(s===null||e.length===s)&&e.every(a=>oD(a,{...t,type:i}))}return!1}}}function sD(e,t,r){for(let n in e){let o=e[n],s=t[n];if(!s)continue;if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s){let f=r[n],p=sD(o.components,s.components,o.components.map((h,y)=>Dre(f,h,y)));if(p)return p;continue}let i=Of(o.type),a=Of(s.type);if(i&&a){let f=sD([{...o,type:i[1]}],[{...s,type:a[1]}],[r[n]?.[0]]);if(f)return f;if(i[1]===a[1]&&o.type!==s.type)return[o.type,s.type];continue}let c=[o.type,s.type],u=r[n];if(c.includes("address")&&(c.includes("string")||c.includes("bytes"))?u===void 0||Ft(u,{strict:!1}):o.type!==s.type)return c}}function Dre(e,t,r){return Array.isArray(e)?e[r]:e?.[t.name]}var Bf=b(()=>{l();Qr();qs();Gs();Fo();Kw();Ag();rc()});function nc(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=ls({abi:t,name:r});if(!c)throw new hg(r,{docsPath:Lre});o=c}if(o.type!=="event")throw new hg(void 0,{docsPath:Lre});let s=[];if(n&&"inputs"in o){let c=o.inputs?.filter(d=>"indexed"in d&&d.indexed),u=Array.isArray(n)?n:Object.values(n).length>0?c?.map(d=>n[d.name])??[]:[];u.length>0&&(s=c?.map((d,f)=>Array.isArray(u[f])?u[f].map((p,h)=>Mre({param:d,value:u[f][h]})):typeof u[f]<"u"&&u[f]!==null?Mre({param:d,value:u[f]}):null)??[])}if(o.anonymous)return s;let i=no(o);return[Wc(i),...s]}function Mre({param:e,value:t}){if(e.type==="string")return Pt(zo(t));if(e.type==="bytes")return Pt(un(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new Lw(e.type);return oo([e],[t])}var Lre,Cg=b(()=>{l();Qr();jU();Pr();Ks();Kw();rc();Cf();Bf();Lre="/docs/contract/encodeEventTopics"});function Fh(e,{method:t}){let r={};return e.transport.type==="fallback"&&e.transport.onResponse?.(({method:n,response:o,status:s,transport:i})=>{s==="success"&&t===n&&(r[o]=i.request)}),(n=>r[n]||e.request)}var N4=b(()=>{l()});async function Zw(e,t){let{address:r,abi:n,args:o,eventName:s,fromBlock:i,strict:a,toBlock:c}=t,u=Fh(e,{method:"eth_newFilter"}),d=s?nc({abi:n,args:o,eventName:s}):void 0,f=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof i=="bigint"?oe(i):i,toBlock:typeof c=="bigint"?oe(c):c,topics:d}]});return{abi:n,args:o,eventName:s,id:f,request:u(f),strict:!!a,type:"event"}}var II=b(()=>{l();Cg();qe();N4()});function ft(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}var tn=b(()=>{l()});function TI(e){let{abi:t,args:r,functionName:n}=e,o=t[0];if(n){let s=ls({abi:t,args:r,name:n});if(!s)throw new wa(n,{docsPath:Hre});o=s}if(o.type!=="function")throw new wa(void 0,{docsPath:Hre});return{abi:[o],functionName:va(no(o))}}var Hre,iD=b(()=>{l();Qr();Ag();Cf();Bf();Hre="/docs/contract/encodeFunctionData"});function Wt(e){let{args:t}=e,{abi:r,functionName:n}=e.abi.length===1&&e.functionName?.startsWith("0x")?e:TI(e),o=r[0],s=n,i="inputs"in o&&o.inputs?oo(o.inputs,t??[]):void 0;return fr([s,i??"0x"])}var us=b(()=>{l();Fn();rc();iD()});var $re,Gw,Fre,R4=b(()=>{l();$re={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},Gw={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},Fre={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"}});var O4,Yw,_I,aD=b(()=>{l();nt();O4=class extends G{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},Yw=class extends G{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},_I=class extends G{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}});function Zc(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(SUe);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var SUe,Jw=b(()=>{l();aD();SUe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new _I({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new Yw({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new O4({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new O4({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}}});function zre(e,t){let r=typeof t=="string"?{to:t}:t,n=r.to;return n==="number"?Ea(e,r):n==="bigint"?B4(e,r):n==="boolean"?k4(e,r):n==="string"?U4(e,r):yt(e,r)}function B4(e,t={}){typeof t.size<"u"&&Ws(e,{size:t.size});let r=yt(e);return dt(r,t)}function k4(e,t={}){let r=e;if(typeof t.size<"u"&&(Ws(r,{size:t.size}),r=bn(r)),r.length>1||r[0]>1)throw new Mw(r);return!!r[0]}function Ea(e,t={}){typeof t.size<"u"&&Ws(e,{size:t.size});let r=yt(e);return wt(r,t)}function U4(e,t={}){let r=e;return typeof t.size<"u"&&(Ws(r,{size:t.size}),r=bn(r,{dir:"right"})),new TextDecoder().decode(r)}var cD=b(()=>{l();yg();Hh();Xr();qe()});function Ys(e,t){let r=typeof t=="string"?qt(t):t,n=Zc(r);if(gt(r)===0&&e.length>0)throw new Si;if(gt(t)&>(t)<32)throw new Bh({data:typeof t=="string"?t:yt(t),params:e,size:gt(t)});let o={limit:r.length*32,used:0},s=0,i=[];for(let a=0;ar.limit)throw new Xw({limit:r.limit});return e.setPosition(n+32),[yt(u),32]}return[yt(e.readBytes(Number.parseInt(s,10),32)),32]}function NUe(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?B4(o,{signed:r}):Ea(o,{signed:r}),32]}function RUe(e,t,{budget:r,staticPosition:n}){let o=t.components.length===0||t.components.some(({name:a})=>!a),s=o?[]:{},i=0;if(D4(t)){let a=Ea(e.readBytes(lD)),c=n+a;for(let u=0;ut.limit)throw new Xw({limit:t.limit});let a=U4(i);return e.setPosition(r+32),[a,32]}function D4(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(D4);let r=Of(e.type);return!!(r&&D4({...e,type:r[1]}))}var Vre,lD,Xw,zh=b(()=>{l();Qr();nt();Zs();Jw();Fo();Ii();cD();Pr();qe();rc();Vre=32,lD=32;Xw=class extends G{constructor({limit:t}){super(`Decoded \`bytes\` and \`string\` values exceed the size limit of ${t} bytes.`,{name:"AbiDecodingSizeLimitExceededError"})}}});function Vh(e){let{abi:t,data:r,cause:n}=e,o=vo(r,0,4);if(o==="0x")throw new Si({cause:n});let i=[...t||[],Gw,Fre].find(a=>a.type==="error"&&o===va(no(a)));if(!i)throw new Uh(o,{docsPath:"/docs/contract/decodeErrorResult",cause:n});return{abiItem:i,args:"inputs"in i&&i.inputs&&i.inputs.length>0?Ys(i.inputs,vo(r,4)):void 0,errorName:i.name}}var L4=b(()=>{l();R4();Qr();Ii();Ag();zh();Cf()});var bt,so=b(()=>{l();bt=(e,t,r)=>JSON.stringify(e,(n,o)=>{let s=typeof o=="bigint"?o.toString():o;return typeof t=="function"?t(n,s):s},r)});function uD({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((o,s)=>`${n&&o.name?`${o.name}: `:""}${typeof t[s]=="object"?bt(t[s]):t[s]}`).join(", ")})`}var jre=b(()=>{l();so()});function NI(e,t=0){if(!Number.isInteger(t)||t<0)throw new PI({decimals:t});let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[o,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${o||"0"}${s?`.${s}`:""}`}function qre(e,t="wei"){return NI(e,jh.ether-jh[t])}function Wre(e,t="wei"){return NI(e,jh.gwei-jh[t])}function RI(e,t=0){if(!Number.isInteger(t)||t<0)throw new PI({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new dD({value:e});let[r="",n="0"]=e.split("."),o=r.startsWith("-");if(o&&(r=r.slice(1)),r===""&&(r="0"),n=n.replace(/(0+)$/,""),t===0)n.length>0&&Number.parseInt(n[0],10)>=5&&(r=`${BigInt(r)+1n}`),n="";else if(n.length>t){let s=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){let a=BUe(s);a.length>t?(n=a.slice(1),r=`${BigInt(r)+1n}`):n=a}else n=s}else n=n.padEnd(t,"0");return BigInt(`${o?"-":""}${r}${n}`)}function BUe(e){let t=e.split(""),r=t.length-1;for(;r>=0;){let n=Number.parseInt(t[r],10)+1;if(n<10)return t[r]=String(n),t.join("");t[r]="0",r--}return`1${t.join("")}`}function Kre(e,t="wei"){return RI(e,jh.ether-jh[t])}function Zre(e,t="wei"){return RI(e,jh.gwei-jh[t])}var jh,dD,PI,Sg=b(()=>{l();jh={wei:0,gwei:9,szabo:12,finney:15,ether:18};dD=class extends Error{constructor({value:t}){super(`Value \`${t}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}},PI=class extends Error{constructor({decimals:t}){super(`\`decimals\` must be a non-negative integer. Got \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}});function qh(e,t="wei"){return qre(e,t)}var M4=b(()=>{l();Sg()});function Pn(e,t="wei"){return Wre(e,t)}var Ig=b(()=>{l();Sg()});function Gre(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n} `,"")}function Yre(e){return e.reduce((t,{address:r,...n})=>{let o=`${t} ${r}: `;return n.nonce&&(o+=` nonce: ${n.nonce} `),n.balance&&(o+=` balance: ${n.balance} @@ -49,35 +49,35 @@ if (cid) { `,o+=Gre(n.stateDiff)),o},` State Override: `).slice(0,-1)}var tb,rb,OI=b(()=>{l();nt();tb=class extends G{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}},rb=class extends G{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}});function Tg(e){let t=Object.entries(e).map(([n,o])=>o===void 0||o===!1?null:[n,o]).filter(Boolean),r=t.reduce((n,[o])=>Math.max(n,o.length),0);return t.map(([n,o])=>` ${`${n}:`.padEnd(r+1)} ${o}`).join(` `)}var BI,Wh,Kh,tu,nb,ob,ru,sb,ib,Gc,nu,Zh,Gh,zn=b(()=>{l();M4();Ig();nt();BI=class extends G{constructor(){super(["Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.","Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."].join(` -`),{name:"FeeConflictError"})}},Wh=class extends G{constructor({filledNonce:t,requestedNonce:r}){super("The filled transaction nonce does not match the requested nonce.",{metaMessages:[`Requested Nonce: ${r}`,`Filled Nonce: ${t}`],name:"FeePayerNonceMismatchError"})}},Kh=class extends G{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}},tu=class extends G{constructor({yParity:t}){super(`Invalid \`yParity\` value "${t}". Expected 0 or 1.`,{name:"InvalidYParityError"})}},nb=class extends G{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Tg(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}},ob=class extends G{constructor({serializedType:t}){super(`Serialized transaction type "${t}" is invalid.`,{name:"InvalidSerializedTransactionType"}),Object.defineProperty(this,"serializedType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedType=t}},ru=class extends G{constructor({attributes:t,serializedTransaction:r,type:n}){let o=Object.entries(t).map(([s,i])=>typeof i>"u"?s:void 0).filter(Boolean);super(`Invalid serialized transaction of type "${n}" was provided.`,{metaMessages:[`Serialized Transaction: "${r}"`,o.length>0?`Missing Attributes: ${o.join(", ")}`:""].filter(Boolean),name:"InvalidSerializedTransactionError"}),Object.defineProperty(this,"serializedTransaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedTransaction=r,this.type=n}},sb=class extends G{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}},ib=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p}){let h=Tg({chain:o&&`${o?.name} (id: ${o?.id})`,from:r?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",h].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},Gc=class extends G{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:o,index:s}){let i="Transaction";n&&s!==void 0&&(i=`Transaction at block time "${n}" at index "${s}"`),t&&s!==void 0&&(i=`Transaction at block hash "${t}" at index "${s}"`),r&&s!==void 0&&(i=`Transaction at block number "${r}" at index "${s}"`),o&&(i=`Transaction with hash "${o}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}},nu=class extends G{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}},Zh=class extends G{constructor({receipt:t}){super(`Transaction with hash "${t.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=t}},Gh=class extends G{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}});function Nn(e){if(e?.reason)return e.reason;if(typeof DOMException=="function")return new DOMException("This operation was aborted","AbortError");let t=new Error("This operation was aborted");return t.name="AbortError",t}function Ii(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var Jre,kf,oc=b(()=>{l();Jre=e=>e;kf=e=>{try{let t=new URL(e);return!t.username&&!t.password?e:(t.username="",t.password="",t.toString())}catch{return e}}});var Yc,ab,Uf,cb,lb,sc,ou=b(()=>{l();tn();R4();L4();Cf();jre();Bf();M4();Ig();Qr();nt();OI();zn();oc();Yc=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p,stateOverride:h}){let y=r?ft(r):void 0,w=Tg({from:y?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});h&&(w+=` +`),{name:"FeeConflictError"})}},Wh=class extends G{constructor({filledNonce:t,requestedNonce:r}){super("The filled transaction nonce does not match the requested nonce.",{metaMessages:[`Requested Nonce: ${r}`,`Filled Nonce: ${t}`],name:"FeePayerNonceMismatchError"})}},Kh=class extends G{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}},tu=class extends G{constructor({yParity:t}){super(`Invalid \`yParity\` value "${t}". Expected 0 or 1.`,{name:"InvalidYParityError"})}},nb=class extends G{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Tg(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}},ob=class extends G{constructor({serializedType:t}){super(`Serialized transaction type "${t}" is invalid.`,{name:"InvalidSerializedTransactionType"}),Object.defineProperty(this,"serializedType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedType=t}},ru=class extends G{constructor({attributes:t,serializedTransaction:r,type:n}){let o=Object.entries(t).map(([s,i])=>typeof i>"u"?s:void 0).filter(Boolean);super(`Invalid serialized transaction of type "${n}" was provided.`,{metaMessages:[`Serialized Transaction: "${r}"`,o.length>0?`Missing Attributes: ${o.join(", ")}`:""].filter(Boolean),name:"InvalidSerializedTransactionError"}),Object.defineProperty(this,"serializedTransaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.serializedTransaction=r,this.type=n}},sb=class extends G{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}},ib=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p}){let h=Tg({chain:o&&`${o?.name} (id: ${o?.id})`,from:r?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",h].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},Gc=class extends G{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:o,index:s}){let i="Transaction";n&&s!==void 0&&(i=`Transaction at block time "${n}" at index "${s}"`),t&&s!==void 0&&(i=`Transaction at block hash "${t}" at index "${s}"`),r&&s!==void 0&&(i=`Transaction at block number "${r}" at index "${s}"`),o&&(i=`Transaction with hash "${o}"`),super(`${i} could not be found.`,{name:"TransactionNotFoundError"})}},nu=class extends G{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}},Zh=class extends G{constructor({receipt:t}){super(`Transaction with hash "${t.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=t}},Gh=class extends G{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}});function Nn(e){if(e?.reason)return e.reason;if(typeof DOMException=="function")return new DOMException("This operation was aborted","AbortError");let t=new Error("This operation was aborted");return t.name="AbortError",t}function Ti(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var Jre,kf,oc=b(()=>{l();Jre=e=>e;kf=e=>{try{let t=new URL(e);return!t.username&&!t.password?e:(t.username="",t.password="",t.toString())}catch{return e}}});var Yc,ab,Uf,cb,lb,sc,ou=b(()=>{l();tn();R4();L4();Cf();jre();Bf();M4();Ig();Qr();nt();OI();zn();oc();Yc=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p,stateOverride:h}){let y=r?ft(r):void 0,w=Tg({from:y?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});h&&(w+=` ${Yre(h)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",w].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},ab=class extends G{constructor(t,{abi:r,args:n,contractAddress:o,docsPath:s,functionName:i,sender:a}){let c=ls({abi:r,args:n,name:i}),u=c?uD({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,d=c?no(c,{includeName:!0}):void 0,f=Tg({address:o&&Jre(o),function:d,args:u&&u!=="()"&&`${[...Array(i?.length??0).keys()].map(()=>" ").join("")}${u}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${i}".`,{cause:t,docsPath:s,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],f&&"Contract Call:",f].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=o,this.functionName=i,this.sender=a}},Uf=class extends G{constructor({abi:t,data:r,functionName:n,message:o,cause:s}){let i,a,c,u;if(r&&r!=="0x")try{a=Vh({abi:t,data:r,cause:s});let{abiItem:f,errorName:p,args:h}=a;if(p==="Error")u=h[0];else if(p==="Panic"){let[y]=h;u=$re[y]}else{let y=f?no(f,{includeName:!0}):void 0,w=f&&h?uD({abiItem:f,args:h,includeFunctionName:!1,includeName:!1}):void 0;c=[y?`Error: ${y}`:"",w&&w!=="()"?` ${[...Array(p?.length??0).keys()].map(()=>" ").join("")}${w}`:""]}}catch(f){i=f}else o&&(u=o);let d;i instanceof Uh&&(d=i.signature,c=[`Unable to decode signature "${d}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${d}.`]),super(u&&u!=="execution reverted"||d?[`The contract function "${n}" reverted with the following ${d?"signature":"reason"}:`,u||d].join(` -`):`The contract function "${n}" reverted.`,{cause:i??s,metaMessages:c,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=u,this.signature=d}},cb=class extends G{constructor({functionName:t,cause:r}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:r})}},lb=class extends G{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}},sc=class extends G{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}}});var Nr,ic,_g,Rn,su,ds,fs=b(()=>{l();so();nt();oc();Nr=class extends G{constructor({body:t,cause:r,details:n,headers:o,status:s,url:i}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[s&&`Status: ${s}`,`URL: ${kf(i)}`,t&&`Request body: ${bt(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=o,this.status=s,this.url=i}},ic=class extends G{constructor({maxSize:t,size:r}){super("HTTP response body exceeded the size limit.",{metaMessages:[`Max: ${t} bytes`,`Received: ${r} bytes`],name:"ResponseBodyTooLargeError"}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t,this.size=r}},_g=class extends G{constructor({body:t,cause:r,details:n,url:o}){super("WebSocket request failed.",{cause:r,details:n,metaMessages:[`URL: ${kf(o)}`,t&&`Request body: ${bt(t)}`].filter(Boolean),name:"WebSocketRequestError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=o}},Rn=class extends G{constructor({body:t,error:r,headers:n,status:o,url:s}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[o&&`Status: ${o}`,`URL: ${kf(s)}`,`Request body: ${bt(t)}`].filter(Boolean),name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.headers=n,this.status=o,this.url=s}},su=class extends G{constructor({url:t}={}){super("The socket has been closed.",{metaMessages:[t&&`URL: ${kf(t)}`].filter(Boolean),name:"SocketClosedError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}},ds=class extends G{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${kf(r)}`,`Request body: ${bt(t)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}});var kUe,Eo,Ao,Yh,Jh,Jc,Qh,Qc,Ti,Xh,e0,iu,Aa,Df,t0,Xc,r0,n0,o0,s0,i0,au,a0,c0,l0,u0,d0,cu,f0,ub,Lf=b(()=>{l();nt();fs();kUe=-1,Eo=class extends G{constructor(t,{code:r,docsPath:n,metaMessages:o,name:s,shortMessage:i}){super(i,{cause:t,docsPath:n,metaMessages:o||t?.metaMessages,name:s||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s||t.name,this.code=t instanceof Rn?t.code:r??kUe}},Ao=class extends Eo{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}},Yh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};Object.defineProperty(Yh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});Jh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};Object.defineProperty(Jh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});Jc=class e extends Eo{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}};Object.defineProperty(Jc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Qh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(` -`)})}};Object.defineProperty(Qh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});Qc=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};Object.defineProperty(Qc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Ti=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(` -`)})}};Object.defineProperty(Ti,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});Xh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(Xh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});e0=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(e0,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});iu=class e extends Eo{constructor(t){super(t,{code:e.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(iu,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});Aa=class e extends Eo{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}};Object.defineProperty(Aa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});Df=class e extends Eo{constructor(t){super(t,{code:e.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty(Df,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});t0=class e extends Eo{constructor(t){super(t,{code:e.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(t0,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Xc=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Xc,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});r0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(r0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});n0=class e extends Ao{constructor(t,{method:r}={}){super(t,{code:e.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}};Object.defineProperty(n0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});o0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(o0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});s0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(s0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});i0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty(i0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});au=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(au,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});a0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(a0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});c0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(c0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});l0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(l0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});u0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(u0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});d0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(d0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});cu=class e extends Ao{constructor(t){super(t,{code:e.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(cu,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});f0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(f0,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});ub=class extends Eo{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});function Js(e,{abi:t,address:r,args:n,docsPath:o,functionName:s,sender:i}){let a=e instanceof sc?e:e instanceof G?e.walk(y=>typeof y=="object"&&y!==null&&"data"in y)||e.walk():{},{code:c,data:u,details:d,message:f,shortMessage:p}=a,h=e instanceof Ci?new cb({functionName:s,cause:e}):[UUe,Qc.code].includes(c)&&(u||d||f||p)||c===Ti.code&&d==="execution reverted"&&u?new Uf({abi:t,data:typeof u=="object"?u.data:u,functionName:s,message:a instanceof Rn?d:p??f,cause:e}):e;return new ab(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:s,sender:i})}var UUe,p0=b(()=>{l();Qr();nt();ou();fs();Lf();UUe=3});function Qre(e){let t=Pt(`0x${e.substring(4)}`).substring(26);return Kc(`0x${t}`)}var Xre=b(()=>{l();Zs();Ks()});function DUe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function fD(e,t,r){return e&t^~e&r}function pD(e,t,r){return e&t^e&r^t&r}var db,Mf,hD=b(()=>{l();Tf();db=class extends $h{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=EI(this.buffer)}update(t){If(this),t=vg(t),eu(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f{l();hD();Tf();LUe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),h0=new Uint32Array(64),kI=class extends db{constructor(t=32){super(64,t,8,!1),this.A=Mf[0]|0,this.B=Mf[1]|0,this.C=Mf[2]|0,this.D=Mf[3]|0,this.E=Mf[4]|0,this.F=Mf[5]|0,this.G=Mf[6]|0,this.H=Mf[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)h0[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=h0[f-15],h=h0[f-2],y=qc(p,7)^qc(p,18)^p>>>3,w=qc(h,17)^qc(h,19)^h>>>10;h0[f]=w+h0[f-7]+y+h0[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=qc(a,6)^qc(a,11)^qc(a,25),h=d+p+fD(a,c,u)+LUe[f]+h0[f]|0,w=(qc(n,2)^qc(n,13)^qc(n,22))+pD(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){ba(h0)}destroy(){this.set(0,0,0,0,0,0,0,0),ba(this.buffer)}},Pg=Ww(()=>new kI)});var UI,gD,ene=b(()=>{l();Tf();UI=class extends $h{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,bre(t);let n=vg(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew UI(e,t).update(r).digest();gD.create=(e,t)=>new UI(e,t)});function fb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function $f(e){if(!fb(e))throw new Error("Uint8Array expected")}function pb(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function H4(e){let t=e.toString(16);return t.length&1?"0"+t:t}function nne(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?xD:BigInt("0x"+e)}function hb(e){if($f(e),one)return e.toHex();let t="";for(let r=0;r=Hf._0&&e<=Hf._9)return e-Hf._0;if(e>=Hf.A&&e<=Hf.F)return e-(Hf.A-10);if(e>=Hf.a&&e<=Hf.f)return e-(Hf.a-10)}function $4(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(one)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oxD;e>>=bD,t+=1);return t}function ine(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=wD(e),o=wD(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=wD(0))=>{o=a(rne([0]),f),n=a(),f.length!==0&&(o=a(rne([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}function zf(e,t,r={}){let n=(o,s,i)=>{let a=HUe[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function AD(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var xD,bD,one,MUe,Hf,yD,Rg,wD,rne,HUe,mb=b(()=>{l();xD=BigInt(0),bD=BigInt(1);one=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",MUe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Hf={_0:48,_9:57,A:65,F:70,a:97,f:102};yD=e=>typeof e=="bigint"&&xD<=e;Rg=e=>(bD<new Uint8Array(e),rne=e=>Uint8Array.from(e);HUe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||fb(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function On(e,t){let r=e%t;return r>=Xs?r:t+r}function Ca(e,t,r){let n=e;for(;t-- >Xs;)n*=n,n%=r;return n}function LI(e,t){if(e===Xs)throw new Error("invert: expected non-zero number");if(t<=Xs)throw new Error("invert: expected positive modulus, got "+t);let r=On(e,t),n=t,o=Xs,s=ps,i=ps,a=Xs;for(;r!==Xs;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ps)throw new Error("invert: does not exist");return On(o,t)}function dne(e,t){let r=(e.ORDER+ps)/cne,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function FUe(e,t){let r=(e.ORDER-lne)/une,n=e.mul(t,Og),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Og),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function zUe(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return dne;let s=o.pow(n,t),i=(t+ps)/Og;return function(c,u){if(c.is0(u))return u;if(ane(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ps<(n[o]="function",n),t);return zf(e,r)}function qUe(e,t,r){if(rXs;)r&ps&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ps;return n}function gb(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function ane(e,t){let r=(e.ORDER-ps)/Og,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function CD(e,t){t!==void 0&&xg(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function F4(e,t,r=!1,n={}){if(e<=Xs)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=CD(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:Rg(o),ZERO:Xs,ONE:ps,create:c=>On(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Xs<=c&&cc===Xs,isOdd:c=>(c&ps)===ps,neg:c=>On(-c,e),eql:(c,u)=>c===u,sqr:c=>On(c*c,e),add:(c,u)=>On(c+u,e),sub:(c,u)=>On(c-u,e),mul:(c,u)=>On(c*u,e),pow:(c,u)=>qUe(a,c,u),div:(c,u)=>On(c*LI(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>LI(c,e),sqrt:n.sqrt||(c=>(i||(i=VUe(e)),i(a,c))),toBytes:c=>r?ED(c,s):lu(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?vD(c):_i(c)},invertBatch:c=>gb(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function fne(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function SD(e){let t=fne(e);return t+Math.ceil(t/2)}function pne(e,t,r=!1){let n=e.length,o=fne(t),s=SD(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?vD(e):_i(e),a=On(i,t-ps)+ps;return r?ED(a,o):lu(a,o)}var Xs,ps,Og,$Ue,cne,lne,une,jUe,z4=b(()=>{l();Tf();mb();Xs=BigInt(0),ps=BigInt(1),Og=BigInt(2),$Ue=BigInt(3),cne=BigInt(4),lne=BigInt(5),une=BigInt(8);jUe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function ID(e,t){let r=t.negate();return e?r:t}function gne(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function TD(e,t){gne(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=Rg(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function mne(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=ND);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function WUe(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function KUe(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function PD(e){return yne.get(e)||1}function wne(e,t){return{constTimeNegate:ID,hasPrecomputes(r){return PD(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>hne;)n&ND&&(o=o.add(s)),s=s.double(),n>>=ND;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=TD(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Rg(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{l();z4();mb();hne=BigInt(0),ND=BigInt(1);_D=new WeakMap,yne=new WeakMap});function vne(e){e.lowS!==void 0&&pb("lowS",e.lowS),e.prehash!==void 0&&pb("prehash",e.prehash)}function ZUe(e){let t=RD(e);zf(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function OD(e,t){return hb(lu(e,t))}function GUe(e){let t=ZUe(e),{Fp:r}=t,n=F4(t.n,t.nBitLength),o=t.toBytes||((E,S,_)=>{let O=S.toAffine();return Qs(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,V4),kD),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return Ng(E,Tr,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(fb(E)&&(E=hb(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:_i(Vn("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=On(M,D)),Ff("private key",M,Tr,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=AD((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=AD(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=gb(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(Vn("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return bne(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,V4),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,V4),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;Ff("scalar",S,el,O);let D=w.ZERO;if(S===el)return D;if(this.is0()||S===Tr)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>el||P>el;)N&Tr&&(R=R.add(B)),P&Tr&&(I=I.add(B)),B=B.double(),N>>=Tr,P>>=Tr;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;Ff("scalar",S,Tr,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===el||P===Tr||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===Tr)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===Tr?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return pb("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return pb("isCompressed",S),hb(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=wne(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function YUe(e){let t=RD(e);return zf(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Ene(e){let t=YUe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return On(C,n)}function u(C){return LI(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=GUe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=Qs;return pb("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=_i(H);if(!Ng(k,Tr,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&Tr)===Tr;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>Tr;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>_i(C.slice(A,U));class v{constructor(A,U,H){Ff("r",A,Tr,n),Ff("s",U,Tr,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=Vn("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=Vf.toSig(Vn("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(Vn("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+OD(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return $4(this.toDERHex())}toDERHex(){return Vf.hexFromSig(this)}toCompactRawBytes(){return $4(this.toCompactHex())}toCompactHex(){let A=o;return OD(this.r,A)+OD(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=SD(t.n);return pne(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=Vn("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=_i(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=Rg(s);function N(C){return Ff("num < 2^"+s,C,el,M),lu(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=Vn("msgHash",C),vne(U),j&&(C=Vn("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(Vn("extraEntropy",ye))}let pe=Qs(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===el)return;let ur=c(Et*c(me+At*te));if(ur===el)return;let _r=(kt.x===At?0:2)|Number(kt.y&Tr),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return ine(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=Vn("msgHash",A),U=Vn("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(vne(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||fb(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof Vf.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}function JUe(e,t){let r=e.ORDER,n=el;for(let y=r-Tr;y%m0===el;y/=m0)n+=Tr;let o=n,s=m0<{let x=f,v=e.pow(w,u),T=e.sqr(v);T=e.mul(T,w);let E=e.mul(y,T);E=e.pow(E,c),E=e.mul(E,v),v=e.mul(E,w),T=e.mul(E,y);let S=e.mul(T,v);E=e.pow(S,d);let _=e.eql(E,e.ONE);v=e.mul(T,p),E=e.mul(S,x),T=e.cmov(v,T,_),S=e.cmov(E,S,_);for(let O=o;O>Tr;O--){let D=O-m0;D=m0<{let T=e.sqr(v),E=e.mul(x,v);T=e.mul(T,E);let S=e.pow(T,y);S=e.mul(S,E);let _=e.mul(S,w),O=e.mul(e.sqr(S),v),D=e.eql(O,x),M=e.cmov(_,S,D);return{isValid:D,value:M}}}return h}function Ane(e,t){if(MI(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");let r=JUe(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let o,s,i,a,c,u,d,f;o=e.sqr(n),o=e.mul(o,t.Z),s=e.sqr(o),s=e.add(s,o),i=e.add(s,e.ONE),i=e.mul(i,t.B),a=e.cmov(t.Z,e.neg(s),!e.eql(s,e.ZERO)),a=e.mul(a,t.A),s=e.sqr(i),u=e.sqr(a),c=e.mul(u,t.A),s=e.add(s,c),s=e.mul(s,i),u=e.mul(u,a),c=e.mul(u,t.B),s=e.add(s,c),d=e.mul(o,i);let{isValid:p,value:h}=r(s,u);f=e.mul(o,n),f=e.mul(f,h),d=e.cmov(d,i,p),f=e.cmov(f,h,p);let y=e.isOdd(n)===e.isOdd(f);f=e.cmov(e.neg(f),f,y);let w=gb(e,[a],!0)[0];return d=e.mul(d,w),{x:d,y:f}}}var BD,Vf,el,Tr,m0,V4,kD,UD=b(()=>{l();xne();z4();mb();BD=class extends Error{constructor(t=""){super(t)}},Vf={Err:BD,_tlv:{encode:(e,t)=>{let{Err:r}=Vf;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=H4(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?H4(o.length/2|128):"";return H4(e)+s+o+t},decode(e,t){let{Err:r}=Vf,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Vf;if(egD(e,t,vre(...r)),randomBytes:AI}}function Cne(e,t){let r=n=>Ene({...e,...QUe(n)});return{...r(t),create:r}}var Sne=b(()=>{l();ene();Tf();UD();});function g0(e,t){if(j4(e),j4(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function eDe(e,t){let r=new Uint8Array(e.length);for(let n=0;n255&&(t=n(Qs(DI("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Qs(t,g0(t.length,1)),c=g0(0,s),u=g0(r,2),d=new Array(i),f=n(Qs(c,e,u,g0(0,1),a));d[0]=n(Qs(f,g0(1,1),a));for(let h=1;h<=i;h++){let y=[eDe(f,d[h-1]),g0(h+1,1),a];d[h]=n(Qs(...y))}return Qs(...d).slice(0,r)}function rDe(e,t,r,n,o){if($f(e),$f(t),j4(r),t.length>255){let s=Math.ceil(2*n/8);t=o.create({dkLen:s}).update(DI("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(g0(r,2)).update(t).update(g0(t.length,1)).digest()}function Ine(e,t,r){zf(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;$f(e),j4(t);let u=typeof c=="string"?DI(c):c,d=n.toString(2).length,f=Math.ceil((d+o)/8),p=t*s*f,h;if(a==="xmd")h=tDe(e,u,p,i);else if(a==="xof")h=rDe(e,u,p,o,i);else if(a==="_internal_pass")h=e;else throw new Error('expand must be "xmd" or "xof"');let y=new Array(t);for(let w=0;wArray.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(f=>f.reduce((p,h)=>e.add(e.mul(p,n),h))),[u,d]=gb(e,[i,c],!0);return n=e.mul(s,u),o=e.mul(o,e.mul(a,d)),{x:n,y:o}}}function _ne(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(s){return e.fromAffine(t(s))}function o(s){let i=s.clearCofactor();return i.equals(e.ZERO)?e.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Ine(s,2,{...r,DST:r.DST,...i}),c=n(a[0]),u=n(a[1]);return o(c.add(u))},encodeToCurve(s,i){let a=Ine(s,1,{...r,DST:r.encodeDST,...i});return o(n(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))}}}var XUe,Pne=b(()=>{l();z4();mb();XUe=_i});var Dne={};Te(Dne,{encodeToCurve:()=>uDe,hashToCurve:()=>lDe,schnorr:()=>iDe,secp256k1:()=>ei,secp256k1_hasher:()=>zD});function One(e){let t=K4,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=Ca(d,r,t)*d%t,p=Ca(f,r,t)*d%t,h=Ca(p,$I,t)*u%t,y=Ca(h,o,t)*h%t,w=Ca(y,s,t)*y%t,x=Ca(w,a,t)*w%t,v=Ca(x,c,t)*x%t,T=Ca(v,a,t)*w%t,E=Ca(T,r,t)*d%t,S=Ca(E,i,t)*y%t,_=Ca(S,n,t)*u%t,O=Ca(_,$I,t);if(!y0.eql(y0.sqr(O),e))throw new Error("Cannot find square root");return O}function FI(e,...t){let r=Rne[e];if(r===void 0){let n=Pg(Uint8Array.from(e,o=>o.charCodeAt(0)));r=Qs(n,n),Rne[e]=r}return Pg(Qs(r,...t))}function MD(e){let t=ei.utils.normPrivateKeyToScalar(e),r=FD.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:W4(-t),bytes:$D(r)}}function Bne(e){Ff("x",e,q4,K4);let t=DD(e*e),r=DD(t*e+BigInt(7)),n=One(r);n%$I!==HD&&(n=DD(-n));let o=new FD(e,n,q4);return o.assertValidity(),o}function kne(...e){return W4(yb(FI("BIP0340/challenge",...e)))}function oDe(e){return MD(e).bytes}function sDe(e,t,r=AI(32)){let n=Vn("message",e),{bytes:o,scalar:s}=MD(t),i=Vn("auxRand",r,32),a=LD(s^yb(FI("BIP0340/aux",i))),c=FI("BIP0340/nonce",a,o,n),u=W4(yb(c));if(u===HD)throw new Error("sign failed: k is zero");let{bytes:d,scalar:f}=MD(u),p=kne(d,o,n),h=new Uint8Array(64);if(h.set(d,0),h.set(LD(W4(f+p*s)),32),!Une(h,n,o))throw new Error("sign: Invalid signature produced");return h}function Une(e,t,r){let n=Vn("signature",e,64),o=Vn("message",t),s=Vn("publicKey",r,32);try{let i=Bne(yb(s)),a=yb(n.subarray(0,32));if(!Ng(a,q4,K4))return!1;let c=yb(n.subarray(32,64));if(!Ng(c,q4,HI))return!1;let u=kne(LD(a),$D(i),o),d=nDe(i,c,W4(-u));return!(!d||!d.hasEvenY()||d.toAffine().x!==a)}catch{return!1}}var K4,HI,HD,q4,$I,Nne,y0,ei,Rne,$D,LD,DD,W4,FD,nDe,yb,iDe,aDe,cDe,zD,lDe,uDe,Bg=b(()=>{l();mD();Tf();Sne();Pne();z4();mb();UD();K4=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),HI=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),HD=BigInt(0),q4=BigInt(1),$I=BigInt(2),Nne=(e,t)=>(e+t/$I)/t;y0=F4(K4,void 0,void 0,{sqrt:One}),ei=Cne({a:HD,b:BigInt(7),Fp:y0,n:HI,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=HI,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-q4*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Nne(s*e,t),c=Nne(-n*e,t),u=On(e-a*r-c*o,t),d=On(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},Pg),Rne={};$D=e=>e.toRawBytes(!0).slice(1),LD=e=>lu(e,32),DD=e=>On(e,K4),W4=e=>On(e,HI),FD=ei.ProjectivePoint,nDe=(e,t,r)=>FD.BASE.multiplyAndAddUnsafe(e,t,r);yb=_i;iDe={getPublicKey:oDe,sign:sDe,verify:Une,utils:{randomPrivateKey:ei.utils.randomPrivateKey,lift_x:Bne,pointToBytes:$D,numberToBytesBE:lu,bytesToNumberBE:_i,taggedHash:FI,mod:On}},aDe=Tne(y0,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),cDe=Ane(y0,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:y0.create(BigInt("-11"))}),zD=_ne(ei.ProjectivePoint,e=>{let{x:t,y:r}=cDe(y0.create(e[0]));return aDe(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:y0.ORDER,m:1,k:128,expand:"xmd",hash:Pg}),lDe=zD.hashToCurve,uDe=zD.encodeToCurve});async function zI({hash:e,signature:t}){let r=We(e)?e:wr(e),{secp256k1:n}=await Promise.resolve().then(()=>(Bg(),Dne));return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){let{r:u,s:d,v:f,yParity:p}=t,h=p===void 0&&f!==void 0&&f>=35n?f%2n===0n?1:0:Lne(Number(p??f));return new n.Signature(dt(u),dt(d)).addRecoveryBit(h)}let i=We(t)?t:wr(t);if(gt(i)!==65)throw new Error("invalid signature length");let a=wt(`0x${i.slice(130)}`),c=Lne(a);return n.Signature.fromCompact(i.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Lne(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}var VD=b(()=>{l();qs();Fo();Xr();qe()});async function ti({hash:e,signature:t}){return Qre(await zI({hash:e,signature:t}))}var w0=b(()=>{l();Xre();VD()});function Vo(e,t="hex"){let r=$ne(e),n=Zc(new Uint8Array(r.length));return r.encode(n),t==="hex"?yt(n.bytes):n.bytes}function Mne(e,t="bytes"){return Vo(e,t)}function Hne(e,t="hex"){return Vo(e,t)}function $ne(e){return Array.isArray(e)?dDe(e.map(t=>$ne(t))):fDe(e)}function dDe(e){let t=e.reduce((o,s)=>o+s.length,0),r=Fne(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function fDe(e){let t=typeof e=="string"?qt(e):e,r=Fne(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function Fne(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new G("Length is too large.")}var wb=b(()=>{l();nt();Jw();Pr();qe()});function zne(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,s=Pt(fr(["0x05",Vo([t?oe(t):"0x",o,r?oe(r):"0x"])]));return n==="bytes"?qt(s):s}var Vne=b(()=>{l();Fn();Pr();qe();wb();Ks()});async function b0(e){let{authorization:t}=e,r=e.signature??t;if(typeof r=="object"&&typeof r.yParity=="number"&&r.yParity!==0&&r.yParity!==1)throw new tu({yParity:BigInt(r.yParity)});return ti({hash:zne(t),signature:r})}var Z4=b(()=>{l();zn();w0();Vne()});var bb,jD=b(()=>{l();M4();Ig();nt();zn();bb=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p}){let h=Tg({from:r?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",h].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}});var ri,Pi,x0,v0,E0,A0,C0,S0,I0,T0,ac,Ni,tl=b(()=>{l();Ig();nt();ri=class extends G{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};Object.defineProperty(ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ri,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Pi=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(Pi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});x0=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};Object.defineProperty(x0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});v0=class extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};Object.defineProperty(v0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});E0=class extends G{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` +`):`The contract function "${n}" reverted.`,{cause:i??s,metaMessages:c,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=u,this.signature=d}},cb=class extends G{constructor({functionName:t,cause:r}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:r})}},lb=class extends G{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}},sc=class extends G{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}}});var Nr,ic,_g,Rn,su,ds,fs=b(()=>{l();so();nt();oc();Nr=class extends G{constructor({body:t,cause:r,details:n,headers:o,status:s,url:i}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[s&&`Status: ${s}`,`URL: ${kf(i)}`,t&&`Request body: ${bt(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=o,this.status=s,this.url=i}},ic=class extends G{constructor({maxSize:t,size:r}){super("HTTP response body exceeded the size limit.",{metaMessages:[`Max: ${t} bytes`,`Received: ${r} bytes`],name:"ResponseBodyTooLargeError"}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t,this.size=r}},_g=class extends G{constructor({body:t,cause:r,details:n,url:o}){super("WebSocket request failed.",{cause:r,details:n,metaMessages:[`URL: ${kf(o)}`,t&&`Request body: ${bt(t)}`].filter(Boolean),name:"WebSocketRequestError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=o}},Rn=class extends G{constructor({body:t,error:r,headers:n,status:o,url:s}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[o&&`Status: ${o}`,`URL: ${kf(s)}`,`Request body: ${bt(t)}`].filter(Boolean),name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.headers=n,this.status=o,this.url=s}},su=class extends G{constructor({url:t}={}){super("The socket has been closed.",{metaMessages:[t&&`URL: ${kf(t)}`].filter(Boolean),name:"SocketClosedError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}},ds=class extends G{constructor({body:t,url:r}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${kf(r)}`,`Request body: ${bt(t)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}});var kUe,Eo,Ao,Yh,Jh,Jc,Qh,Qc,_i,Xh,e0,iu,Aa,Df,t0,Xc,r0,n0,o0,s0,i0,au,a0,c0,l0,u0,d0,cu,f0,ub,Lf=b(()=>{l();nt();fs();kUe=-1,Eo=class extends G{constructor(t,{code:r,docsPath:n,metaMessages:o,name:s,shortMessage:i}){super(i,{cause:t,docsPath:n,metaMessages:o||t?.metaMessages,name:s||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=s||t.name,this.code=t instanceof Rn?t.code:r??kUe}},Ao=class extends Eo{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}},Yh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};Object.defineProperty(Yh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});Jh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};Object.defineProperty(Jh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});Jc=class e extends Eo{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}};Object.defineProperty(Jc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Qh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(` +`)})}};Object.defineProperty(Qh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});Qc=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};Object.defineProperty(Qc,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});_i=class e extends Eo{constructor(t){super(t,{code:e.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(` +`)})}};Object.defineProperty(_i,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});Xh=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(Xh,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});e0=class e extends Eo{constructor(t){super(t,{code:e.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(e0,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});iu=class e extends Eo{constructor(t){super(t,{code:e.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(iu,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});Aa=class e extends Eo{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}};Object.defineProperty(Aa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});Df=class e extends Eo{constructor(t){super(t,{code:e.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty(Df,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});t0=class e extends Eo{constructor(t){super(t,{code:e.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(t0,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Xc=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Xc,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});r0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(r0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});n0=class e extends Ao{constructor(t,{method:r}={}){super(t,{code:e.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}};Object.defineProperty(n0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});o0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(o0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});s0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(s0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});i0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty(i0,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});au=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(au,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});a0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(a0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});c0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(c0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});l0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(l0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});u0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(u0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});d0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(d0,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});cu=class e extends Ao{constructor(t){super(t,{code:e.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(cu,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});f0=class e extends Ao{constructor(t){super(t,{code:e.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(f0,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});ub=class extends Eo{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});function Js(e,{abi:t,address:r,args:n,docsPath:o,functionName:s,sender:i}){let a=e instanceof sc?e:e instanceof G?e.walk(y=>typeof y=="object"&&y!==null&&"data"in y)||e.walk():{},{code:c,data:u,details:d,message:f,shortMessage:p}=a,h=e instanceof Si?new cb({functionName:s,cause:e}):[UUe,Qc.code].includes(c)&&(u||d||f||p)||c===_i.code&&d==="execution reverted"&&u?new Uf({abi:t,data:typeof u=="object"?u.data:u,functionName:s,message:a instanceof Rn?d:p??f,cause:e}):e;return new ab(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:s,sender:i})}var UUe,p0=b(()=>{l();Qr();nt();ou();fs();Lf();UUe=3});function Qre(e){let t=Pt(`0x${e.substring(4)}`).substring(26);return Kc(`0x${t}`)}var Xre=b(()=>{l();Zs();Ks()});function DUe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function fD(e,t,r){return e&t^~e&r}function pD(e,t,r){return e&t^e&r^t&r}var db,Mf,hD=b(()=>{l();Tf();db=class extends $h{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=EI(this.buffer)}update(t){If(this),t=vg(t),eu(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f{l();hD();Tf();LUe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),h0=new Uint32Array(64),kI=class extends db{constructor(t=32){super(64,t,8,!1),this.A=Mf[0]|0,this.B=Mf[1]|0,this.C=Mf[2]|0,this.D=Mf[3]|0,this.E=Mf[4]|0,this.F=Mf[5]|0,this.G=Mf[6]|0,this.H=Mf[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)h0[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=h0[f-15],h=h0[f-2],y=qc(p,7)^qc(p,18)^p>>>3,w=qc(h,17)^qc(h,19)^h>>>10;h0[f]=w+h0[f-7]+y+h0[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=qc(a,6)^qc(a,11)^qc(a,25),h=d+p+fD(a,c,u)+LUe[f]+h0[f]|0,w=(qc(n,2)^qc(n,13)^qc(n,22))+pD(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){ba(h0)}destroy(){this.set(0,0,0,0,0,0,0,0),ba(this.buffer)}},Pg=Ww(()=>new kI)});var UI,gD,ene=b(()=>{l();Tf();UI=class extends $h{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,bre(t);let n=vg(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew UI(e,t).update(r).digest();gD.create=(e,t)=>new UI(e,t)});function fb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function $f(e){if(!fb(e))throw new Error("Uint8Array expected")}function pb(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function H4(e){let t=e.toString(16);return t.length&1?"0"+t:t}function nne(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?xD:BigInt("0x"+e)}function hb(e){if($f(e),one)return e.toHex();let t="";for(let r=0;r=Hf._0&&e<=Hf._9)return e-Hf._0;if(e>=Hf.A&&e<=Hf.F)return e-(Hf.A-10);if(e>=Hf.a&&e<=Hf.f)return e-(Hf.a-10)}function $4(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(one)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oxD;e>>=bD,t+=1);return t}function ine(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=wD(e),o=wD(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=wD(0))=>{o=a(rne([0]),f),n=a(),f.length!==0&&(o=a(rne([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}function zf(e,t,r={}){let n=(o,s,i)=>{let a=HUe[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function AD(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var xD,bD,one,MUe,Hf,yD,Rg,wD,rne,HUe,mb=b(()=>{l();xD=BigInt(0),bD=BigInt(1);one=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",MUe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Hf={_0:48,_9:57,A:65,F:70,a:97,f:102};yD=e=>typeof e=="bigint"&&xD<=e;Rg=e=>(bD<new Uint8Array(e),rne=e=>Uint8Array.from(e);HUe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||fb(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function On(e,t){let r=e%t;return r>=Xs?r:t+r}function Ca(e,t,r){let n=e;for(;t-- >Xs;)n*=n,n%=r;return n}function LI(e,t){if(e===Xs)throw new Error("invert: expected non-zero number");if(t<=Xs)throw new Error("invert: expected positive modulus, got "+t);let r=On(e,t),n=t,o=Xs,s=ps,i=ps,a=Xs;for(;r!==Xs;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ps)throw new Error("invert: does not exist");return On(o,t)}function dne(e,t){let r=(e.ORDER+ps)/cne,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function FUe(e,t){let r=(e.ORDER-lne)/une,n=e.mul(t,Og),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Og),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function zUe(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return dne;let s=o.pow(n,t),i=(t+ps)/Og;return function(c,u){if(c.is0(u))return u;if(ane(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ps<(n[o]="function",n),t);return zf(e,r)}function qUe(e,t,r){if(rXs;)r&ps&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ps;return n}function gb(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function ane(e,t){let r=(e.ORDER-ps)/Og,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function CD(e,t){t!==void 0&&xg(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function F4(e,t,r=!1,n={}){if(e<=Xs)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=CD(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:Rg(o),ZERO:Xs,ONE:ps,create:c=>On(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Xs<=c&&cc===Xs,isOdd:c=>(c&ps)===ps,neg:c=>On(-c,e),eql:(c,u)=>c===u,sqr:c=>On(c*c,e),add:(c,u)=>On(c+u,e),sub:(c,u)=>On(c-u,e),mul:(c,u)=>On(c*u,e),pow:(c,u)=>qUe(a,c,u),div:(c,u)=>On(c*LI(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>LI(c,e),sqrt:n.sqrt||(c=>(i||(i=VUe(e)),i(a,c))),toBytes:c=>r?ED(c,s):lu(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?vD(c):Pi(c)},invertBatch:c=>gb(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function fne(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function SD(e){let t=fne(e);return t+Math.ceil(t/2)}function pne(e,t,r=!1){let n=e.length,o=fne(t),s=SD(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?vD(e):Pi(e),a=On(i,t-ps)+ps;return r?ED(a,o):lu(a,o)}var Xs,ps,Og,$Ue,cne,lne,une,jUe,z4=b(()=>{l();Tf();mb();Xs=BigInt(0),ps=BigInt(1),Og=BigInt(2),$Ue=BigInt(3),cne=BigInt(4),lne=BigInt(5),une=BigInt(8);jUe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function ID(e,t){let r=t.negate();return e?r:t}function gne(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function TD(e,t){gne(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=Rg(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function mne(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=ND);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function WUe(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function KUe(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function PD(e){return yne.get(e)||1}function wne(e,t){return{constTimeNegate:ID,hasPrecomputes(r){return PD(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>hne;)n&ND&&(o=o.add(s)),s=s.double(),n>>=ND;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=TD(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Rg(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{l();z4();mb();hne=BigInt(0),ND=BigInt(1);_D=new WeakMap,yne=new WeakMap});function vne(e){e.lowS!==void 0&&pb("lowS",e.lowS),e.prehash!==void 0&&pb("prehash",e.prehash)}function ZUe(e){let t=RD(e);zf(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function OD(e,t){return hb(lu(e,t))}function GUe(e){let t=ZUe(e),{Fp:r}=t,n=F4(t.n,t.nBitLength),o=t.toBytes||((E,S,_)=>{let O=S.toAffine();return Qs(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,V4),kD),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return Ng(E,Tr,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(fb(E)&&(E=hb(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:Pi(Vn("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=On(M,D)),Ff("private key",M,Tr,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=AD((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=AD(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=gb(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(Vn("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return bne(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,V4),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,V4),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;Ff("scalar",S,el,O);let D=w.ZERO;if(S===el)return D;if(this.is0()||S===Tr)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>el||P>el;)N&Tr&&(R=R.add(B)),P&Tr&&(I=I.add(B)),B=B.double(),N>>=Tr,P>>=Tr;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;Ff("scalar",S,Tr,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===el||P===Tr||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===Tr)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===Tr?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return pb("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return pb("isCompressed",S),hb(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=wne(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function YUe(e){let t=RD(e);return zf(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Ene(e){let t=YUe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return On(C,n)}function u(C){return LI(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=GUe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=Qs;return pb("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=Pi(H);if(!Ng(k,Tr,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&Tr)===Tr;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>Tr;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>Pi(C.slice(A,U));class v{constructor(A,U,H){Ff("r",A,Tr,n),Ff("s",U,Tr,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=Vn("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=Vf.toSig(Vn("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(Vn("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+OD(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return $4(this.toDERHex())}toDERHex(){return Vf.hexFromSig(this)}toCompactRawBytes(){return $4(this.toCompactHex())}toCompactHex(){let A=o;return OD(this.r,A)+OD(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=SD(t.n);return pne(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=Vn("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=Pi(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=Rg(s);function N(C){return Ff("num < 2^"+s,C,el,M),lu(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=Vn("msgHash",C),vne(U),j&&(C=Vn("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(Vn("extraEntropy",ye))}let pe=Qs(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===el)return;let ur=c(Et*c(me+At*te));if(ur===el)return;let _r=(kt.x===At?0:2)|Number(kt.y&Tr),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return ine(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=Vn("msgHash",A),U=Vn("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(vne(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||fb(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof Vf.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}function JUe(e,t){let r=e.ORDER,n=el;for(let y=r-Tr;y%m0===el;y/=m0)n+=Tr;let o=n,s=m0<{let x=f,v=e.pow(w,u),T=e.sqr(v);T=e.mul(T,w);let E=e.mul(y,T);E=e.pow(E,c),E=e.mul(E,v),v=e.mul(E,w),T=e.mul(E,y);let S=e.mul(T,v);E=e.pow(S,d);let _=e.eql(E,e.ONE);v=e.mul(T,p),E=e.mul(S,x),T=e.cmov(v,T,_),S=e.cmov(E,S,_);for(let O=o;O>Tr;O--){let D=O-m0;D=m0<{let T=e.sqr(v),E=e.mul(x,v);T=e.mul(T,E);let S=e.pow(T,y);S=e.mul(S,E);let _=e.mul(S,w),O=e.mul(e.sqr(S),v),D=e.eql(O,x),M=e.cmov(_,S,D);return{isValid:D,value:M}}}return h}function Ane(e,t){if(MI(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");let r=JUe(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let o,s,i,a,c,u,d,f;o=e.sqr(n),o=e.mul(o,t.Z),s=e.sqr(o),s=e.add(s,o),i=e.add(s,e.ONE),i=e.mul(i,t.B),a=e.cmov(t.Z,e.neg(s),!e.eql(s,e.ZERO)),a=e.mul(a,t.A),s=e.sqr(i),u=e.sqr(a),c=e.mul(u,t.A),s=e.add(s,c),s=e.mul(s,i),u=e.mul(u,a),c=e.mul(u,t.B),s=e.add(s,c),d=e.mul(o,i);let{isValid:p,value:h}=r(s,u);f=e.mul(o,n),f=e.mul(f,h),d=e.cmov(d,i,p),f=e.cmov(f,h,p);let y=e.isOdd(n)===e.isOdd(f);f=e.cmov(e.neg(f),f,y);let w=gb(e,[a],!0)[0];return d=e.mul(d,w),{x:d,y:f}}}var BD,Vf,el,Tr,m0,V4,kD,UD=b(()=>{l();xne();z4();mb();BD=class extends Error{constructor(t=""){super(t)}},Vf={Err:BD,_tlv:{encode:(e,t)=>{let{Err:r}=Vf;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=H4(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?H4(o.length/2|128):"";return H4(e)+s+o+t},decode(e,t){let{Err:r}=Vf,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Vf;if(egD(e,t,vre(...r)),randomBytes:AI}}function Cne(e,t){let r=n=>Ene({...e,...QUe(n)});return{...r(t),create:r}}var Sne=b(()=>{l();ene();Tf();UD();});function g0(e,t){if(j4(e),j4(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function eDe(e,t){let r=new Uint8Array(e.length);for(let n=0;n255&&(t=n(Qs(DI("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Qs(t,g0(t.length,1)),c=g0(0,s),u=g0(r,2),d=new Array(i),f=n(Qs(c,e,u,g0(0,1),a));d[0]=n(Qs(f,g0(1,1),a));for(let h=1;h<=i;h++){let y=[eDe(f,d[h-1]),g0(h+1,1),a];d[h]=n(Qs(...y))}return Qs(...d).slice(0,r)}function rDe(e,t,r,n,o){if($f(e),$f(t),j4(r),t.length>255){let s=Math.ceil(2*n/8);t=o.create({dkLen:s}).update(DI("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(g0(r,2)).update(t).update(g0(t.length,1)).digest()}function Ine(e,t,r){zf(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;$f(e),j4(t);let u=typeof c=="string"?DI(c):c,d=n.toString(2).length,f=Math.ceil((d+o)/8),p=t*s*f,h;if(a==="xmd")h=tDe(e,u,p,i);else if(a==="xof")h=rDe(e,u,p,o,i);else if(a==="_internal_pass")h=e;else throw new Error('expand must be "xmd" or "xof"');let y=new Array(t);for(let w=0;wArray.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(f=>f.reduce((p,h)=>e.add(e.mul(p,n),h))),[u,d]=gb(e,[i,c],!0);return n=e.mul(s,u),o=e.mul(o,e.mul(a,d)),{x:n,y:o}}}function _ne(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(s){return e.fromAffine(t(s))}function o(s){let i=s.clearCofactor();return i.equals(e.ZERO)?e.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Ine(s,2,{...r,DST:r.DST,...i}),c=n(a[0]),u=n(a[1]);return o(c.add(u))},encodeToCurve(s,i){let a=Ine(s,1,{...r,DST:r.encodeDST,...i});return o(n(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))}}}var XUe,Pne=b(()=>{l();z4();mb();XUe=Pi});var Dne={};Te(Dne,{encodeToCurve:()=>uDe,hashToCurve:()=>lDe,schnorr:()=>iDe,secp256k1:()=>ei,secp256k1_hasher:()=>zD});function One(e){let t=K4,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=Ca(d,r,t)*d%t,p=Ca(f,r,t)*d%t,h=Ca(p,$I,t)*u%t,y=Ca(h,o,t)*h%t,w=Ca(y,s,t)*y%t,x=Ca(w,a,t)*w%t,v=Ca(x,c,t)*x%t,T=Ca(v,a,t)*w%t,E=Ca(T,r,t)*d%t,S=Ca(E,i,t)*y%t,_=Ca(S,n,t)*u%t,O=Ca(_,$I,t);if(!y0.eql(y0.sqr(O),e))throw new Error("Cannot find square root");return O}function FI(e,...t){let r=Rne[e];if(r===void 0){let n=Pg(Uint8Array.from(e,o=>o.charCodeAt(0)));r=Qs(n,n),Rne[e]=r}return Pg(Qs(r,...t))}function MD(e){let t=ei.utils.normPrivateKeyToScalar(e),r=FD.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:W4(-t),bytes:$D(r)}}function Bne(e){Ff("x",e,q4,K4);let t=DD(e*e),r=DD(t*e+BigInt(7)),n=One(r);n%$I!==HD&&(n=DD(-n));let o=new FD(e,n,q4);return o.assertValidity(),o}function kne(...e){return W4(yb(FI("BIP0340/challenge",...e)))}function oDe(e){return MD(e).bytes}function sDe(e,t,r=AI(32)){let n=Vn("message",e),{bytes:o,scalar:s}=MD(t),i=Vn("auxRand",r,32),a=LD(s^yb(FI("BIP0340/aux",i))),c=FI("BIP0340/nonce",a,o,n),u=W4(yb(c));if(u===HD)throw new Error("sign failed: k is zero");let{bytes:d,scalar:f}=MD(u),p=kne(d,o,n),h=new Uint8Array(64);if(h.set(d,0),h.set(LD(W4(f+p*s)),32),!Une(h,n,o))throw new Error("sign: Invalid signature produced");return h}function Une(e,t,r){let n=Vn("signature",e,64),o=Vn("message",t),s=Vn("publicKey",r,32);try{let i=Bne(yb(s)),a=yb(n.subarray(0,32));if(!Ng(a,q4,K4))return!1;let c=yb(n.subarray(32,64));if(!Ng(c,q4,HI))return!1;let u=kne(LD(a),$D(i),o),d=nDe(i,c,W4(-u));return!(!d||!d.hasEvenY()||d.toAffine().x!==a)}catch{return!1}}var K4,HI,HD,q4,$I,Nne,y0,ei,Rne,$D,LD,DD,W4,FD,nDe,yb,iDe,aDe,cDe,zD,lDe,uDe,Bg=b(()=>{l();mD();Tf();Sne();Pne();z4();mb();UD();K4=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),HI=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),HD=BigInt(0),q4=BigInt(1),$I=BigInt(2),Nne=(e,t)=>(e+t/$I)/t;y0=F4(K4,void 0,void 0,{sqrt:One}),ei=Cne({a:HD,b:BigInt(7),Fp:y0,n:HI,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=HI,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-q4*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Nne(s*e,t),c=Nne(-n*e,t),u=On(e-a*r-c*o,t),d=On(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},Pg),Rne={};$D=e=>e.toRawBytes(!0).slice(1),LD=e=>lu(e,32),DD=e=>On(e,K4),W4=e=>On(e,HI),FD=ei.ProjectivePoint,nDe=(e,t,r)=>FD.BASE.multiplyAndAddUnsafe(e,t,r);yb=Pi;iDe={getPublicKey:oDe,sign:sDe,verify:Une,utils:{randomPrivateKey:ei.utils.randomPrivateKey,lift_x:Bne,pointToBytes:$D,numberToBytesBE:lu,bytesToNumberBE:Pi,taggedHash:FI,mod:On}},aDe=Tne(y0,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),cDe=Ane(y0,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:y0.create(BigInt("-11"))}),zD=_ne(ei.ProjectivePoint,e=>{let{x:t,y:r}=cDe(y0.create(e[0]));return aDe(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:y0.ORDER,m:1,k:128,expand:"xmd",hash:Pg}),lDe=zD.hashToCurve,uDe=zD.encodeToCurve});async function zI({hash:e,signature:t}){let r=We(e)?e:wr(e),{secp256k1:n}=await Promise.resolve().then(()=>(Bg(),Dne));return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){let{r:u,s:d,v:f,yParity:p}=t,h=p===void 0&&f!==void 0&&f>=35n?f%2n===0n?1:0:Lne(Number(p??f));return new n.Signature(dt(u),dt(d)).addRecoveryBit(h)}let i=We(t)?t:wr(t);if(gt(i)!==65)throw new Error("invalid signature length");let a=wt(`0x${i.slice(130)}`),c=Lne(a);return n.Signature.fromCompact(i.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Lne(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}var VD=b(()=>{l();qs();Fo();Xr();qe()});async function ti({hash:e,signature:t}){return Qre(await zI({hash:e,signature:t}))}var w0=b(()=>{l();Xre();VD()});function Vo(e,t="hex"){let r=$ne(e),n=Zc(new Uint8Array(r.length));return r.encode(n),t==="hex"?yt(n.bytes):n.bytes}function Mne(e,t="bytes"){return Vo(e,t)}function Hne(e,t="hex"){return Vo(e,t)}function $ne(e){return Array.isArray(e)?dDe(e.map(t=>$ne(t))):fDe(e)}function dDe(e){let t=e.reduce((o,s)=>o+s.length,0),r=Fne(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function fDe(e){let t=typeof e=="string"?qt(e):e,r=Fne(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function Fne(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new G("Length is too large.")}var wb=b(()=>{l();nt();Jw();Pr();qe()});function zne(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,s=Pt(fr(["0x05",Vo([t?oe(t):"0x",o,r?oe(r):"0x"])]));return n==="bytes"?qt(s):s}var Vne=b(()=>{l();Fn();Pr();qe();wb();Ks()});async function b0(e){let{authorization:t}=e,r=e.signature??t;if(typeof r=="object"&&typeof r.yParity=="number"&&r.yParity!==0&&r.yParity!==1)throw new tu({yParity:BigInt(r.yParity)});return ti({hash:zne(t),signature:r})}var Z4=b(()=>{l();zn();w0();Vne()});var bb,jD=b(()=>{l();M4();Ig();nt();zn();bb=class extends G{constructor(t,{account:r,docsPath:n,chain:o,data:s,gas:i,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:u,nonce:d,to:f,value:p}){let h=Tg({from:r?.address,to:f,value:typeof p<"u"&&`${qh(p)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:s,gas:i,gasPrice:typeof a<"u"&&`${Pn(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${Pn(c)} gwei`,maxPriorityFeePerGas:typeof u<"u"&&`${Pn(u)} gwei`,nonce:d});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",h].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}});var ri,Ni,x0,v0,E0,A0,C0,S0,I0,T0,ac,Ri,tl=b(()=>{l();Ig();nt();ri=class extends G{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};Object.defineProperty(ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ri,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});Ni=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(Ni,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});x0=class extends G{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};Object.defineProperty(x0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});v0=class extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};Object.defineProperty(v0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});E0=class extends G{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(` `),{cause:t,name:"NonceTooLowError"})}};Object.defineProperty(E0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});A0=class extends G{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}};Object.defineProperty(A0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});C0=class extends G{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(` `),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(C0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance|outoffunds/});S0=class extends G{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(S0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});I0=class extends G{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(I0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});T0=class extends G{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(T0,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});ac=class extends G{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${typeof r=="bigint"?` = ${Pn(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${typeof n=="bigint"?` = ${Pn(n)} gwei`:""}).`].join(` -`),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(ac,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Ni=class extends G{constructor({cause:t}){super(`An error occurred while executing: ${t?.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}});function _0(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof G?e.walk(o=>o?.code===ri.code):e;return n instanceof G?new ri({cause:e,message:n.details}):ri.nodeMessage.test(r)?new ri({cause:e,message:e.details}):Pi.nodeMessage.test(r)?new Pi({cause:e,maxFeePerGas:t?.maxFeePerGas}):x0.nodeMessage.test(r)?new x0({cause:e,maxFeePerGas:t?.maxFeePerGas}):v0.nodeMessage.test(r)?new v0({cause:e,nonce:t?.nonce}):E0.nodeMessage.test(r)?new E0({cause:e,nonce:t?.nonce}):A0.nodeMessage.test(r)?new A0({cause:e,nonce:t?.nonce}):C0.nodeMessage.test(r)?new C0({cause:e}):S0.nodeMessage.test(r)?new S0({cause:e,gas:t?.gas}):I0.nodeMessage.test(r)?new I0({cause:e,gas:t?.gas}):T0.nodeMessage.test(r)?new T0({cause:e}):ac.nodeMessage.test(r)?new ac({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new Ni({cause:e})}var G4=b(()=>{l();nt();tl()});function jne(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ni?e:o})();return new bb(n,{docsPath:t,...r})}var qne=b(()=>{l();jD();tl();G4()});function Ri(e,{format:t}){if(!t)return{};let r={};function n(s){let i=Object.keys(s);for(let a of i)a in e&&(r[a]=e[a]),s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&n(s[a])}let o=t(e||{});return n(o),r}var P0=b(()=>{l()});function N0(e,t){return({exclude:r,format:n})=>({exclude:r,format:(o,s)=>{let i=t(o,s);if(r)for(let a of r)delete i[a];return{...i,...n(o,s)}},type:e})}var Y4=b(()=>{l()});function Bn(e,t){let r={};return typeof e.authorizationList<"u"&&(r.authorizationList=pDe(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>yt(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=oe(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=oe(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=oe(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=oe(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=oe(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=oe(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=qD[e.type]),typeof e.value<"u"&&(r.value=oe(e.value)),r}function pDe(e){return e.map(t=>({address:t.address,r:t.r?oe(BigInt(t.r)):t.r,s:t.s?oe(BigInt(t.s)):t.s,chainId:oe(t.chainId),nonce:oe(t.nonce),...typeof t.yParity<"u"?{yParity:oe(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:oe(t.v)}:{}}))}var qD,Wne,rl=b(()=>{l();qe();Y4();qD={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};Wne=N0("transactionRequest",Bn)});function Kne(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new A4({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new A4({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function hDe(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:s}=e,i={};if(s!==void 0&&(i.code=s),t!==void 0&&(i.balance=oe(t)),r!==void 0&&(i.nonce=oe(r)),n!==void 0&&(i.state=Kne(n)),o!==void 0){if(i.state)throw new rb;i.stateDiff=Kne(o)}return i}function xb(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!Ft(r,{strict:!1}))throw new br({address:r});if(t[r])throw new tb({address:r});t[r]=hDe(n)}return t}var VI=b(()=>{l();tc();C4();OI();Gs();qe()});var Zne,Gne,Yne,Jne,Qne,Xne,eoe,toe,roe,noe,ooe,soe,ioe,aoe,coe,loe,uoe,doe,foe,poe,hoe,moe,goe,yoe,woe,boe,xoe,voe,Eoe,Aoe,Coe,Soe,Ioe,Toe,_oe,Poe,Noe,Roe,Ooe,Boe,koe,Uoe,Doe,Loe,Moe,Hoe,$oe,Foe,zoe,Voe,joe,qoe,Woe,Koe,Zoe,Goe,Yoe,Joe,Qoe,Xoe,ese,tse,rse,nse,ose,sse,ise,ase,cse,lse,use,dse,fse,pse,hse,mse,gse,yse,wse,bse,xse,vse,Ese,Ase,Cse,Sse,Ise,Tse,_se,Pse,Nse,Rse,Ose,Bse,kse,R0,jI=b(()=>{l();Zne=2n**(8n-1n)-1n,Gne=2n**(16n-1n)-1n,Yne=2n**(24n-1n)-1n,Jne=2n**(32n-1n)-1n,Qne=2n**(40n-1n)-1n,Xne=2n**(48n-1n)-1n,eoe=2n**(56n-1n)-1n,toe=2n**(64n-1n)-1n,roe=2n**(72n-1n)-1n,noe=2n**(80n-1n)-1n,ooe=2n**(88n-1n)-1n,soe=2n**(96n-1n)-1n,ioe=2n**(104n-1n)-1n,aoe=2n**(112n-1n)-1n,coe=2n**(120n-1n)-1n,loe=2n**(128n-1n)-1n,uoe=2n**(136n-1n)-1n,doe=2n**(144n-1n)-1n,foe=2n**(152n-1n)-1n,poe=2n**(160n-1n)-1n,hoe=2n**(168n-1n)-1n,moe=2n**(176n-1n)-1n,goe=2n**(184n-1n)-1n,yoe=2n**(192n-1n)-1n,woe=2n**(200n-1n)-1n,boe=2n**(208n-1n)-1n,xoe=2n**(216n-1n)-1n,voe=2n**(224n-1n)-1n,Eoe=2n**(232n-1n)-1n,Aoe=2n**(240n-1n)-1n,Coe=2n**(248n-1n)-1n,Soe=2n**(256n-1n)-1n,Ioe=-(2n**(8n-1n)),Toe=-(2n**(16n-1n)),_oe=-(2n**(24n-1n)),Poe=-(2n**(32n-1n)),Noe=-(2n**(40n-1n)),Roe=-(2n**(48n-1n)),Ooe=-(2n**(56n-1n)),Boe=-(2n**(64n-1n)),koe=-(2n**(72n-1n)),Uoe=-(2n**(80n-1n)),Doe=-(2n**(88n-1n)),Loe=-(2n**(96n-1n)),Moe=-(2n**(104n-1n)),Hoe=-(2n**(112n-1n)),$oe=-(2n**(120n-1n)),Foe=-(2n**(128n-1n)),zoe=-(2n**(136n-1n)),Voe=-(2n**(144n-1n)),joe=-(2n**(152n-1n)),qoe=-(2n**(160n-1n)),Woe=-(2n**(168n-1n)),Koe=-(2n**(176n-1n)),Zoe=-(2n**(184n-1n)),Goe=-(2n**(192n-1n)),Yoe=-(2n**(200n-1n)),Joe=-(2n**(208n-1n)),Qoe=-(2n**(216n-1n)),Xoe=-(2n**(224n-1n)),ese=-(2n**(232n-1n)),tse=-(2n**(240n-1n)),rse=-(2n**(248n-1n)),nse=-(2n**(256n-1n)),ose=2n**8n-1n,sse=2n**16n-1n,ise=2n**24n-1n,ase=2n**32n-1n,cse=2n**40n-1n,lse=2n**48n-1n,use=2n**56n-1n,dse=2n**64n-1n,fse=2n**72n-1n,pse=2n**80n-1n,hse=2n**88n-1n,mse=2n**96n-1n,gse=2n**104n-1n,yse=2n**112n-1n,wse=2n**120n-1n,bse=2n**128n-1n,xse=2n**136n-1n,vse=2n**144n-1n,Ese=2n**152n-1n,Ase=2n**160n-1n,Cse=2n**168n-1n,Sse=2n**176n-1n,Ise=2n**184n-1n,Tse=2n**192n-1n,_se=2n**200n-1n,Pse=2n**208n-1n,Nse=2n**216n-1n,Rse=2n**224n-1n,Ose=2n**232n-1n,Bse=2n**240n-1n,kse=2n**248n-1n,R0=2n**256n-1n});function jn(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,s=t?ft(t):void 0;if(s&&!Ft(s.address))throw new br({address:s.address});if(o&&!Ft(o))throw new br({address:o});if(r&&r>R0)throw new Pi({maxFeePerGas:r});if(typeof n=="bigint"&&typeof r=="bigint"&&n>r)throw new ac({maxFeePerGas:r,maxPriorityFeePerGas:n})}var nl=b(()=>{l();tn();jI();tc();tl();Gs()});var O0,uu,vb,Eb=b(()=>{l();Ig();nt();O0=class extends G{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}},uu=class extends G{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}},vb=class extends G{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Pn(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}});var du,J4=b(()=>{l();nt();du=class extends G{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}});function jf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?wt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?wt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Q4[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=mDe(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}function mDe(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var Q4,Use,Ab=b(()=>{l();Xr();Y4();Q4={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};Use=N0("transaction",jf)});function qf(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:jf(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}var Dse,X4=b(()=>{l();Y4();Ab();Dse=N0("block",qf)});async function xn(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let s=o??!1,i=r!==void 0?oe(r):void 0,a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,s]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[i||n,s]},{dedupe:!!i}),!a)throw new du({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||qf)(a,"getBlock")}var fu=b(()=>{l();J4();qe();X4()});async function Cb(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}var qI=b(()=>{l()});async function Lse(e,t){return WD(e,t)}async function WD(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let s=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof s=="function"){let a=r||await ue(e,xn,"getBlock")({}),c=await s({block:a,client:e,request:o});if(c===null)throw new Error;return c}if(typeof s<"u")return s;let i=await e.request({method:"eth_maxPriorityFeePerGas"});return dt(i)}catch{let[s,i]=await Promise.all([r?Promise.resolve(r):ue(e,xn,"getBlock")({}),ue(e,Cb,"getGasPrice")({})]);if(typeof s.baseFeePerGas!="bigint")throw new uu;let a=i-s.baseFeePerGas;return a<0n?0n:a}}var KD=b(()=>{l();Eb();Xr();_t();fu();qI()});async function Mse(e,t){return WI(e,t)}async function WI(e,t){let{block:r,chain:n=e.chain,request:o,type:s="eip1559"}=t||{},i=await(async()=>typeof n?.fees?.baseFeeMultiplier=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:o}):n?.fees?.baseFeeMultiplier??1.2)();if(i<1)throw new O0;let c=10**(i.toString().split(".")[1]?.length??0),u=p=>p*BigInt(Math.round(i*c))/BigInt(c),d=r||await ue(e,xn,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas=="function"){let p=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:o,type:s});if(p!==null)return p}if(s==="eip1559"){if(typeof d.baseFeePerGas!="bigint")throw new uu;let p=typeof o?.maxPriorityFeePerGas=="bigint"?o.maxPriorityFeePerGas:await WD(e,{block:d,chain:n,request:o}),h=u(d.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+p,maxPriorityFeePerGas:p}}return{gasPrice:o?.gasPrice??u(await ue(e,Cb,"getGasPrice")({}))}}var ZD=b(()=>{l();Eb();_t();KD();fu();qI()});function ni(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new G("`requireCanonical` can only be provided when `blockHash` is set.");return t?o?{blockHash:t,requireCanonical:o}:{blockHash:t}:typeof r=="bigint"?oe(r):n??"latest"}var B0=b(()=>{l();nt();qe()});async function k0(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),a=await e.request({method:"eth_getTransactionCount",params:[t,i]},{dedupe:typeof n=="bigint"||r!==void 0});return wt(a)}var e3=b(()=>{l();B0();Xr()});var Wf,U0,Sb,kg,Kf,Ug=b(()=>{l();nt();Wf=class extends G{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}},U0=class extends G{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} \u2013 ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} \u2013 ${t.name}`],name:"ChainMismatchError"})}},Sb=class extends G{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(` -`),{name:"ChainNotFoundError"})}},kg=class extends G{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}},Kf=class extends G{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}});function D0(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>qt(s)):e.blobs,o=[];for(let s of n)o.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?o:o.map(s=>yt(s))}var t3=b(()=>{l();Pr();qe()});function L0(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>qt(i)):e.blobs,o=typeof e.commitments[0]=="string"?e.commitments.map(i=>qt(i)):e.commitments,s=[];for(let i=0;iyt(i))}var r3=b(()=>{l();Pr();qe()});var Hse,$se=b(()=>{l();mD();Hse=Pg});function KI(e,t){let r=t||"hex",n=Hse(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var GD=b(()=>{l();$se();qs();Pr();qe()});function Ib(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),o=KI(t,"bytes");return o.set([r],0),n==="bytes"?o:yt(o)}var ZI=b(()=>{l();qe();GD()});function Tb(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),o=[];for(let s of t)o.push(Ib({commitment:s,to:n,version:r}));return o}var GI=b(()=>{l();ZI()});var YI,_b,JI,QI,YD=b(()=>{l();nt();YI=class extends G{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}},_b=class extends G{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}},JI=class extends G{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}},QI=class extends G{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}});function XI(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?qt(e.data):e.data,n=gt(r);if(!n)throw new _b;if(n>761855)throw new YI({maxSize:761855,size:n});let o=[],s=!0,i=0;for(;s;){let a=Zc(new Uint8Array(131072)),c=0;for(;c<4096;){let u=r.slice(i,i+31);if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),s=!1;break}c++,i+=31}o.push(a)}return t==="bytes"?o.map(a=>a.bytes):o.map(a=>yt(a.bytes))}var JD=b(()=>{l();YD();Jw();Fo();Pr();qe()});function M0(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??XI({data:t,to:n}),s=e.commitments??D0({blobs:o,kzg:r,to:n}),i=e.proofs??L0({blobs:o,commitments:s,kzg:r,to:n}),a=[];for(let c=0;c{l();t3();r3();JD()});function Pb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new nb({transaction:e})}var e9=b(()=>{l();zn()});function H0(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ni?e:o})();return new ib(n,{docsPath:t,...r})}var o3=b(()=>{l();tl();zn();G4()});async function hs(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return wt(t)}var Zf=b(()=>{l();Xr()});async function Nb(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:s=e.chain,blobVersionedHashes:i,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,nonceManager:w,to:x,type:v,value:T,...E}=t,S=await(async()=>{if(!r||!w||typeof y<"u")return y;let M=ft(r),N=s?s.id:await ue(e,hs,"getChainId")({});return await w.consume({address:M.address,chainId:N,client:e})})();jn(t);let _=s?.formatters?.transactionRequest?.format,D=(_||Bn)({...Ri(E,{format:_}),account:r?ft(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:i,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:S,to:x,type:v,value:T},"fillTransaction");try{let M=await e.request({method:"eth_fillTransaction",params:[D]}),L=(s?.formatters?.transaction?.format||jf)(M.tx);delete L.blockHash,delete L.blockNumber,delete L.r,delete L.s,delete L.transactionIndex,delete L.v,delete L.yParity,typeof L.maxFeePerGas<"u"&&delete L.gasPrice,L.data=L.input;let P=typeof L.feePayerSignature<"u"&&L.feePayerSignature!==null;if(P&&typeof S<"u"&&BigInt(L.nonce)!==BigInt(S))throw new Wh({filledNonce:L.nonce,requestedNonce:S});if(!P){L.gas&&(L.gas=t.gas??L.gas),L.gasPrice&&(L.gasPrice=t.gasPrice??L.gasPrice),L.maxFeePerBlobGas&&(L.maxFeePerBlobGas=t.maxFeePerBlobGas??L.maxFeePerBlobGas),L.maxFeePerGas&&(L.maxFeePerGas=t.maxFeePerGas??L.maxFeePerGas),L.maxPriorityFeePerGas&&(L.maxPriorityFeePerGas=t.maxPriorityFeePerGas??L.maxPriorityFeePerGas),typeof L.nonce<"u"&&typeof t.nonce<"u"&&(L.nonce=typeof L.nonce=="bigint"?BigInt(t.nonce):t.nonce);let R=await(async()=>{if(typeof s?.fees?.baseFeeMultiplier=="function"){let A=await ue(e,xn,"getBlock")({});return s.fees.baseFeeMultiplier({block:A,client:e,request:t})}return s?.fees?.baseFeeMultiplier??1.2})();if(R<1)throw new O0;let B=10**(R.toString().split(".")[1]?.length??0),C=A=>A*BigInt(Math.round(R*B))/BigInt(B);L.maxFeePerGas&&!t.maxFeePerGas&&(L.maxFeePerGas=C(L.maxFeePerGas)),L.gasPrice&&!t.gasPrice&&(L.gasPrice=C(L.gasPrice))}return{raw:M.raw,transaction:{from:D.from,...L},...M.capabilities?{capabilities:M.capabilities}:{}}}catch(M){throw H0(M,{...t,chain:e.chain})}}var t9=b(()=>{l();tn();Eb();zn();o3();P0();Ab();rl();_t();nl();fu();Zf()});async function pu(e,t){let r={...t};typeof r.account>"u"&&(r.account=e.account),r.parameters??=s3;let{account:n,chain:o=e.chain,nonceManager:s,parameters:i}=r,a=(()=>{if(typeof o?.prepareTransactionRequest=="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt}})(),c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:o?o.id:(c=await ue(e,hs,"getChainId")({}),c))}let d=n&&ft(n),f=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"})??r,f??=r.nonce;let D=r.account??r.from;d=D?ft(D):void 0}if(i.includes("nonce")&&typeof f>"u"&&d&&s){let D=await u();f=await s.consume({address:d.address,chainId:D,client:e})}let p=(i.includes("blobVersionedHashes")||i.includes("sidecars"))&&r.kzg&&r.blobs?!1:i.length>0&&"feePayer"in r&&r.feePayer&&!("feePayerSignature"in r&&r.feePayerSignature)?!0:QD.get(e.uid)===!1||!["fees","gas"].some(M=>i.includes(M))?!1:!!(i.includes("chainId")&&typeof r.chainId!="number"||i.includes("nonce")&&typeof f!="number"||i.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||i.includes("gas")&&typeof r.gas!="bigint"),h,y=D=>ue(e,Nb,"fillTransaction")({...D,nonce:f}).then(M=>{let{chainId:N,from:L,gas:P,gasPrice:R,nonce:I,maxFeePerBlobGas:B,maxFeePerGas:C,maxPriorityFeePerGas:A,type:U,...H}=M.transaction,k="feeToken"in H?H.feeToken:void 0,F="feePayerSignature"in H&&H.feePayerSignature!==null&&typeof H.feePayerSignature<"u",j=typeof k<"u"&&k!==null&&(!("feeToken"in D)||F);QD.set(e.uid,!0),h=N;let{feeToken:W,...ae}=D;return{...F?ae:D,...L?{from:L}:{},...U&&!D.type?{type:U}:{},...typeof P<"u"?{gas:P}:{},...typeof R<"u"?{gasPrice:R}:{},...typeof I<"u"?{nonce:I}:{},...typeof B<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxFeePerBlobGas:B}:{},...typeof C<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxFeePerGas:C}:{},...typeof A<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxPriorityFeePerGas:A}:{},..."nonceKey"in H&&typeof H.nonceKey<"u"?{nonceKey:H.nonceKey}:{},..."validBefore"in H&&H.validBefore!==null&&typeof H.validBefore<"u"?{validBefore:H.validBefore}:{},..."validAfter"in H&&H.validAfter!==null&&typeof H.validAfter<"u"?{validAfter:H.validAfter}:{},..."keyAuthorization"in H&&typeof H.keyAuthorization<"u"&&H.keyAuthorization!==null&&!("keyAuthorization"in D)?{keyAuthorization:H.keyAuthorization}:{},..."feePayerSignature"in H&&typeof H.feePayerSignature<"u"&&H.feePayerSignature!==null?{feePayerSignature:H.feePayerSignature}:{},...j?{feeToken:k}:{},...M.capabilities?{_capabilities:M.capabilities}:{}}}),w=(D,M)=>{let N=D;if(N.name!=="TransactionExecutionError")return M;if(N.walk?.(I=>I instanceof Wh)||N.walk?.(I=>I.name==="ExecutionRevertedError"))throw D;return N.walk?.(I=>{let B=I;return B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"||B.message?.includes("eth_fillTransaction is not available")})&&QD.set(e.uid,!1),M},x=p?await y(r).catch(async D=>{let M=a?.fn&&a.runAt?.includes("afterFillTransactionError")?await a.fn({...r,chain:o},{client:e,error:D,phase:"afterFillTransactionError"}):void 0;return M?y(M).catch(N=>w(N,M)):w(D,r)}):r;if(f??=x.nonce,r={...x,...d?{from:d?.address}:{},...typeof f<"u"?{nonce:f}:{}},typeof h<"u"&&(r.chainId??=o?.id??h,r.chainId!==h))throw new U0({chain:o?.id===r.chainId?o:{id:r.chainId,name:"Unknown"},currentChainId:h});let{blobs:v,gas:T,kzg:E,type:S}=r;a?.fn&&a.runAt?.includes("beforeFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"})??r);let _;async function O(){return _||(_=await ue(e,xn,"getBlock")({blockTag:"latest"}),_)}if(i.includes("nonce")&&typeof f>"u"&&d&&!s&&(r.nonce=await ue(e,k0,"getTransactionCount")({address:d.address,blockTag:"pending"})),(i.includes("blobVersionedHashes")||i.includes("sidecars"))&&v&&E){let D=D0({blobs:v,kzg:E});if(i.includes("blobVersionedHashes")){let M=Tb({commitments:D,to:"hex"});r.blobVersionedHashes=M}if(i.includes("sidecars")){let M=L0({blobs:v,commitments:D,kzg:E}),N=M0({blobs:v,commitments:D,proofs:M,to:"hex"});r.sidecars=N}}if(i.includes("chainId")&&(r.chainId=await u()),(i.includes("fees")||i.includes("type"))&&typeof S>"u")try{r.type=Pb(r)}catch{let D=Fse.get(e.uid);typeof D>"u"&&(D=typeof(await O())?.baseFeePerGas=="bigint",Fse.set(e.uid,D)),r.type=D?"eip1559":"legacy"}if(i.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let D=await O(),{maxFeePerGas:M,maxPriorityFeePerGas:N}=await WI(e,{block:D,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&typeof r.maxFeePerGas=="bigint"&&r.maxFeePerGas"u"){let D=await O(),{gasPrice:M}=await WI(e,{block:D,chain:o,request:r,type:"legacy"});r.gasPrice=M}}return i.includes("gas")&&typeof T>"u"&&(r.gas=await ue(e,Ob,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"})??r),jn(r),delete r.parameters,r}var s3,Fse,QD,Rb=b(()=>{l();tn();ZD();r9();fu();e3();Ug();Eb();zn();t3();r3();GI();n3();_t();_f();nl();e9();t9();Zf();s3=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Fse=new Map,QD=new xo(128)});async function Ob(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ft(r):void 0,s=t.stateOverride!==void 0||typeof t.blockNumber=="bigint"||t.blockTag!==void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local"||s)return["blobVersionedHashes"]})();try{let a=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await b0({authorization:t.authorizationList[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:c,authorizationList:u,blobs:d,blobVersionedHashes:f,blockNumber:p,blockTag:h,data:y,gas:w,gasPrice:x,maxFeePerBlobGas:v,maxFeePerGas:T,maxPriorityFeePerGas:E,nonce:S,value:_,stateOverride:O,...D}=n?await pu(e,{...t,parameters:i,to:a}):t;if(w&&t.gas!==w&&!s)return w;let N=(typeof p=="bigint"?oe(p):void 0)||h,L=xb(O);jn(t);let P=e.chain?.formatters?.transactionRequest?.format,I=(P||Bn)({...Ri(D,{format:P}),account:o,accessList:c,authorizationList:u,blobs:d,blobVersionedHashes:f,data:y,gasPrice:x,maxFeePerBlobGas:v,maxFeePerGas:T,maxPriorityFeePerGas:E,nonce:S,to:a,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:L?[I,N??e.experimental_blockTag??"latest",L]:N?[I,N]:[I]}))}catch(a){throw jne(a,{...t,account:o,chain:e.chain})}}var r9=b(()=>{l();tn();nt();Z4();qe();qne();P0();rl();VI();nl();Rb()});async function $0(e,t){let{abi:r,address:n,args:o,functionName:s,dataSuffix:i=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Wt({abi:r,args:o,functionName:s});try{return await ue(e,Ob,"estimateGas")({data:`${c}${i?i.replace("0x",""):""}`,to:n,...a})}catch(u){let d=a.account?ft(a.account):void 0;throw Js(u,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:d?.address})}}var i3=b(()=>{l();tn();us();p0();_t();r9()});function xr(e,t){if(!Ft(e,{strict:!1}))throw new br({address:e});if(!Ft(t,{strict:!1}))throw new br({address:t});return e.toLowerCase()===t.toLowerCase()}var Oi=b(()=>{l();tc();Gs()});function qn(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var hu=b(()=>{l()});function Yf(e){let{abi:t,data:r,eventName:n,strict:o,topics:s}=e,i=o??!0,a=t.filter(p=>p.type==="event"&&"name"in p),c=s[0],u=c?a.find(p=>!p.anonymous&&c===Wc(no(p))):void 0,d=u?[u]:wDe(a,s.length,n);if(d.length>1)throw new Gf(d.map(p=>p.name));let f=d[0];if(!f)throw c?new Jl(c,{docsPath:XD}):new Yl({docsPath:XD});return xDe({abiItem:f,argTopics:f.anonymous?s:s.slice(1),data:r,strict:i})}function wDe(e,t,r){return(r?e.filter(o=>o.name===r):e.every(o=>o.anonymous)?e:[]).filter(o=>o.anonymous&&bDe(o)===t)}function bDe(e){return e.inputs?.filter(t=>t.indexed).length??0}function xDe({abiItem:e,argTopics:t,data:r,strict:n}){let{name:o,inputs:s}=e,i=s?.some(p=>!("name"in p&&p.name)),a=i?[]:{},c=s.map((p,h)=>[p,h]).filter(([p])=>"indexed"in p&&p.indexed),u=[];for(let p=0;p!("indexed"in p&&p.indexed)),f=n?d:[...u.map(([p])=>p),...d];if(f.length>0){if(r&&r!=="0x")try{let p=Ys(f,r);if(p){let h=0;if(!n)for(let[y,w]of u)a[i?w:y.name||w]=p[h++];if(i)for(let y=0;y0?a:void 0}}function vDe({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Ys([e],t)||[])[0]}var XD,Gf,a3=b(()=>{l();Qr();nt();aD();Fo();Kw();zh();Cf();XD="/docs/contract/decodeEventLog";Gf=class extends G{constructor(t){let r=new Set(t).size===t.length;super("Ambiguous anonymous event log.",{docsPath:XD,metaMessages:[`Matched ${t.map(n=>`\`${n}\``).join(", ")}.`,"These events take the same number of indexed topics.",r?"Pass `eventName` to choose one.":"Pass an `abi` that holds only the event to decode."],name:"AbiEventAmbiguityError"})}}});function cc(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),i=t.filter(c=>c.type==="event").map(c=>({abi:c,selector:Wc(c)})),a=s?i.filter(c=>c.abi.anonymous&&s.includes(c.abi.name)):i.every(c=>c.abi.anonymous)?i:[];return n.map(c=>{let u=typeof c.blockNumber=="string"?qn(c):c,d=i.filter(y=>!y.abi.anonymous&&u.topics[0]===y.selector),f=(()=>{if(d.length>0)return s?d.filter(w=>s.includes(w.abi.name)):d;let y=a.filter(w=>(w.abi.inputs?.filter(x=>x.indexed).length??0)===u.topics.length);return y.length===1?y:[]})();if(f.length===0)return null;let p,h;for(let y of f)try{p=Yf({...u,abi:[y.abi],strict:!0}),h=y;break}catch{}if(!p&&!o){let y=f[0];if(!y||y.abi.anonymous)return null;h=y;try{p=Yf({data:u.data,topics:u.topics,abi:[h.abi],strict:!1})}catch{let w=h.abi.inputs?.some(x=>!("name"in x&&x.name));p={eventName:h.abi.name,args:w?[]:{}}}}return!p||!h||s&&!s.includes(p.eventName)||!EDe({anonymous:h.abi.anonymous,args:p.args,inputs:h.abi.inputs,matchArgs:r,topics:u.topics})?null:{...p,...u}}).filter(Boolean)}function EDe(e){let{anonymous:t,args:r,inputs:n,matchArgs:o,topics:s}=e;if(!o)return!0;if(!r)return!1;let i=n.filter(c=>c.indexed).slice(0,t?s.length:s.length-1);function a(c,u,d){try{if(c.type==="address")return xr(u,d);if(i.includes(c)&&(c.type==="string"||c.type==="bytes")){let f=c.type==="string"?zo(u):un(u);return Pt(f)===d}return typeof u=="string"&&typeof d=="string"&&Eg.test(c.type)?u.toLowerCase()===d.toLowerCase():Rf.test(c.type)&&(typeof u=="number"||typeof u=="bigint")&&(typeof d=="number"||typeof d=="bigint")?BigInt(u)===BigInt(d):u===d}catch{return!1}}return Array.isArray(r)&&Array.isArray(o)?o.every((c,u)=>{if(c==null)return!0;let d=n[u];return d?(Array.isArray(c)?c:[c]).some(p=>a(d,p,r[u])):!1}):typeof r=="object"&&!Array.isArray(r)&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).every(([c,u])=>{if(u==null)return!0;let d=n.find(p=>p.name===c);return d?(Array.isArray(u)?u:[u]).some(p=>a(d,p,r[c])):!1}):!1}var Dg=b(()=>{l();Oi();Pr();hu();Ks();Kw();P4();a3()});function Bb(e){if(!(e instanceof G))return!0;let t=e.walk(r=>r instanceof Nr||r instanceof Rn);return t?t instanceof Rn&&t.code===429||t instanceof Nr&&t.status===void 0?!1:t.status!==401&&t.status!==403&&t.status!==429:!0}var n9=b(()=>{l();nt();fs()});async function*o9(e,t){let{address:r,args:n,blockRange:o=1000n,event:s,events:i,fromBlock:a,strict:c,toBlock:u="latest"}=t;if(o<1n)throw new G("`blockRange` must be at least 1n.");let d=typeof u=="bigint"?u:(await ue(e,xn,"getBlock")({blockTag:u})).number,f=o,p=a;for(;p<=d;){let h=p+f-1n,y=h{if(p===y||!Bb(x))throw x});if(!w){f=(y-p+1n)/2n;continue}yield{endBlock:d,fromBlock:p,logs:w,toBlock:y},p=y+1n,f=f*2n{l();nt();_t();fu();c3();n9()});async function F0(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:s,events:i,args:a,blockRange:c,strict:u}={}){if(c!==void 0){let w=[];for await(let x of o9(e,{address:t,args:a,blockRange:c,event:s,events:i,fromBlock:n,strict:u,toBlock:o}))for(let v of x.logs)w.push(v);return w}let d=u??!1,f=i??(s?[s]:void 0),p=[];f&&(p=[f.flatMap(x=>nc({abi:[x],eventName:x.name,args:i?void 0:a}))],s&&(p=p[0]));let h;r?h=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]}):h=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n=="bigint"?oe(n):n,toBlock:typeof o=="bigint"?oe(o):o}]});let y=h.map(w=>qn(w));return f?cc({abi:f,args:a,logs:y,strict:d}):y}var c3=b(()=>{l();Cg();Dg();qe();hu();eL()});async function kb(e,t){let{abi:r,address:n,args:o,blockHash:s,eventName:i,fromBlock:a,toBlock:c,strict:u}=t,d=i?ls({abi:r,name:i}):void 0,f=d?void 0:r.filter(p=>p.type==="event");return ue(e,F0,"getLogs")({address:n,args:o,blockHash:s,event:d,events:f,fromBlock:a,toBlock:c,strict:u})}var s9=b(()=>{l();Bf();_t();c3()});function dn(e){let{abi:t,args:r,functionName:n,data:o}=e,s=t[0];if(n){let a=ls({abi:t,args:r,name:n});if(!a)throw new wa(n,{docsPath:tL});s=a}if(s.type!=="function")throw new wa(void 0,{docsPath:tL});if(!s.outputs)throw new Dh(s.name,{docsPath:tL});let i=Ys(s.outputs,o);if(i&&i.length>1)return i;if(i&&i.length===1)return i[0]}var tL,lc=b(()=>{l();Qr();zh();Bf();tL="/docs/contract/decodeFunctionResult"});var zse,Vse=b(()=>{l();zse="0.1.1"});function jse(){return zse}var qse=b(()=>{l();Vse()});function Wse(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?Wse(e.cause,t):t?null:e}var Ke,Bi=b(()=>{l();qse();Ke=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=r.docsOrigin??e.prototype.docsOrigin,i=`${s}${o??""}`,a=!!(r.version??e.prototype.showVersion),c=r.version??e.prototype.version,u=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o||a?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(d=>typeof d=="string").join(` -`);super(u,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=i,this.docsOrigin=s,this.docsPath=o,this.shortMessage=t,this.showVersion=a,this.version=c}walk(t){return Wse(this,t)}};Object.defineProperty(Ke,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${jse()}`}});Ke.setStaticOptions(Ke.defaultStaticOptions)});function Ub(e,t){if(uc(e)>t)throw new i9({givenSize:uc(e),maxSize:t})}function Kse(e,t){if(typeof t=="number"&&t>0&&t>uc(e)-1)throw new l3({offset:t,position:"start",size:uc(e)})}function Zse(e,t,r){if(typeof t=="number"&&typeof r=="number"&&uc(e)!==r-t)throw new l3({offset:r,position:"end",size:uc(e)})}function rL(e){if(e>=Jf.zero&&e<=Jf.nine)return e-Jf.zero;if(e>=Jf.A&&e<=Jf.F)return e-(Jf.A-10);if(e>=Jf.a&&e<=Jf.f)return e-(Jf.a-10)}function Gse(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new a9({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;s{l();mu();Jf={zero:48,nine:57,A:65,F:70,a:97,f:102}});function Db(e,t){if(Mr(e)>t)throw new c9({givenSize:Mr(e),maxSize:t})}function Jse(e,t){if(typeof t=="number"&&t>0&&t>Mr(e)-1)throw new u3({offset:t,position:"start",size:Mr(e)})}function Qse(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Mr(e)!==r-t)throw new u3({offset:r,position:"end",size:Mr(e)})}function oL(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new l9({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function Xse(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;s{l();io()});function z0(e,t,r){return JSON.stringify(e,(n,o)=>typeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+CDe:o,r)}var CDe,d3=b(()=>{l();CDe="#__bigint"});function TDe(e){if(!(e instanceof Uint8Array)){if(!e)throw new Lb(e);if(typeof e!="object")throw new Lb(e);if(!("BYTES_PER_ELEMENT"in e))throw new Lb(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new Lb(e)}}function aL(e){return e instanceof Uint8Array?e:typeof e=="string"?Lg(e):_De(e)}function _De(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Lg(e,t={}){let{size:r}=t,n=e.slice(2);n.length%2&&(n=`0${n}`),r&&(Db(e,r),n=n.padEnd(r*2,"0"));let o=n.length/2,s=new Uint8Array(o);for(let i=0,a=0;i1||n[0]>1)throw new iL(n);return!!n[0]}function Xf(e,t={}){let{size:r}=t;typeof r<"u"&&Ub(e,r);let n=vn(e,t);return f9(n,t)}function d9(e,t={}){let{size:r}=t,n=e;return typeof r<"u"&&(Ub(n,r),n=NDe(n)),SDe.decode(n)}function cL(e){return nL(e,{dir:"left"})}function NDe(e){return nL(e,{dir:"right"})}function oie(e){try{return TDe(e),!0}catch{return!1}}var SDe,IDe,iL,Lb,i9,l3,a9,mu=b(()=>{l();Bi();io();Yse();sL();d3();SDe=new TextDecoder,IDe=new TextEncoder;iL=class extends Ke{constructor(t){super(`Bytes value \`${t}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}},Lb=class extends Ke{constructor(t){super(`Value \`${typeof t=="object"?z0(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},i9=class extends Ke{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},l3=class extends Ke{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}},a9=class extends Ke{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function kDe(e,t={}){let{even:r=!1,strict:n=!1}=t;if(!e)throw new p9(e);if(typeof e!="string")throw new p9(e);if(n&&!BDe.test(e))throw new h9(e);if(!e.startsWith("0x"))throw new h9(e);if(r&&e.length%2!==0)throw new m9(e)}function fn(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Hb(e){return e instanceof Uint8Array?vn(e):Array.isArray(e)?vn(new Uint8Array(e)):e}function g9(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Db(r,t.size),ep(r,t.size)):r}function vn(e,t={}){let r="";for(let o=0;os||o>1n;return n<=s?n:n-o-1n}function f9(e,t={}){let{signed:r,size:n}=t;return Number(!r&&!n?e:lL(e,t))}function q0(e,t={}){let{even:r=!1,strict:n=!1}=t;try{return kDe(e,{even:r,strict:n}),!0}catch{return!1}}var RDe,ODe,BDe,V0,p9,h9,m9,c9,u3,l9,io=b(()=>{l();Bi();sL();d3();RDe=new TextEncoder,ODe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),BDe=/^0x[0-9a-fA-F]*$/;V0=class extends Ke{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},p9=class extends Ke{constructor(t){super(`Value \`${typeof t=="object"?z0(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},h9=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},m9=class extends Ke{constructor(t){super(`Hex value \`"${t}"\` is an odd length (${t.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"})}},c9=class extends Ke{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},u3=class extends Ke{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},l9=class extends Ke{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function sie(e){return{address:e.address,amount:Yt(e.amount),index:Yt(e.index),validatorIndex:Yt(e.validatorIndex)}}var iie=b(()=>{l();io()});function w9(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Yt(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Yt(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Yt(e.gasLimit)},...typeof e.number=="bigint"&&{number:Yt(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Yt(e.prevRandao)},...typeof e.time=="bigint"&&{time:Yt(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(sie)}}}var uL=b(()=>{l();io();iie()});var ki,W0,cie,b9,lie,dL,fL,x9,Fb,Hr,uie,die,fie,pie,So=b(()=>{l();ki=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],W0=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],cie=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],b9=[...cie,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],lie=[...cie,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],dL=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],fL=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],x9=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Fb=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],Hr=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],uie=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],die=[{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC1155InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC1155InvalidApprover",type:"error"},{inputs:[{internalType:"uint256",name:"idsLength",type:"uint256"},{internalType:"uint256",name:"valuesLength",type:"uint256"}],name:"ERC1155InvalidArrayLength",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC1155InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC1155InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC1155InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC1155MissingApprovalForAll",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"values",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}],fie=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"event",name:"ApprovalForAll",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"operator",type:"address"},{indexed:!1,name:"approved",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"payable",inputs:[{name:"spender",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"getApproved",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"address"}]},{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"operator",type:"address"}],outputs:[{type:"bool"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"owner",type:"address"}]},{type:"function",name:"safeTransferFrom",stateMutability:"payable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"safeTransferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"id",type:"uint256"},{name:"data",type:"bytes"}],outputs:[]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"index",type:"uint256"}],outputs:[{type:"uint256"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"index",type:"uint256"}],outputs:[{name:"tokenId",type:"uint256"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transferFrom",stateMutability:"payable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}],pie=[{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!0,name:"owner",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],name:"allowance",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],name:"approve",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"asset",outputs:[{name:"assetTokenAddress",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"convertToAssets",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"convertToShares",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"}],name:"deposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxDeposit",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxMint",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxRedeem",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxWithdraw",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"}],name:"mint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewDeposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewMint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewRedeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewWithdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"redeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"totalAssets",outputs:[{name:"totalManagedAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"withdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"}]});var hie,mie=b(()=>{l();hie="0x82ad56cb"});var zb,v9,f3,Mg,Vb=b(()=>{l();zb="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",v9="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",f3="0x608060405234801561001057600080fd5b506040516106ad3803806106ad83398101604081905261002f91610537565b600061003c848484610048565b9050806000526001601ff35b60007f649264926492649264926492649264926492649264926492649264926492649261007483610425565b036101e7576000606080848060200190518101906100929190610590565b60405192955090935091506000906001600160a01b038516906100b69085906105f6565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b908790600401610612565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d1919061064c565b6001600160e01b0319161494505050505061041e565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e906102279087908790600401610612565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610268919061064c565b6001600160e01b03191614905061041e565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061068d83398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e761043e565b5060208201516040808401518451859392600091859190811061030c5761030c610676565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061068d83398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b604080516000808252602082018084528a905260ff841692820192909252606081018590526080810184905260019060a0016020604051602081039080840390855afa1580156103e0573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116158015906104165750886001600160a01b0316816001600160a01b0316145b955050505050505b9392505050565b600060208251101561043657600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461047157600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b838110156104a557818101518382015260200161048d565b50506000910152565b600082601f8301126104bf57600080fd5b81516001600160401b038111156104d8576104d8610474565b604051601f8201601f19908116603f011681016001600160401b038111828210171561050657610506610474565b60405281815283820160200185101561051e57600080fd5b61052f82602083016020870161048a565b949350505050565b60008060006060848603121561054c57600080fd5b83516105578161045c565b6020850151604086015191945092506001600160401b0381111561057a57600080fd5b610586868287016104ae565b9150509250925092565b6000806000606084860312156105a557600080fd5b83516105b08161045c565b60208501519093506001600160401b038111156105cc57600080fd5b6105d8868287016104ae565b604086015190935090506001600160401b0381111561057a57600080fd5b6000825161060881846020870161048a565b9190910192915050565b828152604060208201526000825180604084015261063781606085016020870161048a565b601f01601f1916919091016060019392505050565b60006020828403121561065e57600080fd5b81516001600160e01b03198116811461041e57600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Mg="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"});function tp(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find(i=>"type"in i&&i.type==="constructor");if(!o)throw new Oh({docsPath:pL});if(!("inputs"in o))throw new Gl({docsPath:pL});if(!o.inputs||o.inputs.length===0)throw new Gl({docsPath:pL});let s=oo(o.inputs,r);return fr([n,s])}var pL,p3=b(()=>{l();Qr();Fn();rc();pL="/docs/contract/encodeDeployData"});function Ui({blockNumber:e,chain:t,contract:r}){let n=t?.contracts?.[r];if(!n)throw new Wf({chain:t,contract:{name:r}});if(e!==void 0&&n.blockCreated!==void 0&&n.blockCreated>e)throw new Wf({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}var K0=b(()=>{l();Ug()});function E9(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ni?e:o})();return new Yc(n,{docsPath:t,...r})}var hL=b(()=>{l();ou();tl();G4()});function jb(){let e=()=>{},t=()=>{};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}var A9=b(()=>{l()});function Z0({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let s=async()=>{let d=c();i();let f=d.map(({args:p})=>p);f.length!==0&&new Promise(p=>p(e(f))).then(p=>{o&&Array.isArray(p)&&p.sort(o);for(let h=0;h{for(let h=0;hmL.delete(t),a=()=>c().map(({args:d})=>d),c=()=>mL.get(t)||[],u=d=>mL.set(t,[...c(),d]);return{flush:i,async schedule(d){let{promise:f,resolve:p,reject:h}=jb();return r?.([...a(),d])&&s(),c().length>0?(u({args:d,resolve:p,reject:h}),f):(u({args:d,resolve:p,reject:h}),setTimeout(s,n),f)}}}var mL,h3=b(()=>{l();A9();mL=new Map});var C9,S9,I9,gie=b(()=>{l();so();nt();oc();C9=class extends G{constructor({callbackSelector:t,cause:r,data:n,extraData:o,sender:s,urls:i}){super(r.shortMessage||"An error occurred while fetching for an offchain result.",{cause:r,metaMessages:[...r.metaMessages||[],r.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(a=>` ${kf(a)}`)],` Sender: ${s}`,` Data: ${n}`,` Callback selector: ${t}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}},S9=class extends G{constructor({result:t,url:r}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${kf(r)}`,`Response: ${bt(t)}`],name:"OffchainLookupResponseMalformedError"})}},I9=class extends G{constructor({sender:t,to:r}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${r}`,`OffchainLookup sender address: ${t}`],name:"OffchainLookupSenderMismatchError"})}}});function T9(e){let{abi:t,data:r}=e,n=vo(r,0,4),o=t.find(s=>s.type==="function"&&n===va(no(s)));if(!o)throw new Bw(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:o.name,args:"inputs"in o&&o.inputs&&o.inputs.length>0?Ys(o.inputs,vo(r,4)):void 0}}var gL=b(()=>{l();Qr();Si();Ag();zh();Cf()});function m3(e){let{abi:t,errorName:r,args:n}=e,o=t[0];if(r){let c=ls({abi:t,args:n,name:r});if(!c)throw new pg(r,{docsPath:yL});o=c}if(o.type!=="error")throw new pg(void 0,{docsPath:yL});let s=no(o),i=va(s),a="0x";if(n&&n.length>0){if(!o.inputs)throw new Ow(o.name,{docsPath:yL});a=oo(o.inputs,n)}return fr([i,a])}var yL,wL=b(()=>{l();Qr();Fn();Ag();rc();Cf();Bf();yL="/docs/contract/encodeErrorResult"});function _9(e){let{abi:t,functionName:r,result:n}=e,o=t[0];if(r){let i=ls({abi:t,name:r});if(!i)throw new wa(r,{docsPath:bL});o=i}if(o.type!=="function")throw new wa(void 0,{docsPath:bL});if(!o.outputs)throw new Dh(o.name,{docsPath:bL});let s=(()=>{if(o.outputs.length===0)return[];if(o.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Mh(n)})();return oo(o.outputs,s)}var bL,xL=b(()=>{l();Qr();rc();Bf();bL="/docs/contract/encodeFunctionResult"});function vL(){let e=0,t=[];return{bytes:ol.bytes,queries:ol.queries,async run(r){e>=ol.concurrency?await new Promise(n=>t.push(n)):e++;try{return await r()}finally{let n=t.shift();n?n():e--}}}}async function EL(e){let{data:t,ccipRequest:r,budget:n=vL(),depth:o=0}=e,{args:[s]}=T9({abi:W0,data:t}),i=[],a=[];return await Promise.all(s.map(async(c,u)=>{try{let d=c.urls.includes(Ia);if(d&&o+1>=ol.depth)throw new Nr({details:`CCIP Read exceeded the maximum batch depth (${ol.depth}).`,url:Ia});if(d)a[u]=await EL({data:c.data,ccipRequest:r,budget:n,depth:o+1});else{if(n.queries<=0)throw new Nr({details:`CCIP Read exceeded the maximum number of queries (${ol.queries}).`,url:c.urls[0]??""});let f=c.urls.slice(0,n.queries);n.queries-=Math.max(1,f.length);let p=await n.run(async()=>n.bytes<0?"0x":r({...c,urls:f}));if(n.bytes-=gt(p),n.bytes<0)throw new Nr({details:`CCIP Read exceeded the maximum response size (${ol.bytes} bytes).`,url:Ia});a[u]=p}i[u]=!1}catch(d){if(n.bytes<0)throw d;i[u]=!0,a[u]=DDe(d)}})),_9({abi:W0,functionName:"query",result:[i,a]})}function DDe(e){return e.name==="HttpRequestError"&&e.status?m3({abi:W0,errorName:"HttpError",args:[e.status,e.shortMessage]}):m3({abi:[Gw],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}var Ia,ol,qb=b(()=>{l();So();R4();fs();gL();wL();xL();Fo();Ia="x-batch-gateway:true",ol={bytes:10485760,concurrency:16,depth:4,queries:256}});function P9(e){let t=e.filter(s=>!!s);if(t.length<2)return{signal:t[0]??null,cleanup:()=>{}};let r=new AbortController,n=()=>{o(),r.abort(t.find(s=>s.aborted)?.reason)},o=()=>{for(let s of t)s.removeEventListener("abort",n)};for(let s of t){if(s.aborted){o(),r.abort(s.reason);break}s.addEventListener("abort",n)}return{signal:r.signal,cleanup:o}}async function Wb(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw await e.body?.cancel(),new ic({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new ic({maxSize:t,size:c});return a}let n=e.body.getReader(),o=new TextDecoder,s="",i=0;try{for(;;){let{done:a,value:c}=await n.read();if(a)break;if(i+=c.byteLength,i>t)throw await n.cancel(),new ic({maxSize:t,size:i});s+=o.decode(c,{stream:!0})}return s+=o.decode(),s}finally{n.releaseLock()}}var N9=b(()=>{l();fs()});function sl(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((o,s)=>{(async()=>{let i,a=new AbortController;try{r>0&&(i=setTimeout(()=>{n?a.abort():s(t)},r)),o(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&Ii(c)){s(t);return}s(c)}finally{clearTimeout(i)}})()})}var Kb=b(()=>{l();oc()});var wie={};Te(wie,{ccipRequest:()=>Hg,offchainLookup:()=>B9,offchainLookupAbiItem:()=>O9,offchainLookupSignature:()=>R9});async function B9(e,{blockHash:t,blockNumber:r,blockTag:n,budget:o=vL(),data:s,depth:i=0,requestOptions:a,requireCanonical:c,to:u}){let{args:d}=Vh({data:s,abi:[O9]}),[f,p,h,y,w]=d,{ccipRead:x}=e,v=x&&typeof x?.request=="function"?x.request:Hg,T=yie(e.transport);try{if(i>=ol.depth)throw new Nr({details:`CCIP Read exceeded the maximum callback depth (${ol.depth}).`,url:p[0]??""});if(!xr(u,f))throw new I9({sender:f,to:u});let E=await(async()=>{if(p.includes(Ia))return EL({budget:o,ccipRequest:O=>v({...O,requestOptions:a,timeout:O.timeout??T}),data:h});if(o.queries<=0)throw new Nr({details:`CCIP Read exceeded the maximum number of queries (${ol.queries}).`,url:p[0]??""});let _=p.slice(0,o.queries);return o.queries-=Math.max(1,_.length),o.run(()=>v({data:h,requestOptions:a,sender:f,timeout:T,urls:_}))})(),S=en([y,oo([{type:"bytes"},{type:"bytes"}],[E,w])]);try{let{data:_}=await ms({...e,ccipRead:!1},{blockHash:t,blockNumber:r,blockTag:n,data:S,requestOptions:a,requireCanonical:c,to:u});return _}catch(_){let O=AL(_);if(O?.slice(0,10)!==R9)throw _;return await B9(e,{blockHash:t,blockNumber:r,blockTag:n,budget:o,data:O,depth:i+1,requestOptions:a,requireCanonical:c,to:u})}}catch(E){throw a?.signal?.aborted?Nn(a.signal):Ii(E)?E:new C9({callbackSelector:y,cause:E,data:s,extraData:w,sender:f,urls:p})}}async function Hg({data:e,requestOptions:t,sender:r,timeout:n=LDe,urls:o}){let s=new Error("An unknown error occurred.");for(let i of o){if(t?.signal?.aborted)throw Nn(t.signal);let a=i.replace("{sender}",r.toLowerCase()).replace("{data}",e),c=i.includes("{data}")?"GET":"POST",u=c==="POST"?{data:e,sender:r}:void 0,d=c==="POST"?{"Content-Type":"application/json"}:{};try{HDe(a);let{response:f,responseBody:p}=await sl(async({signal:y})=>{let{signal:w,cleanup:x}=P9([t?.signal,n>0?y:null]);try{let v=await fetch(a,{body:JSON.stringify(u),headers:d,method:c,...w?{signal:w}:{}}),T=await Wb(v,{maxResponseBodySize:MDe});return{response:v,responseBody:T}}finally{x()}},{errorInstance:new ds({body:u??{data:e,sender:r},url:i}),signal:!0,timeout:n}),h;if(f.headers.get("Content-Type")?.startsWith("application/json")?h=JSON.parse(p).data:h=p,!f.ok){s=new Nr({body:u,details:h?.error?bt(h.error):f.statusText,headers:f.headers,status:f.status,url:i});continue}if(!We(h)){s=new S9({result:h,url:i});continue}return h}catch(f){if(t?.signal?.aborted)throw Nn(t.signal);if(Ii(f))throw f;if(f instanceof Nr||f instanceof ds||f instanceof ic){s=f;continue}s=new Nr({body:u,cause:f,url:i})}}throw s}function HDe(e){let t=(()=>{try{return new URL(e)}catch{throw new Nr({details:"CCIP Read URL is invalid.",url:e})}})();if(!(t.protocol==="http:"||t.protocol==="https:"))throw new Nr({details:`CCIP Read URL scheme "${t.protocol.slice(0,-1)}" is not allowed.`,url:e})}function yie(e){let t=e.timeout??e.config?.timeout;if(t!==void 0)return t;let r=(e.transports??e.value?.transports??[]).map(yie).filter(n=>n!==void 0);return r.length?Math.max(...r):void 0}var LDe,MDe,R9,O9,k9=b(()=>{l();G0();gie();fs();oc();L4();rc();Oi();Fn();qs();qb();N9();Kb();so();LDe=1e4,MDe=10485760,R9="0x556f1830",O9={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function ms(e,t){let{account:r=e.account,authorizationList:n,batch:o=!!e.batch?.multicall,blockHash:s,blockNumber:i,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:u,blobs:d,blockOverrides:f,code:p,data:h,factory:y,factoryData:w,gas:x,gasPrice:v,maxFeePerBlobGas:T,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:_,requestOptions:O,to:D,value:M,stateOverride:N,...L}=t,P=r?ft(r):void 0;if(p&&(y||w))throw new G("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(p&&D)throw new G("Cannot provide both `code` & `to` as parameters.");let R=p&&h,I=y&&w&&D&&h,B=R||I,C=R?vie({code:p,data:h}):I?qDe({data:h,factory:y,factoryData:w,to:D}):h;try{jn(t);let A=ni({blockHash:s,blockNumber:i,blockTag:a,requireCanonical:c}),U=f?w9(f):void 0,H=xb(N),k=e.chain?.formatters?.transactionRequest?.format,j=(k||Bn)({...Ri(L,{format:k}),accessList:u,account:P,authorizationList:n,blobs:d,data:C,gas:x,gasPrice:v,maxFeePerBlobGas:T,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:_,to:B?void 0:D,value:M},"call");if(o&&$De({request:j})&&!U&&s===void 0)try{let{deployless:te=!1}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},X=xie(e,{blockNumber:i,deployless:te});if(!X||!jDe(H,X))return await VDe(e,{...j,blockHash:s,blockNumber:i,blockTag:a,multicallAddress:X,requestOptions:O,requireCanonical:c,rpcStateOverride:H})}catch(te){if(!(te instanceof kg)&&!(te instanceof Wf))throw te}let W=(()=>{let te=[j,A];return H&&U?[...te,H,U]:H?[...te,H]:U?[...te,{},U]:te})(),ae=await e.request({method:"eth_call",params:W},O);return ae==="0x"?{data:void 0}:{data:ae}}catch(A){if(O?.signal?.aborted)throw Nn(O.signal);if(Ii(A))throw A;let U=AL(A),{offchainLookup:H,offchainLookupSignature:k}=await Promise.resolve().then(()=>(k9(),wie));if(e.ccipRead!==!1&&U?.slice(0,10)===k&&D)return{data:await H(e,{blockHash:s,blockNumber:i,blockTag:a,data:U,requestOptions:O,requireCanonical:c,to:D})};throw B&&U?.slice(0,10)==="0x101bb98d"?new lb({factory:y}):E9(A,{...t,account:P,chain:e.chain})}}function $De({request:e}){let{data:t,to:r,...n}=e;return!(!t||t.startsWith(hie)||!r||Object.values(n).filter(o=>typeof o<"u").length>0)}function zDe(e){if(!e)return"default";let t=bie.get(e);if(t!==void 0)return t;let r=FDe++;return bie.set(e,r),r}async function VDe(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockHash:s,blockNumber:i,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:u,multicallAddress:d,requestOptions:f,rpcStateOverride:p,to:h}=t,y=d!==void 0?d:xie(e,{blockNumber:i,deployless:n}),w=ni({blockHash:s,blockNumber:i,blockTag:a,requireCanonical:c}),x=typeof w=="string"?w:JSON.stringify(w),v=p?`.${JSON.stringify(p)}`:"",{schedule:T}=Z0({id:`${e.uid}.${x}.${zDe(f)}${v}`,wait:o,shouldSplitBatch(_){return _.reduce((D,{data:M})=>D+(M.length-2),0)>r*2},fn:async _=>{let O=_.map(P=>({allowFailure:!0,callData:P.data,target:P.to})),D=Wt({abi:ki,args:[O],functionName:"aggregate3"}),M={...y===null?{data:vie({code:Mg,data:D})}:{to:y,data:D}},N=await e.request({method:"eth_call",params:p?[M,w,p]:[M,w]},f),L=dn({abi:ki,args:[O],functionName:"aggregate3",data:N||"0x"});if(L.length!==_.length)throw new G(`Multicall returned ${L.length} results for ${_.length} calls.`);return L}}),[{returnData:E,success:S}]=await T({data:u,to:h});if(!S)throw new sc({data:E});return E==="0x"?{data:void 0}:{data:E}}function xie(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return Ui({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new kg}function jDe(e,t){return e?Object.keys(e).some(r=>xr(r,t)):!1}function vie(e){let{code:t,data:r}=e;return tp({abi:Iw(["constructor(bytes, bytes)"]),bytecode:zb,args:[t,r]})}function qDe(e){let{data:t,factory:r,factoryData:n,to:o}=e;return tp({abi:Iw(["constructor(address, bytes, address, bytes)"]),bytecode:v9,args:[o,t,r,n]})}function AL(e){if(!(e instanceof G))return;let t=e.walk();return typeof t?.data=="object"?t.data?.data:t.data}var FDe,bie,G0=b(()=>{l();fg();uL();tn();So();mie();Vb();nt();Ug();ou();oc();lc();p3();us();Oi();B0();K0();hL();P0();rl();h3();VI();nl();FDe=0,bie=new WeakMap});async function er(e,t){let{abi:r,address:n,args:o,functionName:s,...i}=t,a=Wt({abi:r,args:o,functionName:s});try{let{data:c}=await ue(e,ms,"call")({...i,data:a,to:n});return dn({abi:r,args:o,functionName:s,data:c||"0x"})}catch(c){throw Js(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:s})}}var oi=b(()=>{l();lc();us();p0();_t();G0()});async function Y0(e,t){let{abi:r,address:n,args:o,functionName:s,dataSuffix:i=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account===void 0?e.account:a.account&&ft(a.account),u=Wt({abi:r,args:o,functionName:s});try{let{data:d}=await ue(e,ms,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=dn({abi:r,args:o,functionName:s,data:d||"0x"}),p=r.filter(h=>"name"in h&&h.name===t.functionName);return{result:f,request:{abi:p,address:n,args:o,dataSuffix:i,functionName:s,...a,account:c}}}catch(d){throw Js(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:s,sender:c?.address})}}var g3=b(()=>{l();tn();lc();us();p0();_t();G0()});function Io(e,t,r){let n=++WDe,o=()=>U9.get(e)||[],s=()=>{let f=o().filter(p=>p.id!==n);if(f.length===0){U9.delete(e),CL.delete(e);return}U9.set(e,f)},i=()=>{let d=o();if(!d.some(p=>p.id===n))return;let f=CL.get(e);if(d.length===1&&f){let p=f();p instanceof Promise&&p.catch(()=>{})}s()},a=o();if(U9.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return i;let c={};for(let d in t)c[d]=((...f)=>{let p=o();if(p.length!==0)for(let h of p)h.fns[d]?.(...f)});let u=r(c);return typeof u=="function"&&CL.set(e,u),i}var U9,CL,WDe,rp=b(()=>{l();U9=new Map,CL=new Map,WDe=0});async function $g(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(Nn(t));return}let o=()=>t?.removeEventListener("abort",i),s=setTimeout(()=>{o(),r()},Math.min(e,2**31-1)),i=()=>{clearTimeout(s),o(),n(Nn(t))};t?.addEventListener("abort",i,{once:!0})})}var D9=b(()=>{l();oc()});function dc(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,s=()=>o=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));let c=await r?.(a)??n;await $g(c);let u=async()=>{o&&(await e({unpoll:s}),await $g(n),u())};u()})(),s}var Fg=b(()=>{l();D9()});function Eie(e){let t=(o,s)=>({clear:()=>s.delete(o),get:()=>s.get(o),set:i=>s.set(o,i)}),r=t(e,KDe),n=t(e,ZDe);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function L9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=Eie(t),o=n.response.get();if(o&&r>0&&Date.now()-o.created.getTime(){l();KDe=new Map,ZDe=new Map});async function Ta(e,{cacheTime:t=e.cacheTime}={}){let r=await L9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:GDe(e.uid),cacheTime:t});return BigInt(r)}var GDe,zg=b(()=>{l();SL();GDe=e=>`blockNumber.${e}`});async function J0(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;let o=n.map(s=>qn(s));return!("abi"in t)||!t.abi?o:cc({abi:t.abi,eventName:t.eventName,logs:o,strict:r})}var y3=b(()=>{l();Dg();hu()});function gu(e){if(e.transport.type==="fallback"){let t=e.transport.transports.find(r=>r.config.type==="webSocket"||r.config.type==="ipc");return t?t.value:e.transport}return e.transport}function Q0(e){return!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))}var Zb=b(()=>{l()});async function X0(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}var w3=b(()=>{l()});function M9(e,t){let{abi:r,address:n,args:o,batch:s=!0,eventName:i,fromBlock:a,onError:c,onLogs:u,poll:d,pollingInterval:f=e.pollingInterval,strict:p}=t;return(typeof d<"u"?d:typeof a=="bigint"?!0:Q0(e))?(()=>{let x=p??!1,v=bt(["watchContractEvent",n,o,s,e.uid,i,f,x,a]);return Io(v,{onLogs:u,onError:c},T=>{let E=!0,S=a===void 0?void 0:a-1n,_,O=!1,D=L=>{if(L.length!==0)if(s)T.onLogs(L);else for(let P of L)T.onLogs([P])},M=(L,P)=>ue(e,kb,"getContractEvents")({abi:r,address:n,args:o,eventName:i,fromBlock:L,toBlock:P,strict:x}),N=dc(async()=>{if(!O){try{_=await ue(e,Zw,"createContractEventFilter")({abi:r,address:n,args:o,eventName:i,strict:x,fromBlock:a})}catch{}if(O=!0,_)return}try{if(_){let R=await ue(e,J0,"getFilterChanges")({filter:_});D(R);return}let L=await ue(e,Ta,"getBlockNumber")({});S??=L;let P=L-S;for(;S{if(R===B||!Bb(A))throw A});if(!E)return;if(!C){P=(B-R+1n)/2n;continue}S=B,D(C)}}catch(L){_&&L instanceof Ti&&(O=!1),T.onError?.(L)}},{emitOnBegin:!0,interval:f});return async()=>{E=!1,_&&await ue(e,X0,"uninstallFilter")({filter:_}),N()}})})():(()=>{let x=p??!1,v=bt(["watchContractEvent",n,o,s,e.uid,i,f,x]),T=!0,E=()=>T=!1;return Io(v,{onLogs:u,onError:c},S=>((async()=>{try{let _=gu(e),O=!!(i||p),D=i?nc({abi:r,eventName:i,args:o}):[],{unsubscribe:M}=await _.subscribe({params:["logs",{address:n,topics:D}],onData(N){if(!T)return;let L=N.result;try{let P=Yf({abi:r,data:L.data,eventName:i,topics:L.topics,strict:p}),R=qn(L,{args:P.args,eventName:P.eventName});S.onLogs([R])}catch(P){if(O&&(P instanceof Gf||P instanceof Yl||P instanceof Jl))return;let R,I;if(P instanceof jc||P instanceof Ql){if(p)return;R=P.abiItem.name,I=P.abiItem.inputs?.some(C=>!("name"in C&&C.name))}let B=qn(L,{args:I?[]:{},eventName:R});S.onLogs([B])}},onError(N){S.onError?.(N)}});E=M,T||E()}catch(_){c?.(_)}})(),()=>E()))})()}var IL=b(()=>{l();Qr();Lf();a3();Cg();hu();_t();rp();Fg();so();II();zg();s9();y3();n9();Zb();w3()});var kn,fc,yu=b(()=>{l();nt();kn=class extends G{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` -`),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}},fc=class extends G{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}});function em({chain:e,currentChainId:t}){if(!e)throw new Sb;if(t!==e.id)throw new U0({chain:e,currentChainId:t})}var b3=b(()=>{l();Ug()});async function Gb(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var H9=b(()=>{l()});async function tm(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:s,authorizationList:i,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,type:x,value:v,...T}=t;if(typeof r>"u")throw new kn({docsPath:"/docs/actions/wallet/sendTransaction"});let E=r?ft(r):null,S;try{jn(t);let _=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await b0({authorization:i[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if(E?.type==="json-rpc"||E===null){let O;o!==null&&(O=await ue(e,hs,"getChainId")({}),n&&em({currentChainId:O,chain:o}));let D=e.chain?.formatters?.transactionRequest?.format,N=(D||Bn)({...Ri(T,{format:D}),accessList:s,account:E,authorizationList:i,blobs:a,chainId:O,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,to:_,type:x,value:v},"sendTransaction"),L=TL.get(e.uid),P=L?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:P,params:[N]},{retryCount:0})}catch(R){if(L===!1)throw R;let I=R;if(I.name==="InvalidInputRpcError"||I.name==="InvalidParamsRpcError"||I.name==="MethodNotFoundRpcError"||I.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[N]},{retryCount:0}).then(B=>(TL.set(e.uid,!0),B)).catch(B=>{let C=B;throw C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError"?(TL.set(e.uid,!1),I):C});throw I}}if(E?.type==="local"){let O=(()=>{if(!E.nonceManager||typeof w<"u")return E.nonceManager;let R=E.nonceManager;return{async consume(I){S={address:I.address,chainId:I.chainId};let B=await R.consume(I);return S={...S,nonce:B},B},get(I){return R.get(I)},increment(I){return R.increment(I)},reset(I){return R.reset(I)}}})(),D=await ue(e,pu,"prepareTransactionRequest")({account:E,accessList:s,authorizationList:i,blobs:a,chain:o,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,nonceManager:O,parameters:[...s3,"sidecars"],type:x,value:v,...T,to:_}),M=o?.serializers?.transaction,N=await E.signTransaction(D,{serializer:M}),L=(o??e.chain)?.serializers?.transactionEnvelope,P=L?await L({serializedTransaction:N,transaction:D}):N;return await ue(e,Gb,"sendRawTransaction")({serializedTransaction:P})}throw E?.type==="smart"?new fc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new fc({docsPath:"/docs/actions/wallet/sendTransaction",type:E?.type})}catch(_){throw _ instanceof fc?_:(S&&E?.nonceManager?.reset(S),H0(_,{...t,account:E,chain:t.chain||void 0}))}}var TL,x3=b(()=>{l();tn();yu();nt();Z4();b3();Fn();o3();P0();rl();_t();_f();nl();Zf();Rb();H9();TL=new xo(128)});async function _a(e,t){return _a.internal(e,tm,"sendTransaction",t)}var Yb=b(()=>{l();tn();yu();us();p0();_t();x3();(function(e){async function t(r,n,o,s){let{abi:i,account:a=r.account,address:c,args:u,functionName:d,...f}=s;if(typeof a>"u")throw new kn({docsPath:"/docs/contract/writeContract"});let p=a?ft(a):null,h=Wt({abi:i,args:u,functionName:d});try{return await ue(r,n,o)({data:h,to:c,account:p,...f})}catch(y){throw Js(y,{abi:i,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:d,sender:p?.address})}}e.internal=t})(_a||(_a={}))});function Aie({abi:e,address:t,client:r}){let n=r,[o,s]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],i=o!=null,a=s!=null,c={},u=!1,d=!1,f=!1;for(let p of e)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:d=!0:p.type==="event"&&(f=!0),u&&d&&f)break;return i&&(u&&(c.read=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o,er,"readContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),d&&(c.simulate=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o,Y0,"simulateContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,Zw,"createContractEventFilter")({abi:e,address:t,eventName:h,args:x,...v})}}}),c.getEvents=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,kb,"getContractEvents")({abi:e,address:t,eventName:h,args:x,...v})}}}),c.watchEvent=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,M9,"watchContractEvent")({abi:e,address:t,eventName:h,args:x,...v})}}}))),a&&d&&(c.write=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(s,_a,"writeContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),(i||a)&&d&&(c.estimateGas=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o??s,$0,"estimateContractGas")({abi:e,address:t,functionName:h,args:w,...x,account:x.account??s.account})}}})),c.address=t,c.abi=e,c}function $9(e){let t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function _L(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);let n=r?e[0]:void 0,o=(r?e[1]:e[0])??{};return{args:n,options:o}}var Cie=b(()=>{l();_t();II();i3();s9();oi();g3();IL();Yb()});var Jb,PL=b(()=>{l();nt();Jb=class extends G{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}}});function np(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((s,i)=>{let a=()=>i(Nn(o));o?.addEventListener("abort",a,{once:!0});let c=async({count:u=0}={})=>{if(o?.aborted){i(Nn(o));return}let d=async({error:f})=>{let p=typeof t=="function"?t({count:u,error:f}):t;if(p)try{await $g(p,{signal:o})}catch(h){i(h);return}return c({count:u+1})};try{let f=await e();s(f)}catch(f){if(o?.aborted){i(Nn(o));return}if(Ii(f)){i(f);return}if(uo?.removeEventListener("abort",a))})}var v3=b(()=>{l();oc();D9()});function op(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>qn(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?wt(e.transactionIndex):null,status:e.status?NL[e.status]:null,type:e.type?Q4[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}var NL,Sie,Qb=b(()=>{l();Xr();Y4();hu();Ab();NL={"0x0":"reverted","0x1":"success"};Sie=N0("transactionReceipt",op)});async function F9(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:s=32,forceAtomic:i=!1,id:a,version:c="2.0.0"}=t,u=r?ft(r):null,d=t.capabilities;e.dataSuffix&&!t.capabilities?.dataSuffix&&(typeof e.dataSuffix=="string"?d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}}:d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}});let f=t.calls.map(p=>{let h=p,y=h.abi?Wt({abi:h.abi,functionName:h.functionName,args:h.args}):h.data;return{data:h.dataSuffix?en([y??"0x",h.dataSuffix]):y,to:h.to,value:h.value?oe(h.value):void 0}});try{let p=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:i,calls:f,capabilities:d,chainId:oe(n.id),from:u?.address,id:a,version:c}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){let h=p;if(o&&(h.name==="MethodNotFoundRpcError"||h.name==="MethodNotSupportedRpcError"||h.name==="UnknownRpcError"||h.details.toLowerCase()==="this request method is not supported"||h.details.toLowerCase().includes("does not exist / is not available")||h.details.toLowerCase().includes("missing or invalid. request()")||h.details.toLowerCase().includes("did not match any variant of untagged enum")||h.details.toLowerCase().includes("account upgraded to unsupported contract")||h.details.toLowerCase().includes("eip-7702 not supported")||h.details.toLowerCase().includes("unsupported wc_ method")||h.details.toLowerCase().includes("feature toggled misconfigured")||h.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d&&Object.values(d).some(v=>!v.optional)){let v="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new au(new G(v,{details:v}))}if(i&&f.length>1){let x="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new cu(new G(x,{details:x}))}let y=[];for(let x of f){try{let v=await ue(e,tm,"sendTransaction")({account:u,chain:n,data:x.data,to:x.to,value:x.value?dt(x.value):void 0});y.push({status:"fulfilled",value:v})}catch(v){y.push({reason:v,status:"rejected"})}s>0&&await new Promise(v=>setTimeout(v,s))}if(y.every(x=>x.status==="rejected"))throw y[0].reason;let w=y.map(x=>x.status==="fulfilled"?x.value:OL);return{id:en([...w,oe(n.id,{size:32}),RL])}}throw H0(p,{...t,account:u,chain:t.chain})}}var RL,OL,z9=b(()=>{l();tn();nt();Lf();us();Fn();Xr();qe();o3();_t();x3();RL="0x5792579257925792579257925792579257925792579257925792579257925792",OL=oe(0,{size:32})});async function V9(e,t){async function r(d){if(d.endsWith(RL.slice(2))){let p=bn(xa(d,-64,-32)),h=xa(d,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(h.map(x=>OL.slice(2)!==x?e.request({method:"eth_getTransactionReceipt",params:[`0x${x}`]},{dedupe:!0}):void 0)),w=y.some(x=>x===null)?100:y.every(x=>x?.status==="0x1")?200:y.every(x=>x?.status==="0x0")?500:600;return{atomic:!1,chainId:wt(p),receipts:y.filter(Boolean),status:w,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:n=!1,chainId:o,receipts:s,version:i="2.0.0",...a}=await r(t.id),[c,u]=(()=>{let d=a.status;return d>=100&&d<200?["pending",d]:d>=200&&d<300?["success",d]:d>=300&&d<700?["failure",d]:d==="CONFIRMED"?["success",200]:d==="PENDING"?["pending",100]:[void 0,d]})();return{...a,atomic:n,chainId:o?wt(o):void 0,receipts:s?.map(d=>({...d,blockNumber:dt(d.blockNumber),gasUsed:dt(d.gasUsed),status:NL[d.status]}))??[],statusCode:u,status:c,version:i}}var BL=b(()=>{l();Si();Hh();Xr();Qb();z9()});function Tie(e){let t=Iie.get(e);return t===void 0&&(t=++YDe,Iie.set(e,t)),t}async function j9(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:w})=>w===200||w>=300,retryCount:s=4,retryDelay:i=({count:w})=>~~(1<{let x=dc(async()=>{let v=T=>{clearTimeout(h),x(),T(),y()};try{let T=await np(async()=>{let E=await ue(e,V9,"getCallsStatus")({id:r});if(c&&E.status==="failure")throw new Jb(E);return E},{retryCount:s,delay:i});if(!o(T))return;v(()=>w.resolve(T))}catch(T){v(()=>w.reject(T))}},{interval:n,emitOnBegin:!0});return x});return h=a?setTimeout(()=>{y(),clearTimeout(h),p(new E3({id:r}))},a):void 0,await d.finally(()=>y())}var Iie,YDe,E3,q9=b(()=>{l();nt();PL();_t();rp();Fg();A9();v3();so();BL();Iie=new WeakMap,YDe=0;E3=class extends G{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}});function rm(e=11){if(!K9||W9+e>256*2){K9="",W9=0;for(let t=0;t<256;t++)K9+=(256+Math.random()*256|0).toString(16).substring(1)}return K9.substring(W9,W9+++e)}var W9,K9,A3=b(()=>{l();W9=256});function wu(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:s="base",name:i="Base Client",tokens:a,type:c="base"}=e,u=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime=="number"?"pending":void 0),d=r?.blockTime??12e3,f=Math.min(Math.max(Math.floor(d/2),500),4e3),p=e.pollingInterval??f,h=e.cacheTime??Math.min(p,Math.floor(d/2)),y=e.account?ft(e.account):void 0,{config:w,request:x,value:v}=e.transport({account:y,chain:r,pollingInterval:p}),T={...w,...v},E={account:y,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:s,name:i,pollingInterval:p,request:x,tokens:a,transport:T,type:c,uid:rm(),...u?{experimental_blockTag:u}:{}};return Nie(E)}function Nie(e){function t(n,o){return s=>{let i=s(n);for(let d in e)d!=="scope"&&delete i[d];let a={...n,...i};for(let d in i){let f=n[d],p=i[d];Pie(f)&&Pie(p)&&(a[d]={...f,...p})}let c=[...o,s],{scope:u}=a;return Object.assign(a,{extend:t(a,c),scope:typeof u=="function"&&_ie.has(u)?r(c):u})}}function r(n){let o=new WeakMap,s=(i={})=>{let a=i.signal&&o.get(i.signal);if(a)return a;let c=`scope.${JDe++}`,u=new AbortController,{signal:d}=i;d?.aborted?u.abort(d.reason):d?.addEventListener("abort",()=>u.abort(d.reason),{once:!0});let f=(h,y)=>e.request(h,{...y,signal:y?.signal??u.signal,uid:y?.uid??c}),p=n.reduce((h,y)=>h.extend(y),Nie({...e,request:f,uid:c}));return d&&o.set(d,p),p};return _ie.add(s),s}return Object.assign(e,{extend:t(e,[]),scope:r([])})}function Pie(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bu(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(s={})=>o.length===1?o(s):o(e,s)}for(let n of["extractEvent","extractEvents"])Object.hasOwn(t,n)&&(r[n]=t[n]);return r}function Rie(){return null}var _ie,JDe,nm=b(()=>{l();tn();A3();_ie=new WeakSet,JDe=0});function Oie(e){let{chains:t,transport:r,...n}=e,o=new Map;return{getClient({chainId:s}){let i=o.get(s);if(i)return i;let a=t.find(d=>d.id===s);if(!a)throw new C3({chainId:s});let c=typeof r=="function"?r({chainId:s}):r[s];if(!c)throw new S3({chainId:s});let u=wu({...n,chain:a,transport:c});return o.set(s,u),u}}}var C3,S3,Bie=b(()=>{l();nt();nm();C3=class extends G{constructor({chainId:t}){super(`Chain with id ${t} is not configured.`,{name:"createClientResolver.ChainNotConfiguredError"})}},S3=class extends G{constructor({chainId:t}){super(`Transport for chain with id ${t} is not configured.`,{name:"createClientResolver.TransportNotConfiguredError"})}}});function Xb(e){if(!(e instanceof G))return!1;let t=e.walk(r=>r instanceof Uf);return t instanceof Uf?t.data?.errorName==="HttpError"||t.data?.errorName==="ResolverError"||t.data?.errorName==="ResolverNotContract"||t.data?.errorName==="ResolverNotFound"||t.data?.errorName==="ReverseAddressMismatch"||t.data?.errorName==="UnsupportedResolverProfile":!1}var Z9=b(()=>{l();nt();ou()});function G9(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;return We(t)?t:null}var kL=b(()=>{l();qs()});function Vg(e){let t=new Uint8Array(32).fill(0);if(!e)return yt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=G9(r[n]),s=o?un(o):Pt(zo(r[n]),"bytes");t=Pt(en([t,s]),"bytes")}return yt(t)}var Y9=b(()=>{l();Fn();Pr();qe();Ks();kL()});function kie(e){return`[${e.slice(2)}]`}var Uie=b(()=>{l()});function J9(e){let t=new Uint8Array(32).fill(0);return e?G9(e)||Pt(zo(e)):yt(t)}var UL=b(()=>{l();Pr();qe();Ks();kL()});function e6(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(zo(t).byteLength+2),n=0,o=t.split(".");for(let s=0;s255&&(i=zo(kie(J9(o[s])))),r[n]=i.length,r.set(i,n+1),n+=i.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}var Q9=b(()=>{l();Pr();Uie();UL()});async function Die(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:s,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(p=>s.endsWith(p)))return null;let f=o!=null?[Vg(s),BigInt(o)]:[Vg(s)];try{let p=Wt({abi:fL,functionName:"addr",args:f}),h={address:u,abi:b9,functionName:"resolveWithGateways",args:[wr(e6(s)),p,i??[Ia]],blockNumber:r,blockTag:n},w=await ue(e,er,"readContract")(h);if(w[0]==="0x")return null;let x=QDe({coinType:o,data:w[0],args:f});return x==="0x"||bn(x)==="0x00"?null:x}catch(p){if(a)throw p;if(Xb(p))return null;throw p}}function QDe({coinType:e,data:t,args:r}){try{return dn({abi:fL,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=20,s=32,i=bn(t),a=gt(i),c=gt(t);if((e===60n||e>=0x80000000n&&e<=0xffffffffn)&&(c===o||c===s)&&a{l();So();lc();us();Zs();K0();Xa();Fo();Hh();qe();Z9();qb();Y9();Q9();_t();oi()});function tLe(e,t={}){let{pad:r=!0,url:n=!1}=t,o=new Uint8Array(Math.ceil(e.length/3)*4);for(let c=0,u=0;u>18],o[c+1]=X9[d>>12&63],o[c+2]=X9[d>>6&63],o[c+3]=X9[d&63]}let s=e.length%3,i=Math.floor(e.length/3)*4+(s&&s+1),a=eLe.decode(new Uint8Array(o.buffer,0,i));return r&&s===1&&(a+="=="),r&&s===2&&(a+="="),n&&(a=a.replaceAll("+","-").replaceAll("/","_")),a}function Mie(e,t={}){return tLe(Mb(e),t)}function rLe(e){let t=e.replace(/=+$/,""),r=t.length,n=new Uint8Array(r+3);XDe.encodeInto(t+"===",n);for(let s=0,i=0;s>16,n[i+1]=a>>8&255,n[i+2]=a&255}let o=(r>>2)*3+(r%4&&r%4-1);return new Uint8Array(n.buffer,0,o)}function Hie(e){return d9(rLe(e))}var XDe,eLe,X9,eT,DL=b(()=>{l();mu();XDe=new TextEncoder,eLe=new TextDecoder,X9=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),eT={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var tT,xu,om,t6,r6,rT=b(()=>{l();nt();tT=class extends G{constructor({data:t}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(t)}`],name:"EnsAvatarInvalidMetadataError"})}},xu=class extends G{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}},om=class extends G{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}},t6=class extends G{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}},r6=class extends G{constructor({chainId:t}){super(`Invalid ENSIP-11 chainId: ${t}. Must be between 0 and 0x7fffffff, or 1.`,{name:"EnsInvalidChainIdError"})}}});async function cLe(e,{timeout:t=zie}={}){try{let r=await sl(({signal:n})=>fetch(e,{method:"HEAD",...n?{signal:n}:{}}),{errorInstance:new ds({body:{},url:e}),signal:!0,timeout:t});return r.status===200?r.headers.get("content-type")?.startsWith("image/"):!1}catch(r){return r instanceof ds||typeof r=="object"&&typeof r.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(n=>{let o=new Image;o.onload=()=>{n(!0)},o.onerror=()=>{n(!1)},o.src=e})}}function Fie(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function LL({uri:e,gatewayUrls:t}){let r=sLe.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=Fie(t?.ipfs,"https://ipfs.io"),o=Fie(t?.arweave,"https://arweave.net"),s=e.match(nLe),{protocol:i,subpath:a,target:c,subtarget:u=""}=s?.groups||{},d=i==="ipns:/"||a==="ipns/",f=i==="ipfs:/"||a==="ipfs/"||oLe.test(e);if(e.startsWith("http")&&!d&&!f){let h=e;return t?.arweave&&(h=e.replace(/https:\/\/arweave.net/g,t?.arweave)),{uri:h,isOnChain:!1,isEncoded:!1}}if((d||f)&&c)return{uri:`${n}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(i==="ar:/"&&c)return{uri:`${o}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(iLe,"");if(p.startsWith("{let i=await fetch(r,s?{signal:s}:{});return Wb(i,{maxResponseBodySize:aLe})},{errorInstance:new ds({body:{},url:r}),signal:!0,timeout:t});return await nT({gatewayUrls:e,uri:ML(JSON.parse(n))})}catch{throw new om({uri:r})}}async function nT({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=LL({uri:t,gatewayUrls:e});if(n||await cLe(r))return r;throw new om({uri:t})}function jie(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));let[r,n,o]=t.split("/"),[s,i]=r.split(":"),[a,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new xu({reason:"Only EIP-155 supported"});if(!i)throw new xu({reason:"Chain ID not found"});if(!c)throw new xu({reason:"Contract address not found"});if(!o)throw new xu({reason:"Token ID not found"});if(!a)throw new xu({reason:"ERC namespace not found"});return{chainID:Number.parseInt(i,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function qie(e,{nft:t}){if(t.namespace==="erc721")return er(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return er(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new t6({namespace:t.namespace})}function Wie({nft:e,uri:t}){let r=e.namespace==="erc1155"?oe(BigInt(e.tokenID),{size:32}).slice(2):e.tokenID;return t.replace(/(?:0x)?{id}/,r)}var nLe,oLe,sLe,iLe,zie,aLe,Kie=b(()=>{l();DL();oi();rT();fs();qe();N9();Kb();nLe=/(?https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,oLe=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,sLe=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,iLe=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/,zie=1e4,aLe=10485760});async function Zie(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?lLe(e,{gatewayUrls:t,record:r}):nT({uri:r,gatewayUrls:t})}async function lLe(e,{gatewayUrls:t,record:r}){let n=jie(r),o=await qie(e,{nft:n}),{uri:s,isOnChain:i,isEncoded:a}=LL({uri:o,gatewayUrls:t});if(i&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){let c=a?Hie(s.replace("data:application/json;base64,","").replace(/\s/g,"")):s,u=JSON.parse(c);return nT({uri:ML(u),gatewayUrls:t})}return Vie({gatewayUrls:t,uri:Wie({nft:n,uri:s})})}var Gie=b(()=>{l();DL();Kie()});async function oT(e,t){let{blockNumber:r,blockTag:n,key:o,name:s,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(f=>s.endsWith(f)))return null;try{let f={address:u,abi:b9,args:[wr(e6(s)),Wt({abi:dL,functionName:"text",args:[Vg(s),o]}),i??[Ia]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await ue(e,er,"readContract")(f);if(h[0]==="0x")return null;let y=dn({abi:dL,functionName:"text",data:h[0]});return y===""?null:y}catch(f){if(a)throw f;if(Xb(f))return null;throw f}}var HL=b(()=>{l();So();lc();us();K0();qe();Z9();qb();Y9();Q9();_t();oi()});async function Yie(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:s,strict:i,universalResolverAddress:a}){let c=await ue(e,oT,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:s,strict:i});if(!c)return null;try{return await Zie(e,{record:c,gatewayUrls:n})}catch{return null}}var Jie=b(()=>{l();Gie();_t();HL()});async function Qie(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:s=60n,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let d={address:u,abi:lie,args:[r,s,i??[Ia]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},f=ue(e,er,"readContract"),[p]=await f(d);return p||null}catch(d){if(a)throw d;if(Xb(d))return null;throw d}}var Xie=b(()=>{l();So();K0();Z9();qb();_t();oi()});async function eae(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:s}=e,i=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return Ui({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),a=s?.ensTlds;if(a&&!a.some(u=>o.endsWith(u)))throw new Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);let[c]=await ue(e,er,"readContract")({address:i,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[wr(e6(o))],blockNumber:r,blockTag:n});return c}var tae=b(()=>{l();K0();qe();Q9();_t();oi()});async function rae(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:s,data:i,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,to:p,value:h,...y}=t,w=r?ft(r):void 0;try{jn(t);let v=(typeof n=="bigint"?oe(n):void 0)||o,T=e.chain?.formatters?.transactionRequest?.format,S=(T||Bn)({...Ri(y,{format:T}),account:w,blobs:s,data:i,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,to:p,value:h},"createAccessList"),_=await e.request({method:"eth_createAccessList",params:[S,v]});if(_.error)throw new G(_.error,{details:_.error});return{accessList:_.accessList,gasUsed:BigInt(_.gasUsed)}}catch(x){throw E9(x,{...t,account:w,chain:e.chain})}}var nae=b(()=>{l();tn();nt();qe();hL();P0();rl();nl()});async function oae(e){let t=Fh(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}var sae=b(()=>{l();N4()});async function sT(e,{address:t,args:r,event:n,events:o,fromBlock:s,strict:i,toBlock:a}={}){let c=o??(n?[n]:void 0),u=Fh(e,{method:"eth_newFilter"}),d=[];c&&(d=[c.flatMap(h=>nc({abi:[h],eventName:h.name,args:r}))],n&&(d=d[0]));let f=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?oe(s):s,toBlock:typeof a=="bigint"?oe(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:f,request:u(f),strict:!!i,toBlock:a,type:"event"}}var $L=b(()=>{l();Cg();qe();N4()});async function iT(e){let t=Fh(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}var FL=b(()=>{l();N4()});async function iae(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,u=Wt({abi:ki,functionName:"getEthBalance",args:[t]}),{data:d}=await ue(e,ms,"call")({to:c,data:u,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});return dn({abi:ki,functionName:"getEthBalance",args:[t],data:d||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,i]});return BigInt(a)}var aae=b(()=>{l();So();lc();us();B0();_t();G0()});async function cae(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var lae=b(()=>{l()});async function uae(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?oe(r):void 0,s=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:!!(t||o)});if(!s)throw new du({blockHash:t,blockNumber:r});let i=e.chain?.formatters?.transactionReceipt?.format||op;return s.map(a=>i(a,"getBlockReceipts"))}var dae=b(()=>{l();J4();qe();Qb()});async function fae(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?oe(r):void 0,s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:!!o}),wt(s)}var pae=b(()=>{l();Xr();qe()});async function jg(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),a=await e.request({method:"eth_getCode",params:[t,i]},{dedupe:typeof n=="bigint"||r!==void 0});if(a!=="0x")return a}var aT=b(()=>{l();B0()});async function hae(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await ue(e,jg,"getCode")({address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(o&>(o)===23&&o.startsWith("0xef0100"))return Gr(vo(o,3,23))}var mae=b(()=>{l();Zs();Fo();Si();_t();aT()});var cT,gae=b(()=>{l();nt();cT=class extends G{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}});async function yae(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[s,i,a,c,u,d,f]=await ue(e,er,"readContract")({abi:uLe,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:i,version:a,chainId:Number(c),verifyingContract:u,salt:d},extensions:f,fields:s}}catch(s){let i=s;throw i.name==="ContractFunctionExecutionError"&&i.cause.name==="ContractFunctionZeroDataError"?new cT({address:r}):i}}var uLe,wae=b(()=>{l();gae();_t();oi();uLe=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}]});function bae(e){return{baseFeePerGas:e.baseFeePerGas.map(t=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map(t=>t.map(r=>BigInt(r)))}}var xae=b(()=>{l()});async function vae(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let s=typeof r=="bigint"?oe(r):void 0,i=await e.request({method:"eth_feeHistory",params:[oe(t),s||n,o]},{dedupe:!!s});return bae(i)}var Eae=b(()=>{l();qe();xae()});async function Aae(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>qn(s));return t.abi?cc({abi:t.abi,eventName:t.eventName,logs:o,strict:r}):o}var Cae=b(()=>{l();Dg();hu()});function Sae(e,t){if(e.length!==t.length)throw new kh({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n{l();Qr();tc();Gs();Fn();Xa();qe();P4()});function I3(e){return!e||typeof e!="object"||!("BYTES_PER_ELEMENT"in e)?!1:e.BYTES_PER_ELEMENT===1&&e.constructor.name==="Uint8Array"}var zL=b(()=>{l()});function _ae(e){return e.opcode==="CREATE2"?jL(e):VL(e)}function VL(e){let t=un(Gr(e.from)),r=un(e.nonce);return r[0]===0&&(r=new Uint8Array([])),Gr(`0x${Pt(Vo([t,r],"bytes")).slice(26)}`)}function jL(e){let t=un(Gr(e.from)),r=Zr(I3(e.salt)?e.salt:un(e.salt),{size:32}),n="bytecodeHash"in e?I3(e.bytecodeHash)?e.bytecodeHash:un(e.bytecodeHash):Pt(e.bytecode,"bytes");return Gr(vo(Pt(en([un("0xff"),t,r,n])),12))}var Pae=b(()=>{l();Fn();zL();Xa();Si();Pr();wb();Ks();Zs()});function lT(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!Ft(o))throw new br({address:o});if(n<0)throw new Kf({chainId:n})}sm(e)}function uT(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new _b;for(let r of t){let n=gt(r),o=wt(vo(r,0,1));if(n!==32)throw new JI({hash:r,size:n});if(o!==1)throw new QI({hash:r,version:o})}}sm(e)}function sm(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new Kf({chainId:t});if(o&&!Ft(o))throw new br({address:o});if(n&&n>R0)throw new Pi({maxFeePerGas:n});if(typeof r=="bigint"&&typeof n=="bigint"&&r>n)throw new ac({maxFeePerGas:n,maxPriorityFeePerGas:r})}function n6(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(t<=0)throw new Kf({chainId:t});if(s&&!Ft(s))throw new br({address:s});if(r||o)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>R0)throw new Pi({maxFeePerGas:n})}function o6(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(s&&!Ft(s))throw new br({address:s});if(typeof t<"u"&&t<=0)throw new Kf({chainId:t});if(r||o)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>R0)throw new Pi({maxFeePerGas:n})}var dT=b(()=>{l();jI();tc();nt();YD();Ug();tl();Gs();Fo();Si();Xr()});function qg(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r{l();tc();zn();Gs()});function fT(e,t){let r=Pb(e);return r==="eip1559"?pLe(e,t):r==="eip2930"?hLe(e,t):r==="eip4844"?fLe(e,t):r==="eip7702"?dLe(e,t):mLe(e,t)}function dLe(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:s,to:i,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:f}=e;lT(e);let p=qg(d),h=Nae(r);return fr(["0x04",Vo([oe(n),s?oe(s):"0x",u?oe(u):"0x",c?oe(c):"0x",o?oe(o):"0x",i??"0x",a?oe(a):"0x",f??"0x",p,h,...s6(e,t)])])}function fLe(e,t){let{chainId:r,gas:n,nonce:o,to:s,value:i,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:f}=e;uT(e);let p=e.blobVersionedHashes,h=e.sidecars;if(e.blobs&&(typeof p>"u"||typeof h>"u")){let E=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(O=>yt(O)),S=e.kzg,_=D0({blobs:E,kzg:S});if(typeof p>"u"&&(p=Tb({commitments:_})),typeof h>"u"){let O=L0({blobs:E,commitments:_,kzg:S});h=M0({blobs:E,commitments:_,proofs:O})}}let y=qg(d),w=[oe(r),o?oe(o):"0x",u?oe(u):"0x",c?oe(c):"0x",n?oe(n):"0x",s??"0x",i?oe(i):"0x",f??"0x",y,a?oe(a):"0x",p??[],...s6(e,t)],x=[],v=[],T=[];if(h)for(let E=0;E{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new Kh({v:t.v});return h})(),f=bn(t.r),p=bn(t.s);u=[...u,oe(d),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(u=[...u,oe(r),"0x","0x"]);return Vo(u)}function s6(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let s=bn(r.r),i=bn(r.s);return[typeof o=="number"?o?oe(1):"0x":n===0n?"0x":n===1n?oe(1):n===27n?"0x":oe(1),s==="0x00"?"0x":s,i==="0x00"?"0x":i]}var pT=b(()=>{l();zn();Rae();t3();r3();GI();n3();Fn();Hh();qe();wb();dT();e9();qL()});function Nae(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...s}=r,i=r.address,a=s6({},s);a.length>0&&s.yParity&&(a[0]=wr(s.yParity)),t.push([n?wr(n):"0x",i,o?wr(o):"0x",...a])}return t}var Rae=b(()=>{l();qe();pT()});async function Oae({address:e,authorization:t,signature:r}){let n=await(async()=>{try{return await b0({authorization:t,signature:r})}catch(o){if(o instanceof tu)return;throw o}})();return n?xr(Gr(e),n):!1}var Bae=b(()=>{l();zn();Zs();Oi();Z4()});function kae(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(hT.get(r))return hT.get(r);let n=e().finally(()=>hT.delete(r));return hT.set(r,n),n}var hT,Uae=b(()=>{l();_f();hT=new xo(8192)});function Dae(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:s,retryDelay:i=150,retryCount:a=3,signal:c,uid:u}={...t,...n},{method:d}=r;if(s?.exclude?.includes(d))throw new Aa(new Error("method not supported"),{method:d});if(s?.include&&!s.include.includes(d))throw new Aa(new Error("method not supported"),{method:d});if(c?.aborted)throw Nn(c);let f=o?yLe(`${u}.${bt(r)}`):void 0;return kae(()=>np(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(p){if(c?.aborted)throw Nn(c);if(Ii(p))throw p;let h=p;switch(h.code){case Yh.code:throw new Yh(h);case Jh.code:throw new Jh(h);case Jc.code:throw new Jc(h,{method:r.method});case Qh.code:throw new Qh(h);case Qc.code:throw new Qc(h);case Ti.code:throw new Ti(h);case Xh.code:throw new Xh(h);case e0.code:throw new e0(h);case iu.code:throw new iu(h);case Aa.code:throw new Aa(h,{method:r.method});case Df.code:throw new Df(h);case t0.code:throw new t0(h);case Xc.code:throw new Xc(h);case r0.code:throw new r0(h);case n0.code:throw new n0(h);case o0.code:throw new o0(h);case s0.code:throw new s0(h);case i0.code:throw new i0(h);case au.code:throw new au(h);case a0.code:throw new a0(h);case c0.code:throw new c0(h);case l0.code:throw new l0(h);case u0.code:throw new u0(h);case d0.code:throw new d0(h);case cu.code:throw new cu(h);case 5e3:throw new Xc(h);case f0.code:throw new f0(h);default:throw p instanceof G?p:new ub(h)}}},{delay:({count:p,error:h})=>{let y=Lae(h)?.headers?.get("Retry-After");if(y){let w=Number.parseInt(y,10);if(!Number.isNaN(w))return w*1e3;let x=Date.parse(y)-Date.now();if(x>0)return x}return~~(1<gLe(p)}),{enabled:o,id:f})}}function gLe(e){if(Ii(e))return!1;let t=Lae(e)?.status;if("code"in e&&typeof e.code=="number"){if(e.code===-1||e.code===Df.code||e.code===Qc.code||e.code===429||e.code===-32007)return!0;if(e.code===Jc.code||e.code===Aa.code||!t)return!1}return t?t===403||t===408||t===413||t===429||t===500||t===502||t===503||t===504:!0}function Lae(e){if(e instanceof G)return e.walk(t=>t instanceof Nr||t instanceof Rn)}function yLe(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}var Mae=b(()=>{l();nt();fs();Lf();oc();Uae();v3();so()});function Hae({batchGateways:e,ccipRequest:t=Hg}){return{async request({data:r,requestOptions:n,sender:o,timeout:s,urls:i}){if(i.includes(Ia))return t({data:r,requestOptions:n,sender:o,timeout:s,urls:e});{let[a,c]=dn({abi:W0,functionName:"query",data:await t({data:Wt({abi:W0,functionName:"query",args:[[{sender:o,data:r,urls:i}]]}),requestOptions:n,sender:o,timeout:s,urls:e})});if(a[0]){let u;try{let d=Vh({abi:[...W0,Gw],data:c[0]});if(d.errorName==="HttpError")u=new Nr({body:{message:d.args[1]},status:d.args[0],url:i.join(" | ")});else{let f=d.args[0];f&&(u=new Error(f))}}catch{}throw u??new Error("An unknown error occurred.")}return c[0]}}}}var $ae=b(()=>{l();So();R4();fs();L4();lc();us();k9();qb()});function Fae(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return o=>{let s=typeof o=="function"?o(n):o,i={...n,...s};return Object.assign(i,{extend:r(i)})}}return Object.assign(t,{extend:r(t)})}function zae(){return{}}var Vae=b(()=>{l()});function jae({chains:e,id:t}){return e.find(r=>r.id===t)}var qae=b(()=>{l()});function Wg(e,t="hex"){let r=(()=>{if(typeof e=="string"){if(e.length>3&&e.length%2!==0)throw new $w(e);return qt(e)}return e})(),n=Zc(r,{recursiveReadLimit:Number.POSITIVE_INFINITY}),o=Zae(n,t);if(n.position=Wae)throw new Fw({limit:Wae});if(e.bytes.length===0)return t==="hex"?yt(e.bytes):e.bytes;let n=e.readByte();if(n<128&&e.decrementPosition(1),n<192){let s=Kae(e,n,128),i=e.readBytes(s);return t==="hex"?yt(i):i}let o=Kae(e,n,192);return wLe(e,o,t,r+1)}function Kae(e,t,r){if(r===128&&t<128)return 1;if(t<=r+55)return t-r;if(t===r+55+1)return e.readUint8();if(t===r+55+2)return e.readUint16();if(t===r+55+3)return e.readUint24();if(t===r+55+4)return e.readUint32();throw new G("Invalid RLP prefix")}function wLe(e,t,r,n){let o=e.position,s=[];for(;e.position-o{l();nt();yg();Jw();Pr();qe();Wae=1024});function i6(e){return We(e)&&e.length===66}var gT=b(()=>{l();qs()});function Gae(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}var bLe,Yae,xLe,Jae,Qae,Xae,ece,vLe,ELe,ALe,CLe,yT,wT,tce,rce=b(()=>{l();hD();Tf();bLe=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Yae=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),xLe=Yae.map(e=>(9*e+5)%16),Jae=(()=>{let r=[[Yae],[xLe]];for(let n=0;n<4;n++)for(let o of r)o.push(o[n].map(s=>bLe[s]));return r})(),Qae=Jae[0],Xae=Jae[1],ece=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),vLe=Qae.map((e,t)=>e.map(r=>ece[t][r])),ELe=Xae.map((e,t)=>e.map(r=>ece[t][r])),ALe=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),CLe=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);yT=new Uint32Array(16),wT=class extends db{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:t,h1:r,h2:n,h3:o,h4:s}=this;return[t,r,n,o,s]}set(t,r,n,o,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=o|0,this.h4=s|0}process(t,r){for(let h=0;h<16;h++,r+=4)yT[h]=t.getUint32(r,!0);let n=this.h0|0,o=n,s=this.h1|0,i=s,a=this.h2|0,c=a,u=this.h3|0,d=u,f=this.h4|0,p=f;for(let h=0;h<5;h++){let y=4-h,w=ALe[h],x=CLe[h],v=Qae[h],T=Xae[h],E=vLe[h],S=ELe[h];for(let _=0;_<16;_++){let O=S4(n+Gae(h,s,a,u)+yT[v[_]]+w,E[_])+f|0;n=f,f=u,u=S4(a,10)|0,a=s,s=O}for(let _=0;_<16;_++){let O=S4(o+Gae(y,i,c,d)+yT[T[_]]+x,S[_])+p|0;o=p,p=d,d=S4(c,10)|0,c=i,i=O}}this.set(this.h1+a+d|0,this.h2+u+p|0,this.h3+f+o|0,this.h4+n+i|0,this.h0+s+c|0)}roundClean(){ba(yT)}destroy(){this.destroyed=!0,ba(this.buffer),this.set(0,0,0,0,0)}},tce=Ww(()=>new wT)});var nce,oce=b(()=>{l();rce();nce=tce});function sce(e,t){let r=t||"hex",n=nce(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var ice=b(()=>{l();oce();qs();Pr();qe()});var ace=b(()=>{l();T4()});var cce=b(()=>{l();SI()});var lce=b(()=>{l();T4()});var uce=b(()=>{l();SI()});function WL(e){let{source:t}=e,r=new Map,n=new xo(8192),o=new Map,s=({address:a,chainId:c})=>`${a}.${c}`,i=a=>{r.delete(a),o.delete(a)};return{async consume({address:a,chainId:c,client:u}){let d=s({address:a,chainId:c}),f=this.get({address:a,chainId:c,client:u});this.increment({address:a,chainId:c});let p=await f;return await t.set({address:a,chainId:c},p),n.set(d,p),p},async increment({address:a,chainId:c}){let u=s({address:a,chainId:c}),d=r.get(u)??0;r.set(u,d+1)},async get({address:a,chainId:c,client:u}){let d=s({address:a,chainId:c}),f=o.get(d);return f||(f=(async()=>{try{let h=await t.get({address:a,chainId:c,client:u}),y=n.get(d);return y!==void 0&&h<=y?y+1:(n.delete(d),h)}finally{i(d)}})(),o.set(d,f)),(r.get(d)??0)+await f},reset({address:a,chainId:c}){let u=s({address:a,chainId:c});n.delete(u),i(u)}}}function SLe(){return{async get(e){let{address:t,client:r}=e;return k0(r,{address:t,blockTag:"pending"})},set(){}}}var dce,fce=b(()=>{l();e3();_f();dce=WL({source:SLe()})});function ILe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var a6,KL=b(()=>{l();a6=ILe()});function mce(e,t={}){let{url:r,headers:n}=_Le(e);return{async request(o){let{body:s,fetchFn:i=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??TLe,onRequest:c=t.onRequest,onResponse:u=t.onResponse,timeout:d=t.timeout??1e4}=o,f={...t.fetchOptions??{},...o.fetchOptions??{}},{headers:p,method:h,signal:y}=f;try{let{response:w,responseBody:x}=await sl(async({signal:E})=>{let{signal:S,cleanup:_}=P9([y,d>0?E:null]);try{let O={};for(let P of[n,{"Content-Type":"application/json"},p])new Headers(P).forEach((R,I)=>{O[I]=R});let D={...f,body:Array.isArray(s)?bt(s.map(P=>({jsonrpc:"2.0",id:P.id??a6.take(),...P}))):bt({jsonrpc:"2.0",id:s.id??a6.take(),...s}),headers:O,method:h||"POST",signal:S},M=(c&&await c(new Request(r,D),D))??{...D,url:r},N=await i(M.url??r,M);u&&await u(N);let L=await Wb(N,{maxResponseBodySize:a});return{response:N,responseBody:L}}finally{_()}},{errorInstance:pce,timeout:d,signal:!0}),v;if(w.headers.get("Content-Type")?.startsWith("application/json"))v=JSON.parse(x);else{v=x;try{v=JSON.parse(v||"{}")}catch(E){if(w.ok)throw E;v={error:v}}}let T=Array.isArray(s)&&Array.isArray(v)&&v.length===1?v[0]:v;if(!w.ok)throw hce(T)?new Rn({body:s,error:T.error,headers:w.headers,status:w.status,url:r}):new Nr({body:s,details:bt(v.error)||w.statusText,headers:w.headers,status:w.status,url:r});if(!Array.isArray(s)||!s.length||Array.isArray(v)&&v.length>=s.length)return v;if(!hce(T))throw new Error(`Expected ${s.length} responses to batch request.`);return s.map(()=>T)}catch(w){throw y?.aborted?Nn(y):w===pce?new ds({body:s,url:r}):Ii(w)||w instanceof Nr||w instanceof ic||w instanceof Rn||w instanceof ds?w:new Nr({body:s,cause:w,url:r})}}}}function hce(e){return typeof e?.error?.code=="number"&&typeof e?.error?.message=="string"}function _Le(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:t.toString(),...r}}catch{return{url:e}}}var TLe,pce,gce=b(()=>{l();fs();oc();N9();Kb();so();KL();TLe=10485760,pce=new Error("timed out")});async function wce(e){let{getSocket:t,keepAlive:r=!0,key:n="socket",reconnect:o=!0,url:s}=e,{interval:i=3e4}=typeof r=="object"?r:{},{attempts:a=5,delay:c=2e3}=typeof o=="object"?o:{},u=JSON.stringify({keepAlive:r,key:n,url:s,reconnect:o}),d=ZL.get(u);if(d)return d;let f=0,{schedule:p}=Z0({id:u,fn:async()=>{let w=new Map,x=new Map,v,T,E,S,_=!1,O=!1;function D(){if(o&&!O&&f{if(S=void 0,O){_=!1;return}await M().catch(console.error),_=!1},c)}else w.clear(),x.clear()}async function M(){let N=await t({onClose(){for(let L of w.values())L.onError?.(new su({url:s}));for(let L of x.values())L.onError?.(new su({url:s}));D()},onError(L){v=L;for(let P of w.values())P.onError?.(v);for(let P of x.values())P.onError?.(v);D()},onOpen(){v=void 0,f=0},onResponse(L){let P=L.method==="eth_subscription",R=P?L.params.subscription:L.id,I=P?x:w,B=I.get(R);B&&B.onResponse(L),P||I.delete(R)}});if(O)return N.close(),N;if(T=N,r&&(E&&clearInterval(E),E=setInterval(()=>T.ping?.(),i)),o&&x.size>0){let L=x.entries();for(let[P,{onResponse:R,body:I,onError:B}]of L)I&&(x.delete(P),d?.request({body:I,onResponse:R,onError:B}))}return N}return await M(),v=void 0,d={close(){O=!0,E&&clearInterval(E),S&&(clearTimeout(S),S=void 0,_=!1),T.close(),ZL.delete(u)},get socket(){return T},request({body:N,onError:L,onResponse:P}){v&&L&&L(v);let R=N.id??a6.take(),I=B=>{typeof B.id=="number"&&R!==B.id||(N.method==="eth_subscribe"&&typeof B.result=="string"&&x.set(B.result,{onResponse:P,onError:L,body:N}),P(B))};N.method==="eth_unsubscribe"&&x.delete(N.params?.[0]),w.set(R,{onResponse:I,onError:L});try{T.request({body:{jsonrpc:"2.0",id:R,...N}})}catch(B){L?.(B)}},async requestAsync({body:N,timeout:L=1e4}){let P=N.id??a6.take();try{return await sl(()=>new Promise((R,I)=>this.request({body:{...N,id:P},onError:I,onResponse:R})),{errorInstance:yce,timeout:L})}catch(R){throw R===yce?new ds({body:N,url:s}):R}finally{w.delete(P)}},requests:w,subscriptions:x,url:s},ZL.set(u,d),[d]}}),[h,[y]]=await p();return y}var ZL,yce,bce=b(()=>{l();fs();h3();Kb();KL();ZL=new Map,yce=new Error("timed out")});function xce(){if(typeof m<"u")return m;if(typeof global.WebSocket<"u")return global.WebSocket;if(typeof window.WebSocket<"u")return window.WebSocket;if(typeof self.WebSocket<"u")return self.WebSocket;throw new Error("`WebSocket` is not supported in this environment")}var vce=b(()=>{l()});var Ece={};Te(Ece,{WebSocket:()=>PLe});var PLe,Ace=b(()=>{l();vce();PLe=xce()});async function c6(e,t={}){let{keepAlive:r,reconnect:n}=t;return wce({async getSocket({onClose:o,onError:s,onOpen:i,onResponse:a}){let c=await Promise.resolve().then(()=>(Ace(),Ece)).then(h=>h.WebSocket),u=new c(e);function d(){u.removeEventListener("close",d),u.removeEventListener("message",f),u.removeEventListener("error",s),u.removeEventListener("open",i),o()}function f({data:h}){if(!(typeof h=="string"&&h.trim().length===0))try{let y=JSON.parse(h);a(y)}catch(y){s(y)}}u.addEventListener("close",d),u.addEventListener("message",f),u.addEventListener("error",s),u.addEventListener("open",i),u.readyState===c.CONNECTING&&await new Promise((h,y)=>{u&&(u.onopen=h,u.onerror=y)});let{close:p}=u;return Object.assign(u,{close(){p.bind(u)(),d()},ping(){try{if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new _g({url:u.url,cause:new su({url:u.url})});let h={jsonrpc:"2.0",id:null,method:"net_version",params:[]};u.send(JSON.stringify(h))}catch(h){s(h)}},request({body:h}){if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new _g({body:h,url:u.url,cause:new su({url:u.url})});return u.send(JSON.stringify(h))}})},keepAlive:r,reconnect:n,url:e})}var GL=b(()=>{l();fs();bce()});async function Cce(e){let t=await c6(e);return Object.assign(t.socket,{requests:t.requests,subscriptions:t.subscriptions})}var Sce=b(()=>{l();GL()});var bT,YL=b(()=>{l();bT=`Ethereum Signed Message: -`});function xT(e){let t=typeof e=="string"?ec(e):typeof e.raw=="string"?e.raw:yt(e.raw),r=ec(`${bT}${gt(t)}`);return en([r,t])}var JL=b(()=>{l();YL();Fn();Fo();qe()});function im(e,t){return Pt(xT(e),t)}var T3=b(()=>{l();Ks();JL()});var l6,u6,d6,Kg,QL=b(()=>{l();so();nt();l6=class extends G{constructor({domain:t}){super(`Invalid domain "${bt(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."],name:"InvalidDomainError"})}},u6=class extends G{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."],name:"InvalidPrimaryTypeError"})}},d6=class extends G{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:['Struct type must contain only letters, digits, "_", "$" and ":", and must not be a Solidity type.'],name:"InvalidStructTypeError"})}},Kg=class extends G{constructor({type:t}){let r=/^u?int(\[[0-9]*\])*$/.test(t);super(`Type "${t}" is not a valid EIP-712 type.`,{metaMessages:r?[`Use "${t.replace(/^(u?int)/,"$&256")}" instead.`]:void 0,name:"InvalidTypedDataTypeError"})}}});function vT(e){let{domain:t,message:r,primaryType:n,types:o}=e,s=(c,u)=>{let d={...u};for(let f of c){let{name:p,type:h}=f;h==="address"&&(d[p]=d[p].toLowerCase())}return d},i=o.EIP712Domain?t?s(o.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return s(o[n],r)})();return bt({domain:i,message:a,primaryType:n,types:o})}function f6(e){let{domain:t,message:r,primaryType:n,types:o}=e,s=(i,a)=>{for(let c of i){let{name:u,type:d}=c,f=a[u],p=d.match(Rf);if(p&&(typeof f=="number"||typeof f=="bigint")){let[y,w,x]=p;oe(f,{signed:w==="int",size:Number.parseInt(x,10)/8})}if(d==="address"&&typeof f=="string"&&!Ft(f))throw new br({address:f});let h=d.match(Eg);if(h){let[y,w]=h;if(w&>(f)!==Number.parseInt(w,10))throw new Lh({expectedSize:Number.parseInt(w,10),givenSize:gt(f)})}Object.hasOwn(o,d)&&s(o[d],f)}};for(let i of Object.keys(o))OLe(i);for(let i of Object.values(o))for(let a of i??[])NLe(a.type,o);if(o.EIP712Domain&&t){if(typeof t!="object")throw new l6({domain:t});s(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])s(o[n],r);else throw new u6({primaryType:n,types:o})}function Zg({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},typeof e?.version=="string"&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function Ice({domain:e}){return _3({domain:e,types:{EIP712Domain:Zg({domain:e})}})}function NLe(e,t){let r=e.replace(/(\[[0-9]*\])+$/,"");if(r==="int"||r==="uint")throw new Kg({type:e});if(!Object.hasOwn(t,r)&&!RLe(r))throw new Kg({type:e})}function RLe(e){return e==="address"||e==="bool"||e==="string"||Eg.test(e)||Rf.test(e)}function OLe(e){if(!/^[A-Za-z0-9_$:]+$/.test(e)||e==="address"||e==="bool"||e==="string"||/^(u?int|bytes)[0-9]*$/.test(e))throw new d6({type:e})}var ET=b(()=>{l();Qr();tc();QL();Gs();Fo();qe();P4();P3();so()});function p6(e){let{domain:t={},message:r,primaryType:n}=e,o={EIP712Domain:Zg({domain:t}),...e.types};f6({domain:t,message:r,primaryType:n,types:o});let s=["0x1901"];return t&&s.push(_3({domain:t,types:o})),n!=="EIP712Domain"&&s.push(AT({data:r,primaryType:n,types:o})),Pt(en(s))}function _3({domain:e,types:t}){return AT({data:e,primaryType:"EIP712Domain",types:t})}function AT({data:e,primaryType:t,types:r}){let n=Tce({data:e,primaryType:t,types:r});return Pt(n)}function Tce({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],o=[BLe({primaryType:t,types:r})];for(let s of r[t]){let[i,a]=Pce({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(i),o.push(a)}return oo(n,o)}function BLe({primaryType:e,types:t}){let r=wr(kLe({primaryType:e,types:t}));return Pt(r)}function kLe({primaryType:e,types:t}){let r="",n=_ce({primaryType:e,types:t});n.delete(e);let o=[e,...Array.from(n).sort()];for(let s of o)r+=`${s}(${t[s].map(({name:i,type:a})=>`${a} ${i}`).join(",")})`;return r}function _ce({primaryType:e,types:t},r=new Set){let n=e.replace(/(\[[0-9]*\])+$/,"");if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let o of t[n])_ce({primaryType:o.type,types:t},r);return r}function Pce({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},Pt(Tce({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},Pt(n)];if(r==="string")return[{type:"bytes32"},Pt(wr(n))];if(r.lastIndexOf("]")===r.length-1){let o=r.slice(0,r.lastIndexOf("[")),s=n.map(i=>Pce({name:t,type:o,types:e,value:i}));return[{type:"bytes32"},Pt(oo(s.map(([i])=>i),s.map(([,i])=>i)))]}return[{type:r},n]}var P3=b(()=>{l();rc();Fn();qe();Ks();ET()});var CT,Nce,ST=b(()=>{l();CT="0x6492649264926492649264926492649264926492649264926492649264926492",Nce="0x0000000000000000000000000000000000000000000000000000000000000000"});function IT(e){return xa(e,-32)===CT}var XL=b(()=>{l();ST();Si()});var N3,Rce=b(()=>{l();N3=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});var R3,eM=b(()=>{l();Rce();R3={checksum:new N3(8192),signatureHash:new N3(8192)}});var TT,Oce=b(()=>{l();eM();TT=R3.checksum});function Gg(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=CI(aL(e));return r==="Bytes"?n:vn(n)}var _T=b(()=>{l();JU();mu();io()});function Bce(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new PT({prefix:n,cause:new oM});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new PT({prefix:n,cause:new nM});return}throw new rM({publicKey:e})}function kce(e){let t=(()=>{if(q0(e))return Uce(e);if(oie(e))return DLe(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return Bce(t),t}function DLe(e){return Uce(vn(e))}function Uce(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new sM({publicKey:e});if(e.length===130){let n=BigInt(rn(e,0,32)),o=BigInt(rn(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(rn(e,0,1)),o=BigInt(rn(e,1,33)),s=BigInt(rn(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(rn(e,0,1)),r=BigInt(rn(e,1,33));return{prefix:t,x:r}}function iM(e,t={}){Bce(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return fn(s?Yt(r,{size:1}):"0x",Yt(n,{size:32}),typeof o=="bigint"?Yt(o,{size:32}):"0x")}var rM,PT,nM,oM,sM,aM=b(()=>{l();mu();Bi();io();d3();rM=class extends Ke{constructor({publicKey:t}){super(`Value \`${z0(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},PT=class extends Ke{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},nM=class extends Ke{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},oM=class extends Ke{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},sM=class extends Ke{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Mr(Hb(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});function Yg(e,t={}){let{strict:r=!0}=t;if(!LLe.test(e))throw new h6({address:e,cause:new O3});if(r){if(e.toLowerCase()===e)return;if(NT(e)!==e)throw new h6({address:e,cause:new cM})}}function NT(e){if(TT.has(e))return TT.get(e);Yg(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=Gg(Mb(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return TT.set(e,o),o}function MLe(e,t={}){let{checksum:r=!1}=t;return Yg(e),r?NT(e):e}function Lce(e,t={}){let r=Gg(`0x${iM(e).slice(4)}`).substring(26);return MLe(`0x${r}`,t)}function lM(e,t={}){let{strict:r=!0}=t??{};try{return Yg(e,{strict:r}),!0}catch{return!1}}var LLe,h6,O3,cM,B3=b(()=>{l();mu();Oce();Bi();_T();aM();LLe=/^0x[a-fA-F0-9]{40}$/;h6=class extends Ke{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},O3=class extends Ke{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},cM=class extends Ke{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});var Mce,Hce,OT,AOt,COt,SOt,IOt,TOt,_Ot,POt,NOt,ROt,OOt,BOt,kOt,UOt,DOt,LOt,MOt,HOt,$Ot,FOt,zOt,VOt,jOt,qOt,WOt,KOt,ZOt,GOt,YOt,JOt,QOt,XOt,eBt,tBt,rBt,nBt,oBt,sBt,iBt,aBt,cBt,lBt,uBt,dBt,fBt,pBt,hBt,mBt,gBt,yBt,wBt,bBt,xBt,vBt,EBt,ABt,CBt,SBt,IBt,TBt,_Bt,PBt,NBt,RBt,OBt,BBt,kBt,UBt,DBt,LBt,MBt,HBt,$Bt,FBt,zBt,VBt,jBt,qBt,WBt,KBt,ZBt,GBt,YBt,JBt,QBt,XBt,ekt,tkt,rkt,nkt,okt,skt,ikt,akt,ckt,lkt,uM,BT=b(()=>{l();Mce=/^(.*)\[([0-9]*)\]$/,Hce=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,OT=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,AOt=2n**(8n-1n)-1n,COt=2n**(16n-1n)-1n,SOt=2n**(24n-1n)-1n,IOt=2n**(32n-1n)-1n,TOt=2n**(40n-1n)-1n,_Ot=2n**(48n-1n)-1n,POt=2n**(56n-1n)-1n,NOt=2n**(64n-1n)-1n,ROt=2n**(72n-1n)-1n,OOt=2n**(80n-1n)-1n,BOt=2n**(88n-1n)-1n,kOt=2n**(96n-1n)-1n,UOt=2n**(104n-1n)-1n,DOt=2n**(112n-1n)-1n,LOt=2n**(120n-1n)-1n,MOt=2n**(128n-1n)-1n,HOt=2n**(136n-1n)-1n,$Ot=2n**(144n-1n)-1n,FOt=2n**(152n-1n)-1n,zOt=2n**(160n-1n)-1n,VOt=2n**(168n-1n)-1n,jOt=2n**(176n-1n)-1n,qOt=2n**(184n-1n)-1n,WOt=2n**(192n-1n)-1n,KOt=2n**(200n-1n)-1n,ZOt=2n**(208n-1n)-1n,GOt=2n**(216n-1n)-1n,YOt=2n**(224n-1n)-1n,JOt=2n**(232n-1n)-1n,QOt=2n**(240n-1n)-1n,XOt=2n**(248n-1n)-1n,eBt=2n**(256n-1n)-1n,tBt=-(2n**(8n-1n)),rBt=-(2n**(16n-1n)),nBt=-(2n**(24n-1n)),oBt=-(2n**(32n-1n)),sBt=-(2n**(40n-1n)),iBt=-(2n**(48n-1n)),aBt=-(2n**(56n-1n)),cBt=-(2n**(64n-1n)),lBt=-(2n**(72n-1n)),uBt=-(2n**(80n-1n)),dBt=-(2n**(88n-1n)),fBt=-(2n**(96n-1n)),pBt=-(2n**(104n-1n)),hBt=-(2n**(112n-1n)),mBt=-(2n**(120n-1n)),gBt=-(2n**(128n-1n)),yBt=-(2n**(136n-1n)),wBt=-(2n**(144n-1n)),bBt=-(2n**(152n-1n)),xBt=-(2n**(160n-1n)),vBt=-(2n**(168n-1n)),EBt=-(2n**(176n-1n)),ABt=-(2n**(184n-1n)),CBt=-(2n**(192n-1n)),SBt=-(2n**(200n-1n)),IBt=-(2n**(208n-1n)),TBt=-(2n**(216n-1n)),_Bt=-(2n**(224n-1n)),PBt=-(2n**(232n-1n)),NBt=-(2n**(240n-1n)),RBt=-(2n**(248n-1n)),OBt=-(2n**(256n-1n)),BBt=2n**8n-1n,kBt=2n**16n-1n,UBt=2n**24n-1n,DBt=2n**32n-1n,LBt=2n**40n-1n,MBt=2n**48n-1n,HBt=2n**56n-1n,$Bt=2n**64n-1n,FBt=2n**72n-1n,zBt=2n**80n-1n,VBt=2n**88n-1n,jBt=2n**96n-1n,qBt=2n**104n-1n,WBt=2n**112n-1n,KBt=2n**120n-1n,ZBt=2n**128n-1n,GBt=2n**136n-1n,YBt=2n**144n-1n,JBt=2n**152n-1n,QBt=2n**160n-1n,XBt=2n**168n-1n,ekt=2n**176n-1n,tkt=2n**184n-1n,rkt=2n**192n-1n,nkt=2n**200n-1n,okt=2n**208n-1n,skt=2n**216n-1n,ikt=2n**224n-1n,akt=2n**232n-1n,ckt=2n**240n-1n,lkt=2n**248n-1n,uM=2n**256n-1n});function Jg(e,t,r){let{checksumAddress:n,staticPosition:o}=r,s=Qg(t.type);if(s){let[i,a]=s;return $Le(e,{...t,type:a},{checksumAddress:n,length:i,staticPosition:o})}if(t.type==="tuple")return jLe(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return HLe(e,{checksum:n});if(t.type==="bool")return FLe(e);if(t.type.startsWith("bytes"))return zLe(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return VLe(e,t);if(t.type==="string")return qLe(e,{staticPosition:o});throw new g6(t.type)}function HLe(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);for(let s=0;s<12;s++)if(n[s]!==0)throw new h6({address:vn(n),cause:new O3});return[(s=>r?NT(s):s)(vn(tie(n,-20))),32]}function $Le(e,t,r){let{checksumAddress:n,length:o,staticPosition:s}=r;if(o===null){let c=Xf(e.readBytes(dM)),u=s+c,d=u+Fce;e.setPosition(u);let f=Xf(e.readBytes(Fce)),p=m6(t),h=0,y=[];for(let w=0;ws||o48?o:Number(o),32]}function jLe(e,t,r){let{checksumAddress:n,staticPosition:o}=r,s=t.components.length===0||t.components.some(({name:c})=>!c),i=s?[]:{},a=0;if(m6(t)){let c=Xf(e.readBytes(dM)),u=o+c;for(let d=0;d0?fn(u,c):u}}if(i)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:fn(...a.map(({encoded:c})=>c))}}function ZLe(e,{type:t}){let[,r]=t.split("bytes"),n=Mr(e);if(!r){let o=e;return n%32!==0&&(o=j0(o,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:fn(ep(Yt(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new k3({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:j0(e)}}function GLe(e){if(typeof e!="boolean")throw new Ke(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ep(g9(e))}}function YLe(e,{signed:t,size:r}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||ei))}}function Qg(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function m6(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(m6);let r=Qg(e.type);return!!(r&&m6({...e,type:r[1]}))}var Fce,dM,pM=b(()=>{l();y6();B3();mu();Bi();io();BT();Fce=32,dM=32});function MT(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(eMe);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var eMe,LT,hM,mM,gM=b(()=>{l();Bi();eMe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new mM({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new hM({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new LT({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new LT({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};LT=class extends Ke{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}},hM=class extends Ke{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}},mM=class extends Ke{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}});function Xg(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,s=typeof t=="string"?Lg(t):t,i=MT(s);if(uc(s)===0&&e.length>0)throw new bM;if(uc(s)&&uc(s)<32)throw new wM({data:typeof t=="string"?t:vn(t),parameters:e,size:uc(s)});let a=0,c=n==="Array"?[]:{};for(let u=0;u{l();fg();B3();mu();Bi();io();pM();gM();BT();(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return Yg(c),ep(c.toLowerCase(),o?32:0)}if(r==="string")return $b(n);if(r==="bytes")return n;if(r==="bool")return ep(g9(n),o?32:1);let s=r.match(OT);if(s){let[c,u,d="256"]=s,f=Number.parseInt(d,10)/8;return Yt(n,{size:o?32:f,signed:u==="int"})}let i=r.match(Hce);if(i){let[c,u]=i;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new k3({expectedSize:Number.parseInt(u,10),value:n});return j0(n,o?32:0)}let a=r.match(Mce);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let f=0;fqce(t))):nMe(e)}function rMe(e){let t=e.reduce((o,s)=>o+s.length,0),r=Wce(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function nMe(e){let t=typeof e=="string"?Lg(e):e,r=Wce(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function Wce(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new Ke("Length is too large.")}var Kce=b(()=>{l();mu();Bi();io();gM()});function H3(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new L3({signature:e});if(typeof e.s>"u")throw new L3({signature:e});if(r&&typeof e.yParity>"u")throw new L3({signature:e});if(e.r<0n||e.r>uM)throw new vM({value:e.r});if(e.s<0n||e.s>uM)throw new EM({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new M3({value:e.yParity})}function sMe(e){return Zce(vn(e))}function Zce(e){if(e.length!==130&&e.length!==132)throw new xM({signature:e});let t=BigInt(rn(e,0,32)),r=BigInt(rn(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return IM(o)}catch{throw new M3({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function Gce(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return CM(e)}function CM(e){let t=typeof e=="string"?Zce(e):e instanceof Uint8Array?sMe(e):typeof e.r=="string"?SM(e):e.v?iMe(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return H3(t),t}function iMe(e){return{r:e.r,s:e.s,yParity:IM(e.v)}}function SM(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=IM(r)),typeof n!="number")throw new M3({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function IM(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new AM({value:e})}var xM,L3,vM,EM,M3,AM,TM=b(()=>{l();Bi();io();d3();BT();xM=class extends Ke{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Mr(Hb(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},L3=class extends Ke{constructor({signature:t}){super(`Signature \`${z0(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},vM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},EM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},M3=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},AM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}});function Jce(e,t={}){return typeof e.chainId=="string"?aMe(e):{...e,...t.signature}}function aMe(e){let{address:t,chainId:r,nonce:n}=e,o=SM(e);return H3({r:o.r,s:o.s}),Xce(o.yParity),{address:t,chainId:Number(r),nonce:BigInt(n),...o}}function Qce(e){return cMe(e,{presign:!0})}function cMe(e,t={}){let{presign:r}=t;return Gg(fn("0x05",jce(lMe(r?{address:e.address,chainId:e.chainId,nonce:e.nonce}:e))))}function lMe(e){let{address:t,chainId:r,nonce:n,r:o,s,yParity:i}=e,a=Gce({r:o,s});return a&&typeof i<"u"&&Xce(i),[r?Yt(r):"0x",t,n?Yt(n):"0x",...a?[i?Yt(i,{size:1}):"0x",a.r===0n?"0x":y9(Yt(a.r)),a.s===0n?"0x":y9(Yt(a.s))]:[]]}function Xce(e){if(!(Number.isInteger(e)&&e>=0&&e<256))throw new V0({max:"255",min:"0",signed:!1,size:1,value:`${e}`})}var ele=b(()=>{l();_T();io();Kce();TM()});function tle(e){return Lce(dMe(e))}function dMe(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new ei.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Hb(t).substring(2));return kce(a)}var Ekt,rle=b(()=>{l();Bg();B3();mu();io();aM();Ekt=Mb("ox.secp256k1.fromSeed.v1")});var il={};Te(il,{InvalidWrappedSignatureError:()=>$T,assert:()=>FT,from:()=>pMe,magicBytes:()=>_M,suffixParameters:()=>PM,unwrap:()=>nle,validate:()=>mMe,wrap:()=>hMe});function FT(e){if(typeof e=="string"){if(rn(e,-32)!==_M)throw new $T(e)}else H3(e.authorization)}function pMe(e){return typeof e=="string"?nle(e):e}function nle(e){FT(e);let t=f9(rn(e,-64,-32)),r=rn(e,-t-64,-64),n=rn(e,0,-t-64),[o,s,i]=Xg(PM,r);return{authorization:Jce({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...i&&i!=="0x"?{data:i,to:s}:{}}}function hMe(e){let{data:t,signature:r}=e;FT(e);let n=tle({payload:Qce(e.authorization),signature:CM(e.authorization)}),o=am(PM,[{...e.authorization,delegation:e.authorization.address,chainId:BigInt(e.authorization.chainId)},e.to??n,t??"0x"]),s=Yt(Mr(o),{size:32});return fn(r,o,s,_M)}function mMe(e){try{return FT(e),!0}catch{return!1}}var _M,PM,$T,ole=b(()=>{l();y6();ele();Bi();io();rle();TM();_M="0x8010801080108010801080108010801080108010801080108010801080108010",PM=D3("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");$T=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}});var $3=b(()=>{l();ole()});function zT(e){return il.validate(e)}var NM=b(()=>{l();$3()});function sle(e){if(!IT(e))return{signature:e};let[t,r,n]=Ys([{type:"address"},{type:"bytes"},{type:"bytes"}],e);return{address:t,data:r,signature:n}}var ile=b(()=>{l();zh();XL()});function ale(e){if(!zT(e))return{signature:e};let{authorization:t,to:r,...n}=il.unwrap(e);return{authorization:{address:t.address,chainId:t.chainId,nonce:Number(t.nonce),r:oe(t.r,{size:32}),s:oe(t.s,{size:32}),yParity:t.yParity},...r?{address:r}:{},...n}}var cle=b(()=>{l();$3();qe();NM()});async function VT({message:e,signature:t}){return ti({hash:im(e),signature:t})}var RM=b(()=>{l();T3();w0()});async function jT(e){let{domain:t,message:r,primaryType:n,signature:o,types:s}=e;return ti({hash:p6({domain:t,message:r,primaryType:n,types:s}),signature:o})}var OM=b(()=>{l();P3();w0()});function lle(e){let{address:t,data:r,signature:n,to:o="hex"}=e,s=fr([oo([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),CT]);return o==="hex"?s:qt(s)}var ule=b(()=>{l();ST();rc();Fn();Pr()});function dle(e){let{address:t,data:r,signature:n,to:o="hex"}=e,s=il.wrap({authorization:{address:e.authorization.address,chainId:e.authorization.chainId,nonce:BigInt(e.authorization.nonce),r:BigInt(e.authorization.r),s:BigInt(e.authorization.s),yParity:e.authorization.yParity},data:r,signature:n,to:t});return o==="hex"?s:qt(s)}var fle=b(()=>{l();$3();Pr()});async function ple({address:e,hash:t,signature:r}){return xr(Gr(e),await ti({hash:t,signature:r}))}var hle=b(()=>{l();Zs();Oi();w0()});async function mle({address:e,message:t,signature:r}){return xr(Gr(e),await VT({message:t,signature:r}))}var gle=b(()=>{l();Zs();Oi();RM()});async function yle(e){let{address:t,domain:r,message:n,primaryType:o,signature:s,types:i}=e;return xr(Gr(t),await jT({domain:r,message:n,primaryType:o,signature:s,types:i}))}var wle=b(()=>{l();Zs();Oi();OM()});function qT(e){let t=xa(e,0,1);if(t==="0x04")return"eip7702";if(t==="0x03")return"eip4844";if(t==="0x02")return"eip1559";if(t==="0x01")return"eip2930";if(t!=="0x"&&wt(t)>=192)return"legacy";throw new ob({serializedType:t})}var BM=b(()=>{l();zn();Si();Xr()});function WT(e){let t=qT(e);return t==="eip1559"?wMe(e):t==="eip2930"?bMe(e):t==="eip4844"?yMe(e):t==="eip7702"?gMe(e):xMe(e)}function gMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p,h,y]=t;if(t.length!==10&&t.length!==13)throw new ru({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:o,maxFeePerGas:s,gas:i,to:a,value:c,data:u,accessList:d,authorizationList:f,...t.length>9?{v:p,r:h,s:y}:{}},serializedTransaction:e,type:"eip7702"});let w={chainId:wt(r),type:"eip7702"};return We(a)&&a!=="0x"&&(w.to=a),We(i)&&i!=="0x"&&(w.gas=dt(i)),We(u)&&u!=="0x"&&(w.data=u),We(n)&&(w.nonce=n==="0x"?0:wt(n)),We(c)&&c!=="0x"&&(w.value=dt(c)),We(o)&&o!=="0x"&&(w.maxPriorityFeePerGas=dt(o)),We(s)&&(s!=="0x"||w.maxPriorityFeePerGas)&&(w.maxFeePerGas=s==="0x"?0n:dt(s)),d.length!==0&&d!=="0x"&&(w.accessList=ZT(d)),f.length!==0&&f!=="0x"&&(w.authorizationList=vMe(f)),lT(w),{...t.length===13?F3(t):void 0,...w}}function yMe(e){let t=KT(e),r=t.length===4,n=r?t[0]:t,o=r?t.slice(1):[],[s,i,a,c,u,d,f,p,h,y,w,x,v,T]=n,[E,S,_]=o;if(!(n.length===11||n.length===14))throw new ru({attributes:{chainId:s,nonce:i,maxPriorityFeePerGas:a,maxFeePerGas:c,gas:u,to:d,value:f,data:p,accessList:h,...n.length>9?{v:x,r:v,s:T}:{}},serializedTransaction:e,type:"eip4844"});let O={blobVersionedHashes:w,chainId:wt(s),to:d,type:"eip4844"};return We(u)&&u!=="0x"&&(O.gas=dt(u)),We(p)&&p!=="0x"&&(O.data=p),We(i)&&(O.nonce=i==="0x"?0:wt(i)),We(f)&&f!=="0x"&&(O.value=dt(f)),We(y)&&y!=="0x"&&(O.maxFeePerBlobGas=dt(y)),We(a)&&a!=="0x"&&(O.maxPriorityFeePerGas=dt(a)),We(c)&&(c!=="0x"||O.maxPriorityFeePerGas)&&(O.maxFeePerGas=c==="0x"?0n:dt(c)),h.length!==0&&h!=="0x"&&(O.accessList=ZT(h)),E&&S&&_&&(O.sidecars=M0({blobs:E,commitments:S,proofs:_})),uT(O),{...n.length===14?F3(n):void 0,...O}}function wMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p,h]=t;if(!(t.length===9||t.length===12))throw new ru({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:o,maxFeePerGas:s,gas:i,to:a,value:c,data:u,accessList:d,...t.length>9?{v:f,r:p,s:h}:{}},serializedTransaction:e,type:"eip1559"});let y={chainId:wt(r),type:"eip1559"};return We(a)&&a!=="0x"&&(y.to=a),We(i)&&i!=="0x"&&(y.gas=dt(i)),We(u)&&u!=="0x"&&(y.data=u),We(n)&&(y.nonce=n==="0x"?0:wt(n)),We(c)&&c!=="0x"&&(y.value=dt(c)),We(o)&&o!=="0x"&&(y.maxPriorityFeePerGas=dt(o)),We(s)&&(s!=="0x"||y.maxPriorityFeePerGas)&&(y.maxFeePerGas=s==="0x"?0n:dt(s)),d.length!==0&&d!=="0x"&&(y.accessList=ZT(d)),sm(y),{...t.length===12?F3(t):void 0,...y}}function bMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p]=t;if(!(t.length===8||t.length===11))throw new ru({attributes:{chainId:r,nonce:n,gasPrice:o,gas:s,to:i,value:a,data:c,accessList:u,...t.length>8?{v:d,r:f,s:p}:{}},serializedTransaction:e,type:"eip2930"});let h={chainId:wt(r),type:"eip2930"};return We(i)&&i!=="0x"&&(h.to=i),We(s)&&s!=="0x"&&(h.gas=dt(s)),We(c)&&c!=="0x"&&(h.data=c),We(n)&&(h.nonce=n==="0x"?0:wt(n)),We(a)&&a!=="0x"&&(h.value=dt(a)),We(o)&&o!=="0x"&&(h.gasPrice=dt(o)),u.length!==0&&u!=="0x"&&(h.accessList=ZT(u)),n6(h),{...t.length===11?F3(t):void 0,...h}}function xMe(e){let t=Wg(e,"hex"),[r,n,o,s,i,a,c,u,d]=t;if(!(t.length===6||t.length===9))throw new ru({attributes:{nonce:r,gasPrice:n,gas:o,to:s,value:i,data:a,...t.length>6?{v:c,r:u,s:d}:{}},serializedTransaction:e,type:"legacy"});let f={type:"legacy"};if(We(s)&&s!=="0x"&&(f.to=s),We(o)&&o!=="0x"&&(f.gas=dt(o)),We(a)&&a!=="0x"&&(f.data=a),We(r)&&(f.nonce=r==="0x"?0:wt(r)),We(i)&&i!=="0x"&&(f.value=dt(i)),We(n)&&n!=="0x"&&(f.gasPrice=dt(n)),o6(f),t.length===6)return f;let p=We(c)&&c!=="0x"?dt(c):0n;if(d==="0x"&&u==="0x")return p>0&&(f.chainId=Number(p)),f;let h=p,y=Number((h-35n)/2n);if(y>0)f.chainId=y;else if(h!==27n&&h!==28n)throw new Kh({v:h});return f.v=h,f.s=d,f.r=u,f.yParity=h%2n===0n?1:0,f}function KT(e){return Wg(`0x${e.slice(4)}`,"hex")}function ZT(e){let t=[];for(let r=0;ri6(s)?s:bn(s))})}return t}function vMe(e){let t=[];for(let r=0;r1n&&u<256n?{r:cs(a,{size:32}),s:cs(c,{size:32}),yParity:Number(u)}:F3([i,a,c]);t.push({address:o,chainId:n==="0x"?0:wt(n),nonce:s==="0x"?0:wt(s),...d})}return t}function F3(e){let t=e.slice(-3),r=t[0]==="0x"?0n:dt(t[0]);if(r!==0n&&r!==1n)throw new tu({yParity:r});let n=r===0n?27n:28n;return{r:cs(t[1],{size:32}),s:cs(t[2],{size:32}),v:n,yParity:n===27n?0:1}}var kM=b(()=>{l();tc();zn();Gs();n3();qs();Xa();Hh();Xr();mT();gT();dT();BM()});function pc(e,t){return NI(e,t)}var z3=b(()=>{l();Sg()});function ble(e,t="wei"){return Kre(e,t)}var xle=b(()=>{l();Sg()});function vle(e,t="wei"){return Zre(e,t)}var Ele=b(()=>{l();Sg()});function GT(e,t){return RI(e,t)}var UM=b(()=>{l();Sg()});var DM=b(()=>{l();us();Xr()});function EMe(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function Ale(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?wt(e.nonce):void 0,storageProof:e.storageProof?EMe(e.storageProof):void 0}}var Cle=b(()=>{l();DM()});async function Sle(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s,storageKeys:i}){let a=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),c=await e.request({method:"eth_getProof",params:[t,i,a]});return Ale(c)}var Ile=b(()=>{l();B0();Cle()});async function Tle(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new Gc({hash:t});return r}var _le=b(()=>{l();zn()});async function Ple(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s,slot:i}){let a=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});return await e.request({method:"eth_getStorageAt",params:[t,i,a]})}var Nle=b(()=>{l();B0()});async function Rle(e,{blockHash:t,blockNumber:r,blockTag:n="latest",requireCanonical:o,requests:s}){let i=ni({blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o});return e.request({method:"eth_getStorageValues",params:[s,i]})}var Ole=b(()=>{l();B0()});async function cm(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:s,sender:i,nonce:a}){let c=n||"latest",u=r!==void 0?oe(r):void 0,d=null;if(o?d=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0}):t?d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,oe(s)]},{dedupe:!0}):(u||c)&&typeof s=="number"?d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,oe(s)]},{dedupe:!!u}):i&&typeof a=="number"&&(d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[i,oe(a)]},{dedupe:!0})),!d)throw new Gc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:s});return(e.chain?.formatters?.transaction?.format||jf)(d,"getTransaction")}var YT=b(()=>{l();zn();qe();Ab()});async function Ble(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([ue(e,Ta,"getBlockNumber")({}),t?ue(e,cm,"getTransaction")({hash:t}):void 0]),s=r?.blockNumber||o?.blockNumber;if(!s)return 0n;let i=n{l();_t();zg();YT()});async function lm(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new nu({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||op)(r,"getTransactionReceipt")}var LM=b(()=>{l();zn();Qb()});async function Ule(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,requireCanonical:u,stateOverride:d}=t,f=t.contracts,p=typeof e.batch?.multicall=="object"?e.batch.multicall:{},h=t.batchSize??p.batchSize??1024,y=t.deployless??p.deployless??!1,w=(()=>{if(t.multicallAddress)return t.multicallAddress;if(y)return null;if(e.chain)return Ui({blockNumber:i,chain:e.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),x=[[]],v=0,T=0;for(let D=0;D0&&T>h&&x[v].length>0&&(v++,T=(R.length-2)/2,x[v]=[]),x[v]=[...x[v],{allowFailure:!0,callData:R,target:N}]}catch(R){let I=Js(R,{abi:M,address:N,args:L,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!o)throw I;x[v]=[...x[v],{allowFailure:!0,callData:"0x",target:N}]}}let E=!!e.batch?.multicall,S=E?x.flatMap(D=>D.map(M=>[M])):x,_=await Promise.allSettled(S.map(D=>E?AMe(e,{account:r,authorizationList:n,batchSize:h,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,call:D[0],multicallAddress:w,requireCanonical:u,stateOverride:d}).then(M=>[M]):ue(e,er,"readContract")({...w===null?{code:Mg}:{address:w},abi:ki,account:r,args:[D],authorizationList:n,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:u,stateOverride:d}))),O=[];for(let D=0;D<_.length;D++){let M=_[D];if(M.status==="rejected"){if(!o)throw M.reason;for(let L=0;Lf+(p.length-2)/2,0)>r},fn:u=>ue(e,er,"readContract")({...o===null?{code:Mg}:{address:o},...s,abi:ki,args:[u],functionName:"aggregate3"})}),[c]=await a(n);return c}var Dle=b(()=>{l();So();Vb();Qr();nt();ou();lc();us();K0();p0();_t();h3();so();oi()});async function w6(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:s,traceTransfers:i,validation:a}=t;try{let c=[];for(let p of o){let h=p.blockOverrides?w9(p.blockOverrides):void 0,y=p.calls.map(x=>{let v=x,T=v.account?ft(v.account):void 0,E=v.abi?Wt(v):v.data,S={...v,account:T,data:v.dataSuffix?en([E||"0x",v.dataSuffix]):E,from:v.from??T?.address};return jn(S),Bn(S)}),w=p.stateOverrides?xb(p.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:w})}let d=(typeof r=="bigint"?oe(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:i,validation:a},d]})).map((p,h)=>({...qf(p),calls:p.calls.map((y,w)=>{let{abi:x,args:v,functionName:T,to:E}=o[h].calls[w],S=y.error?.data??y.returnData,_=BigInt(y.gasUsed),O=y.maxUsedGas===void 0?void 0:BigInt(y.maxUsedGas),D=y.logs?.map(P=>qn(P)),M=y.status==="0x1"?"success":"failure",N=x&&M==="success"&&S!=="0x"?dn({abi:x,data:S,functionName:T}):null,L=(()=>{if(M==="success")return;let P;if(S==="0x"?P=new Ci:S&&(P=new sc({data:S})),!!P)return Js(P,{abi:x??[],address:E??"0x",args:v,functionName:T??""})})();return{data:S,gasUsed:_,logs:D,...O===void 0?{}:{maxUsedGas:O},status:M,...M==="success"?{result:N}:{error:L}}})}))}catch(c){let u=c,d=_0(u,{});throw d instanceof Ni?u:d}}var MM=b(()=>{l();uL();tn();Qr();ou();tl();lc();us();Fn();qe();p0();G4();X4();hu();rl();VI();nl()});function XT(e){let t=!0,r="",n=0,o="",s=!1;for(let i=0;ir==="object"&&JT(Lle(e,i,a),i));let o=CMe.exec(n);if(o){if(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&!Number.isInteger(e))return!1;let i=n.startsWith("int"),a=Number.parseInt(o[1]??"256",10),c=2n**(BigInt(a)-(i?1n:0n))-1n,u=i?-c-1n:0n;return e>=u&&e<=c}if(SMe.test(n)){if(typeof e!="string"&&!(e instanceof Uint8Array))return!1;let i=n.slice(5);return i?e instanceof Uint8Array?e.length===Number.parseInt(i,10):q0(e)?Mr(e)===Number.parseInt(i,10):!1:e instanceof Uint8Array||q0(e)}let s=Qg(n);if(s){let[i,a]=s;return Array.isArray(e)&&(i===null||e.length===i)&&e.every(c=>JT(c,{...t,type:a}))}return!1}}}function QT(e,t,r){for(let n in e){let o=e[n],s=t[n];if(!s)continue;if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s){let f=r[n],p=QT(o.components,s.components,o.components.map((h,y)=>Lle(f,h,y)));if(p)return p;continue}let i=Qg(o.type),a=Qg(s.type);if(i&&a){let f=QT([{...o,type:i[1]}],[{...s,type:a[1]}],[r[n]?.[0]]);if(f)return f;if(i[1]===a[1]&&o.type!==s.type)return[o.type,s.type];continue}let c=[o.type,s.type],u=r[n];if(c.includes("address")&&(c.includes("string")||c.includes("bytes"))?u===void 0||lM(u,{strict:!1}):o.type!==s.type)return c}}function Lle(e,t,r){return Array.isArray(e)?e[r]:e?.[t.name]}var CMe,SMe,Mle=b(()=>{l();B3();Bi();io();pM();CMe=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,SMe=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/});function b6(e,t={}){let{prepare:r=!0}=t,n=Array.isArray(e)?Tw(e):typeof e=="string"?Tw(e):e;return{...n,...r?{hash:ey(n)}:{}}}function x6(e,t,r){let{args:n=[],prepare:o=!0}=r??{},s=q0(t,{strict:!1}),i=e.filter(d=>s?d.type==="function"||d.type==="error"?$M(d)===rn(t,0,4):d.type==="event"?ey(d)===t:!1:"name"in d&&d.name===t);if(i.length===0)throw new sp({name:t});if(i.length===1)return{...i[0],...o?{hash:ey(i[0])}:{}};let a,c;for(let d of i){if(!("inputs"in d))continue;if(!n||n.length===0){!c&&(!d.inputs||d.inputs.length===0)&&(c=d);continue}if(!d.inputs||d.inputs.length===0||d.inputs.length!==n.length)continue;if(n.every((p,h)=>{let y="inputs"in d&&d.inputs[h];return y?JT(p,y):!1})){if(a&&"inputs"in a&&a.inputs){let p=QT(d.inputs,a.inputs,n);if(p)throw new HM({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let u=(()=>{if(a)return a;let d=c??i[0],f=i.filter(p=>p!==d);return{...d,overloads:f}})();if(!u)throw new sp({name:t});return{...u,...o?{hash:ey(u)}:{}}}function $M(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return x6(r,n)}return e[0]})();return rn(ey(t),0,4)}function TMe(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return x6(n,o)}return e[0]})(),r=typeof t=="string"?t:Af(t);return XT(r)}function ey(...e){let t=(()=>{if(Array.isArray(e[0])){let[s,i]=e;return x6(s,i)}return e[0]})();if(typeof t!="string"&&"hash"in t&&t.hash)return t.hash;let r=TMe(t),n=R3.signatureHash.get(r);if(n)return n;let o=Gg($b(r));return R3.signatureHash.set(r,o),o}var HM,sp,e_=b(()=>{l();fg();Bi();_T();io();Mle();eM();HM=class extends Ke{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${XT(Af(t.abiItem))}\`, and`,`\`${r.type}\` in \`${XT(Af(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}},sp=class extends Ke{constructor({name:t,data:r,type:n="item"}){let o=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${o} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}});function Hle(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[s,i]=e;return[_Me(s),i]}return e})(),{bytecode:n,args:o}=r;return fn(n,t.inputs?.length&&o?.length?am(t.inputs,o):"0x")}function $le(e){return b6(e)}function _Me(e){let t=e.find(r=>r.type==="constructor");if(!t)throw new sp({name:"constructor"});return t}var Fle=b(()=>{l();e_();y6();io()});function zle(e,t={}){return b6(e,t)}function Vle(e){return ey(e)}var jle=b(()=>{l();e_()});function qle(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[s,i,a,c]=e;return[zM(s,i),a,c]}return e})(),o=Xg(t.outputs,r,n);if(!(o&&Object.keys(o).length===0))return o&&Object.keys(o).length===1?Array.isArray(o)?o[0]:Object.values(o)[0]:o}function um(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[u,d,f]=e;return[zM(u,d,{args:f}),f]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?zM([t,...n],t.name,{args:r}):t,s=RMe(o),i=r.length>0?am(o.inputs,r):void 0;return i?fn(s,i):s}function ty(e,t={}){return b6(e,t)}function zM(e,t,r){let n=x6(e,t,r);if(n.type!=="function")throw new sp({name:t,type:"function"});return n}function RMe(e){return $M(e)}var Wle=b(()=>{l();e_();y6();io()});var v6,dm,t_=b(()=>{l();v6="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",dm="0x0000000000000000000000000000000000000000"});async function eue(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:s,traceAssetChanges:i,traceTransfers:a,validation:c}=t,u=t.account?ft(t.account):void 0;if(i&&!u)throw new G("`account` is required when `traceAssetChanges` is true");let d=u?Hle($le("constructor(bytes, bytes)"),{bytecode:zb,args:[BMe,um(ty("function getBalance(address)"),[u.address])]}):void 0,f=n??e.experimental_blockTag??"latest",p=r;if(i&&typeof p!="bigint"&&f!=="earliest"&&f!=="pending")if(f==="latest")p=await Ta(e,{cacheTime:0});else{let W=await xn(e,{blockTag:f});if(typeof W.number!="bigint")throw new G(`Block tag \`${f}\` did not resolve to a number.`);p=W.number}let h=typeof p=="bigint"?{blockNumber:p}:{blockTag:f},y=i?await w6(e,{...h,blocks:[{calls:o.map(W=>({...W,from:u.address})),stateOverrides:s}],traceTransfers:a,validation:c}):void 0,w=y?[...new Set([...LMe(y[0].calls.flatMap(W=>W.logs??[]),u.address),...t.calls.map(W=>W.to?.toLowerCase())])].filter(W=>!!W&&W!==v6&&W!==dm):[],x=MMe([...u?[u.address]:[],...w,...s?.map(({address:W})=>W)??[]]),v=[{address:x,code:Xle}],[T,E]=await Promise.all([i?Promise.all([Qle(e,{account:u.address,...h,data:d,stateOverride:s}),...w.map(W=>Qle(e,{account:u.address,address:W,...h,data:um(Kle,[u.address]),staticCallAddress:x,stateOverride:s}))]):[],w6(e,{...h,blocks:[{calls:[...o,{to:dm}].map(W=>({...W,from:u?.address})),stateOverrides:s},...i?[{calls:[{data:d}]},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Kle,[u.address]))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Zle))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Gle,[0n]))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Yle))})),stateOverrides:v}]:[]],traceTransfers:a,validation:c})]),S=E[0],[_,O,D,M,N]=i?E.slice(1):[],{calls:L,...P}=S,R=L.slice(0,-1),I=T.map(W=>Jle(W)?dt(W.data):null),B=_?.calls??[],C=O?.calls??[],U=[...B,...C].map(W=>Jle(W)?dt(W.data):null),H=(D?.calls??[]).map(W=>VM(W,Zle)),k=(N?.calls??[]).map(W=>VM(W,Yle)),F=(M?.calls??[]).map(W=>VM(W,Gle)),j=[];for(let[W,ae]of U.entries()){let te=I[W],X=T[W],pe=typeof te=="bigint"?te:W>0&&X?.status==="success"&&X.data==="0x"?0n:null;if(typeof ae!="bigint"||typeof pe!="bigint")continue;let me=H[W-1],Ne=k[W-1],ye=F[W-1],Re=W===0?{address:v6,decimals:18,symbol:"ETH"}:{address:w[W-1],decimals:ye||me?Number(me??1):void 0,symbol:Ne??void 0};j.push({token:Re,value:{pre:pe,post:ae,diff:ae-pe}})}return{assetChanges:j,block:P,results:R}}function j3(e,t){return um(DMe,[e,t])}function LMe(e,t){let r=Zr(t.toLowerCase(),{size:32});return e.filter(n=>n.topics[0]?.toLowerCase()!==UMe||n.address.toLowerCase()===v6?!1:n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r).map(n=>n.address.toLowerCase())}function Jle(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function VM(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return qle(t,e.data)}catch{return null}}async function Qle(e,t){let{account:r,address:n,blockNumber:o,blockTag:s,data:i,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await ms({...e,ccipRead:!1},{account:n?dm:r,data:n?j3(n,i):i,stateOverride:n&&a?[...c??[],{address:a,code:Xle}]:c,...n?{gas:V3,to:a}:{},...typeof o=="bigint"?{blockNumber:o}:{blockTag:s}})).data??"0x",status:"success"}}catch(u){if(!(u instanceof Yc)||!(u.cause instanceof ri))throw u;return{data:"0x",status:"failure"}}}function MMe(e){let t=new Set(e.map(n=>n.toLowerCase())),r=kMe;for(;t.has(`0x${r.toString(16).padStart(40,"0")}`);)r++;return`0x${r.toString(16).padStart(40,"0")}`}var BMe,Xle,V3,kMe,UMe,Kle,Zle,Gle,Yle,DMe,tue=b(()=>{l();Fle();jle();Wle();tn();t_();Vb();nt();ou();tl();Xa();Xr();G0();fu();zg();MM();BMe="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",Xle="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",V3=1000000n,kMe=0x00000000000000000000000000000000deadbeefn,UMe=Vle(zle("event Transfer(address indexed from, address indexed to, uint256 value)")),Kle=ty("function balanceOf(address) returns (uint256)"),Zle=ty("function decimals() returns (uint256)"),Gle=ty("function tokenURI(uint256) returns (string)"),Yle=ty("function symbol() returns (string)"),DMe=ty("function query(address target, bytes data)")});var q3={};Te(q3,{InvalidWrappedSignatureError:()=>r_,assert:()=>qM,from:()=>FMe,magicBytes:()=>jM,universalSignatureValidatorAbi:()=>$Me,universalSignatureValidatorBytecode:()=>HMe,unwrap:()=>rue,validate:()=>VMe,wrap:()=>zMe});function qM(e){if(rn(e,-32)!==jM)throw new r_(e)}function FMe(e){return typeof e=="string"?rue(e):e}function rue(e){qM(e);let[t,r,n]=Xg(D3("address, bytes, bytes"),e);return{data:r,signature:n,to:t}}function zMe(e){let{data:t,signature:r,to:n}=e;return fn(am(D3("address, bytes, bytes"),[n,t,r]),jM)}function VMe(e){try{return qM(e),!0}catch{return!1}}var jM,HMe,$Me,r_,nue=b(()=>{l();y6();Bi();io();jM="0x6492649264926492649264926492649264926492649264926492649264926492",HMe="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",$Me=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];r_=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}});var oue=b(()=>{l();nue()});function W3({r:e,s:t,to:r="hex",v:n,yParity:o}){let s=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),i=`0x${new ei.Signature(dt(e),dt(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?i:qt(i)}var WM=b(()=>{l();Bg();Xr();Pr()});async function fm(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:s=t.universalSignatureVerifierAddress??(()=>{let{blockNumber:u}=t,d=n?.contracts?.erc6492Verifier;if(!(u!==void 0&&d?.blockCreated&&d.blockCreated>u))return d?.address})(),multicallAddress:i=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(r===dm)return!1;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let u=t.signature;return We(u)?u:typeof u=="object"&&"r"in u&&"s"in u?W3(u):yt(u)})();try{if(a==="eoa")try{if(xr(Gr(r),await ti({hash:o,signature:c})))return!0}catch{}return il.validate(c)?await jMe(e,{...t,multicallAddress:i,signature:c}):await qMe(e,{...t,verifierAddress:s,signature:c})}catch(u){if(a!=="eoa")try{if(xr(Gr(r),await ti({hash:o,signature:c})))return!0}catch{}if(u instanceof vu)return!1;throw u}}async function jMe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:s,hash:i,multicallAddress:a,requireCanonical:c}=t,{authorization:u,data:d,signature:f,to:p}=il.unwrap(t.signature);if(await jg(e,{address:r,blockHash:n,blockNumber:o,blockTag:s,requireCanonical:c})===fr(["0xef0100",u.address]))return await WMe(e,{...t,signature:f});let y={address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce),r:oe(u.r,{size:32}),s:oe(u.s,{size:32}),yParity:u.yParity};if(!await Oae({address:r,authorization:y}))throw new vu;let{data:x}=await ms({...e,ccipRead:!1},{...a?{to:a}:{code:Mg},authorizationList:[y],blockHash:n,blockNumber:o,blockTag:s??"pending",data:Wt({abi:ki,functionName:"aggregate3",args:[[...d?[{allowFailure:!0,target:p??r,callData:d}]:[],{allowFailure:!0,target:r,callData:Wt({abi:x9,functionName:"isValidSignature",args:[i,f]})}]]}),requireCanonical:c}),v=dn({abi:ki,functionName:"aggregate3",data:x??"0x"}),T=v[v.length-1];if(T?.success&&T.returnData.startsWith("0x1626ba7e"))return!0;throw new vu}async function qMe(e,t){let{address:r,factory:n,factoryData:o,hash:s,signature:i,verifierAddress:a,...c}=t,u=await(async()=>!n&&!o||q3.validate(i)?i:q3.wrap({data:o,signature:i,to:n}))(),d=a?{batch:!1,to:a,data:Wt({abi:Fb,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:tp({abi:Fb,args:[r,s,u],bytecode:f3}),...c},{data:f}=await ms({...e,ccipRead:!1},d).catch(p=>{throw p instanceof Yc?new vu:p});if(qw(f??"0x0"))return!0;throw new vu}async function WMe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:s,hash:i,requireCanonical:a,signature:c}=t,{data:u}=await ms({...e,ccipRead:!1},{batch:!1,blockHash:n,blockNumber:o,blockTag:s,data:Wt({abi:x9,functionName:"isValidSignature",args:[i,c]}),requireCanonical:a,to:r}).catch(f=>{throw f instanceof Yc?new vu:f});if((()=>{try{return dn({abi:x9,functionName:"isValidSignature",data:u??"0x"})}catch{throw new vu}})().startsWith("0x1626ba7e"))return!0;throw new vu}var vu,K3=b(()=>{l();oue();$3();So();t_();Vb();ou();lc();p3();us();Zs();Oi();Bae();Fn();qs();Xr();qe();w0();WM();G0();aT();vu=class extends Error{}});async function sue(e,{address:t,message:r,factory:n,factoryData:o,signature:s,...i}){let a=im(r);return ue(e,fm,"verifyHash")({address:t,factory:n,factoryData:o,hash:a,signature:s,...i})}var iue=b(()=>{l();_t();T3();K3()});async function aue(e,t){let{address:r,factory:n,factoryData:o,signature:s,message:i,primaryType:a,types:c,domain:u,...d}=t,f=p6({message:i,primaryType:a,types:c,domain:u});return ue(e,fm,"verifyHash")({address:r,factory:n,factoryData:o,hash:f,signature:s,...d})}var cue=b(()=>{l();_t();P3();K3()});function n_(e,{emitOnBegin:t=!1,emitMissed:r,onBlockNumber:n,onError:o,poll:s,pollingInterval:i=e.pollingInterval}){let a=typeof s<"u"?s:Q0(e),c=e.chain?.blockTime,u=r??(c!==void 0&&i>c/2),d;return a?(()=>{let h=bt(["watchBlockNumber",e.uid,t,u,i]);return Io(h,{onBlockNumber:n,onError:o},y=>dc(async()=>{try{let w=await ue(e,Ta,"getBlockNumber")({cacheTime:0});if(d!==void 0){if(w===d)return;if(w-d>1&&u)for(let x=d+1n;xd)&&(y.onBlockNumber(w,d),d=w)}catch(w){y.onError?.(w)}},{emitOnBegin:t,interval:i}))})():(()=>{let h=bt(["watchBlockNumber",e.uid,t,u]);return Io(h,{onBlockNumber:n,onError:o},y=>{let w=!0,x=()=>w=!1;return(async()=>{try{let v=gu(e),{unsubscribe:T}=await v.subscribe({params:["newHeads"],onData(E){if(!w)return;let S=dt(E.result?.number);y.onBlockNumber(S,d),d=S},onError(E){y.onError?.(E)}});x=T,w||x()}catch(v){o?.(v)}})(),()=>x()})})()}var KM=b(()=>{l();Xr();_t();rp();Fg();so();zg();Zb()});async function Z3(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:s,retryCount:i=6,retryDelay:a=({count:L})=>~~(1<e.chain?.transactionReplacement?.getKey?.(L)??String(L.nonce),p=t.pollingInterval?t.pollingInterval:e.chain?.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval,h=bt(["waitForTransactionReceipt",e.uid,o,{checkReplacement:r,confirmations:n,pollingInterval:p,replacement:d,retryCount:i,signal:c?rm():void 0,timeout:u}]),y,w,x,v=!1,T,E,S,{promise:_,resolve:O,reject:D}=jb(),M=u?setTimeout(()=>{S?.(),E?.(),T=void 0,D(new Gh({hash:o}))},u):void 0,N=()=>{clearTimeout(M),S?.(),E?.(),D(Nn(c))};return c?.addEventListener("abort",N,{once:!0}),E=Io(h,{onReplaced:s,resolve:O,reject:D},async L=>{if(w=await ue(e,lm,"getTransactionReceipt")({hash:o}).catch(()=>{}),c?.aborted)return;if(w&&n<=1){clearTimeout(M),L.resolve(w),E?.();return}let P=async R=>{let I=C=>{T=void 0,clearTimeout(M),S?.(),C(),E?.()},B=R;try{if(w){if(n>1&&(!w.blockNumber||B-w.blockNumber+1nU instanceof nu?null:void 0);if(C===void 0)return;if(!C){w=void 0,x||(y=void 0),x=void 0;return}if(w=C,n>1&&(!C.blockNumber||B-C.blockNumber+1n{A&&L.onReplaced?.(A),L.resolve(C)});return}if(r&&!y&&(v=!0,await np(async()=>{y=await ue(e,cm,"getTransaction")({hash:o}),y.blockNumber&&(B=y.blockNumber)},{delay:a,retryCount:i,signal:c,shouldRetry:({error:C})=>!(d&&C instanceof Gc)}),v=!1),w=await ue(e,lm,"getTransactionReceipt")({hash:o}),n>1&&(!w.blockNumber||B-w.blockNumber+1nL.resolve(w))}catch(C){if(C instanceof Gc||C instanceof nu){v=!1;let A=y??(r&&d?{...d,hash:o.toLowerCase()}:void 0);if(!A||A.blockNumber)return;try{if(!y){v=!0;let F=await ue(e,cm,"getTransaction")({nonce:A.nonce,sender:A.from}).catch(j=>{(j instanceof Jc||j instanceof Aa)&&(y=A)});if(v=!1,F?.hash.toLowerCase()===A.hash){y=F;return}if(F){let j=await ue(e,lm,"getTransactionReceipt")({hash:F.hash}).catch(W=>{if(!(W instanceof nu))throw W});if(!j||(w=j,x={reason:e.chain?.transactionReplacement?.getReason?.({replaced:A,replacement:F})??lue(A,F),replacedTransaction:A,transaction:F,transactionReceipt:w},n>1&&(!w.blockNumber||B-w.blockNumber+1n{L.onReplaced?.(x),L.resolve(w)});return}}v=!0;let U=await np(()=>ue(e,xn,"getBlock")({blockNumber:B,includeTransactions:!0}),{delay:a,retryCount:i,signal:c,shouldRetry:({error:F})=>F instanceof du});v=!1;let H=f(A),k=U.transactions.find(F=>xr(F.from,A.from)&&F.hash!==A.hash&&f(F)===H);if(!k||(w=await ue(e,lm,"getTransactionReceipt")({hash:k.hash}),x={reason:e.chain?.transactionReplacement?.getReason?.({replaced:A,replacement:k})??lue(A,k),replacedTransaction:A,transaction:k,transactionReceipt:w},n>1&&(!w.blockNumber||B-w.blockNumber+1n{L.onReplaced?.(x),L.resolve(w)})}catch(U){I(()=>L.reject(U))}}else I(()=>L.reject(C))}};S=ue(e,n_,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:p,async onBlockNumber(R){for(T=R;T!==void 0&&!v;){let I=T;T=void 0,await P(I)}}})}),_.finally(()=>{c?.removeEventListener("abort",N),clearTimeout(M),E?.()})}function lue(e,t){return(t.to&&e.to?xr(t.to,e.to):t.to===e.to)&&t.value===e.value&&t.input===e.input?"repriced":t.from===t.to&&t.value===0n?"cancelled":"replaced"}var ZM=b(()=>{l();J4();Lf();zn();oc();Oi();_t();rp();A9();v3();so();A3();fu();YT();LM();KM()});function uue(e,{onBlockHeader:t,onError:r}){let n,o=bt(["watchBlockHeaders",e.uid]);return Io(o,{onBlockHeader:t,onError:r},s=>{let i=!0,a=!1,c=()=>i=!1;return(async()=>{try{let u=gu(e),{unsubscribe:d}=await u.subscribe({params:["newHeads"],onData(f){if(!i)return;let p=(e.chain?.formatters?.block?.format||qf)(f.result,"watchBlockHeaders");for(let h of KMe)delete p[h];s.onBlockHeader(p,n),n=p},onError(f){a&&s.onError?.(f)}});a=!0,c=d,i||c()}catch(u){s.onError?.(u)}})(),()=>c()})}var KMe,due=b(()=>{l();X4();rp();so();Zb();KMe=["size","totalDifficulty","transactions","uncles","withdrawals"]});function fue(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r,emitOnBegin:n=!1,onBlock:o,onError:s,includeTransactions:i,poll:a,pollingInterval:c=e.pollingInterval}){let u=typeof a<"u"?a:Q0(e),d=i??!1,f=e.chain?.blockTime,p=r??((t==="latest"||t==="pending")&&f!==void 0&&c>f/2),h=r===void 0?100:Number.POSITIVE_INFINITY,y;return u?(()=>{let v=bt(["watchBlocks",e.uid,t,p,n,d,h,c]);return Io(v,{onBlock:o,onError:s},T=>dc(async()=>{try{let E=await ue(e,xn,"getBlock")({blockTag:t,includeTransactions:d});if(E.number!==null&&y?.number!=null){if(E.number===y.number)return;let S=Number(E.number-y.number)-1;if(S>0&&S<=h&&p){let O=y.number+1n;for(let D=0;Due(e,xn,"getBlock")({blockNumber:O+BigInt(D+L),includeTransactions:d})));for(let N of M)T.onBlock(N,y),y=N}}}(y?.number==null||t==="pending"&&E?.number==null||E.number!==null&&E.number>y.number)&&(T.onBlock(E,y),y=E)}catch(E){T.onError?.(E)}},{emitOnBegin:n,interval:c}))})():(()=>{let v=!0,T=!0,E=()=>v=!1;return(async()=>{try{n&&ue(e,xn,"getBlock")({blockTag:t,includeTransactions:d}).then(O=>{v&&T&&(o(O,void 0),T=!1)}).catch(s);let S=gu(e),{unsubscribe:_}=await S.subscribe({params:["newHeads"],async onData(O){if(!v)return;let D=await ue(e,xn,"getBlock")({blockNumber:O.result?.number,includeTransactions:d}).catch(()=>{});v&&(o(D,y),T=!1,y=D)},onError(O){s?.(O)}});E=_,v||E()}catch(S){s?.(S)}})(),()=>E()})()}var pue=b(()=>{l();_t();rp();Fg();so();fu();Zb()});function hue(e,{address:t,args:r,batch:n=!0,event:o,events:s,fromBlock:i,onError:a,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:f}){let p=typeof u<"u"?u:typeof i=="bigint"?!0:Q0(e),h=f??!1;return p?(()=>{let x=bt(["watchEvent",t,r,n,e.uid,o,s,d,h,i]);return Io(x,{onLogs:c,onError:a},v=>{let T=!0,E=i===void 0?void 0:i-1n,S,_=!1,O=N=>{if(N.length!==0)if(n)v.onLogs(N);else for(let L of N)v.onLogs([L])},D=(N,L)=>ue(e,F0,"getLogs")({address:t,args:r,event:o,events:s,fromBlock:N,strict:h,toBlock:L}),M=dc(async()=>{if(!_){try{S=await ue(e,sT,"createEventFilter")({address:t,args:r,event:o,events:s,strict:h,fromBlock:i})}catch{}if(_=!0,S)return}try{if(S){let P=await ue(e,J0,"getFilterChanges")({filter:S});O(P);return}let N=await ue(e,Ta,"getBlockNumber")({});E??=N;let L=N-E;for(;E{if(P===I||!Bb(C))throw C});if(!T)return;if(!B){L=(I-P+1n)/2n;continue}E=I,O(B)}}catch(N){S&&N instanceof Ti&&(_=!1),v.onError?.(N)}},{emitOnBegin:!0,interval:d});return async()=>{T=!1,S&&await ue(e,X0,"uninstallFilter")({filter:S}),M()}})})():(()=>{let x=!0,v=()=>x=!1;return(async()=>{try{let T=gu(e),E=s??(o?[o]:void 0),S=[];E&&(S=[E.flatMap(D=>nc({abi:[D],eventName:D.name,args:r}))],o&&(S=S[0]));let{unsubscribe:_}=await T.subscribe({params:["logs",{address:t,topics:S}],onData(O){if(!x)return;let D=O.result;try{let{eventName:M,args:N}=Yf({abi:E??[],data:D.data,topics:D.topics,strict:h}),L=qn(D,{args:N,eventName:M});c([L])}catch(M){if((E||f)&&(M instanceof Gf||M instanceof Yl||M instanceof Jl))return;let N,L;if(M instanceof jc||M instanceof Ql){if(f)return;N=M.abiItem.name,L=M.abiItem.inputs?.some(R=>!("name"in R&&R.name))}let P=qn(D,{args:L?[]:{},eventName:N});c([P])}},onError(O){a?.(O)}});v=_,x||v()}catch(T){a?.(T)}})(),()=>v()})()}var mue=b(()=>{l();Qr();Lf();a3();Cg();hu();_t();rp();Fg();so();$L();zg();y3();c3();n9();Zb();w3()});function gue(e,{batch:t=!0,onError:r,onTransactions:n,poll:o,pollingInterval:s=e.pollingInterval}){return(typeof o<"u"?o:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let u=bt(["watchPendingTransactions",e.uid,t,s]);return Io(u,{onTransactions:n,onError:r},d=>{let f,p=dc(async()=>{try{if(!f)try{f=await ue(e,iT,"createPendingTransactionFilter")({});return}catch(y){throw p(),y}let h=await ue(e,J0,"getFilterChanges")({filter:f});if(h.length===0)return;if(t)d.onTransactions(h);else for(let y of h)d.onTransactions([y])}catch(h){d.onError?.(h)}},{emitOnBegin:!0,interval:s});return async()=>{f&&await ue(e,X0,"uninstallFilter")({filter:f}),p()}})})():(()=>{let u=!0,d=()=>u=!1;return(async()=>{try{let{unsubscribe:f}=await e.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;let h=p.result;n([h])},onError(p){r?.(p)}});d=f,u||d()}catch(f){r?.(f)}})(),()=>d()})()}var yue=b(()=>{l();_t();rp();Fg();so();FL();y3();w3()});function GMe(e){return ZMe.test(e)?!Number.isNaN(new Date(e).getTime()):!1}function GM(e){return GMe(e)?new Date(e):new Date(Number.NaN)}function wue(e){let{scheme:t,statement:r,...n}=e.match(YMe)?.groups??{},{chainId:o,expirationTime:s,issuedAt:i,notBefore:a,requestId:c,resources:u,...d}=e.match(JMe)?.groups??{},f=u?.split(` -- `).slice(1);return{...n,...d,...o?{chainId:Number(o)}:{},...s?{expirationTime:GM(s)}:{},...i?{issuedAt:GM(i)}:{},...a?{notBefore:GM(a)}:{},...c?{requestId:c}:{},...f?{resources:f}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var ZMe,YMe,JMe,bue=b(()=>{l();ZMe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;YMe=/^(?:(?[a-zA-Z][a-zA-Z0-9+\-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,JMe=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.*))?(?:\nResources:(?(?:\n- .+)*))?/});function xue(e){let{address:t,domain:r,message:n,nonce:o,scheme:s,time:i=new Date}=e;if(r&&n.domain!==r||o&&n.nonce!==o||s&&n.scheme!==s||n.nonce!==void 0&&!QMe.test(n.nonce)||n.version!==void 0&&n.version!=="1"||Number.isNaN(i.getTime())||n.expirationTime&&(Number.isNaN(n.expirationTime.getTime())||i>=n.expirationTime)||n.notBefore&&(Number.isNaN(n.notBefore.getTime())||i{l();Gs();Oi();QMe=/^[a-zA-Z0-9]{8,}$/});async function Eue(e,t){let{address:r,domain:n,message:o,nonce:s,scheme:i,signature:a,time:c=new Date,...u}=t,d=wue(o);if(!d.address||!xue({address:r,domain:n,message:d,nonce:s,scheme:i,time:c}))return!1;let p=im(o);return fm(e,{address:d.address,hash:p,signature:a,...u})}var Aue=b(()=>{l();T3();bue();vue();K3()});function E6(e,t){return{amount:e,decimals:t,formatted:pc(e,t)}}function o_(e,t){if(typeof e=="bigint")return e;let r=e.decimals??t;return GT(e.formatted,XMe(r))}function XMe(e){if(e===void 0)throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function s_(e,t){return typeof e=="bigint"?t:e.decimals??t}function jo(e,t){let{decimals:r,token:n}=t,o=JM(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(Ft(n,{strict:!1}))return{address:n,decimals:r??tHe(e,n)};throw new Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function JM(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=eHe(r,t);if(o)return YM(o,n);if(Ft(t,{strict:!1}))for(let s of r){let i=YM(s,n);if(i&&xr(i.address,t))return i}}function YM(e,t){if(e.addresses[t])return e(t)}function eHe(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n}function tHe(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let s=YM(o,n);if(s&&xr(s.address,t))return s.decimals}}async function A6(e,t){let{address:r,decimals:n}=jo(e,t);return n!==void 0?{address:r,decimals:n}:{address:r,decimals:await er(e,{abi:Hr,address:r,functionName:"decimals"})}}function C6(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:s,nonce:i}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:s,nonce:i}}function Eu(e){return{...e,data:Wt(e),to:e.address}}var ip=b(()=>{l();So();Gs();Oi();DM();z3();UM();oi()});async function ap(e,t){return ap.inner(_a,e,t)}function rHe(e,t){let{amount:r,spender:n,token:o}=t,{address:s,decimals:i}=jo(e,{token:o});return{abi:Hr,address:s,args:[n,o_(r,i)],functionName:"approve"}}var QM=b(()=>{l();So();Dg();i3();g3();Yb();ip();(function(e){async function t(i,a,c){return await i(a,{...c,...e.call(a,c)})}e.inner=t;function r(i,a){return Eu(rHe(i,a))}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:r,writable:!0});async function n(i,a){return $0(i,{...C6(a),...e.call(i,a)})}e.estimateGas=n;async function o(i,a){return Y0(i,{...C6(a),...e.call(i,a)})}e.simulate=o;function s(i){let[a]=cc({abi:Hr,logs:i,eventName:"Approval",strict:!0});if(!a)throw new Error("`Approval` event not found.");return a}e.extractEvent=s})(ap||(ap={}))});async function S6(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),i=(e.chain?.formatters?.transactionReceipt?.format||op)(o);if(i.status==="reverted"&&r)throw new Zh({receipt:i});return i}var i_=b(()=>{l();zn();Qb()});async function a_(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:s,authorizationList:i,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,pollingInterval:x,throwOnReceiptRevert:v,type:T,value:E,...S}=t,_=t.timeout??Math.max((o?.blockTime??0)*3,5e3);if(typeof r>"u")throw new kn({docsPath:"/docs/actions/wallet/sendTransactionSync"});let O=r?ft(r):null,D;try{jn(t);let M=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await b0({authorization:i[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if(O?.type==="json-rpc"||O===null){let N;o!==null&&(N=await ue(e,hs,"getChainId")({}),n&&em({currentChainId:N,chain:o}));let L=e.chain?.formatters?.transactionRequest?.format,R=(L||Bn)({...Ri(S,{format:L}),accessList:s,account:O,authorizationList:i,blobs:a,chainId:N,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,to:M,type:T,value:E},"sendTransaction"),I=XM.get(e.uid),B=I?"wallet_sendTransaction":"eth_sendTransaction",C=await(async()=>{try{return await e.request({method:B,params:[R]},{retryCount:0})}catch(U){if(I===!1)throw U;let H=U;if(H.name==="InvalidInputRpcError"||H.name==="InvalidParamsRpcError"||H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[R]},{retryCount:0}).then(k=>(XM.set(e.uid,!0),k)).catch(k=>{let F=k;throw F.name==="MethodNotFoundRpcError"||F.name==="MethodNotSupportedRpcError"?(XM.set(e.uid,!1),H):F});throw H}})(),A=await ue(e,Z3,"waitForTransactionReceipt")({checkReplacement:!1,hash:C,pollingInterval:x,timeout:_});if(v&&A.status==="reverted")throw new Zh({receipt:A});return A}if(O?.type==="local"){let N=(()=>{if(!O.nonceManager||typeof w<"u")return O.nonceManager;let A=O.nonceManager;return{async consume(U){D={address:U.address,chainId:U.chainId};let H=await A.consume(U);return D={...D,nonce:H},H},get(U){return A.get(U)},increment(U){return A.increment(U)},reset(U){return A.reset(U)}}})(),L=await ue(e,pu,"prepareTransactionRequest")({account:O,accessList:s,authorizationList:i,blobs:a,chain:o,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,nonceManager:N,parameters:[...s3,"sidecars"],type:T,value:E,...S,to:M}),P=o?.serializers?.transaction,R=await O.signTransaction(L,{serializer:P}),I=(o??e.chain)?.serializers?.transactionEnvelope,B=I?await I({serializedTransaction:R,transaction:L}):R,C=Date.now();try{return await ue(e,S6,"sendRawTransactionSync")({serializedTransaction:B,throwOnReceiptRevert:v,timeout:t.timeout})}catch(A){let U=A instanceof G?A.walk(j=>j?.code===4):null;if(!U)throw A;D=void 0;let H=(()=>{let{data:j}=U;if(typeof j=="string"&&i6(j))return j;if(xa(B,0,1)==="0x03"){let W=Wg(xa(B,1));if(W.length===4&&Array.isArray(W[0]))return Pt(en(["0x03",Vo(W[0])]))}return Pt(B)})(),k=_-(Date.now()-C);if(k<=0)throw new Gh({hash:H});let F=await ue(e,Z3,"waitForTransactionReceipt")({checkReplacement:!1,hash:H,pollingInterval:x,timeout:k});if(v&&F.status==="reverted")throw new Zh({receipt:F});return F}}throw O?.type==="smart"?new fc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new fc({docsPath:"/docs/actions/wallet/sendTransactionSync",type:O?.type})}catch(M){throw M instanceof fc?M:(D&&!(M instanceof Zh)&&O?.nonceManager?.reset(D),H0(M,{...t,account:O,chain:t.chain||void 0}))}}var XM,eH=b(()=>{l();tn();yu();nt();zn();Z4();b3();Fn();Si();mT();wb();o3();P0();rl();_t();gT();Ks();_f();nl();Zf();ZM();Rb();i_();XM=new xo(128)});async function I6(e,t){return _a.internal(e,a_,"sendTransactionSync",t)}var c_=b(()=>{l();eH();Yb()});async function tH(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:s}=jo(e,{token:n}),i=s_(r,s),a=await ap.inner(I6,e,{...t,throwOnReceiptRevert:o}),{args:c}=ap.extractEvent(a.logs);return{...c,...i===void 0?{}:{decimals:i,formatted:pc(c.value,i)},receipt:a}}var Cue=b(()=>{l();z3();c_();QM();ip()});async function T6(e,t){let{account:r,decimals:n,spender:o,token:s,...i}=t,[a,{decimals:c}]=await Promise.all([er(e,{...i,...T6.call(e,{account:r,spender:o,token:s})}),A6(e,{decimals:n,token:s})]);return E6(a,c)}var Sue=b(()=>{l();So();oi();ip();(function(e){function t(r,n){return Eu({address:jo(r,n).address,abi:Hr,functionName:"allowance",args:[n.account,n.spender]})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(T6||(T6={}))});async function _6(e,t){let{account:r=e.account,decimals:n,token:o,...s}=t;if(!r)throw new kn;let i=ft(r).address,[a,{decimals:c}]=await Promise.all([er(e,{...s,..._6.call(e,{account:i,token:o})}),A6(e,{decimals:n,token:o})]);return E6(a,c)}var Iue=b(()=>{l();tn();So();yu();oi();ip();(function(e){function t(r,n){let o=n.account??r.account;if(!o)throw new kn;let s=ft(o).address;return Eu({address:jo(r,n).address,abi:Hr,functionName:"balanceOf",args:[s]})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(_6||(_6={}))});async function rH(e,t){let{token:r,...n}=t,{address:o}=jo(e,{token:r}),s=JM(e,r),[i,a,c]=await Promise.all([s?.decimals??er(e,{...n,abi:Hr,address:o,functionName:"decimals"}),s?.name??er(e,{...n,abi:Hr,address:o,functionName:"name"}),s?.symbol??er(e,{...n,abi:Hr,address:o,functionName:"symbol"})]);return{decimals:i,name:a,symbol:c}}var Tue=b(()=>{l();So();oi();ip()});async function P6(e,t){let{decimals:r,token:n,...o}=t,[s,{decimals:i}]=await Promise.all([er(e,{...o,...P6.call(e,{token:n})}),A6(e,{decimals:r,token:n})]);return E6(s,i)}var _ue=b(()=>{l();So();oi();ip();(function(e){function t(r,n){return Eu({address:jo(r,n).address,abi:Hr,args:[],functionName:"totalSupply"})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(P6||(P6={}))});async function cp(e,t){return cp.inner(_a,e,t)}function nHe(e,t){let{amount:r,from:n,to:o,token:s}=t,{address:i,decimals:a}=jo(e,{token:s}),c=o_(r,a);return n?{abi:Hr,address:i,args:[n,o,c],functionName:"transferFrom"}:{abi:Hr,address:i,args:[o,c],functionName:"transfer"}}var nH=b(()=>{l();So();Dg();i3();g3();Yb();ip();(function(e){async function t(i,a,c){return await i(a,{...c,...e.call(a,c)})}e.inner=t;function r(i,a){return Eu(nHe(i,a))}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:r,writable:!0});async function n(i,a){return $0(i,{...C6(a),...e.call(i,a)})}e.estimateGas=n;async function o(i,a){return Y0(i,{...C6(a),...e.call(i,a)})}e.simulate=o;function s(i){let[a]=cc({abi:Hr,logs:i,eventName:"Transfer",strict:!0});if(!a)throw new Error("`Transfer` event not found.");return a}e.extractEvent=s})(cp||(cp={}))});async function oH(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:s}=jo(e,{token:n}),i=s_(r,s),a=await cp.inner(I6,e,{...t,throwOnReceiptRevert:o}),{args:c}=cp.extractEvent(a.logs);return{...c,...i===void 0?{}:{decimals:i,formatted:pc(c.value,i)},receipt:a}}var Pue=b(()=>{l();z3();c_();ip();nH()});var sH=b(()=>{l();QM();Cue();Sue();Iue();Tue();_ue();nH();Pue()});function l_(e){return{call:t=>ms(e,t),createAccessList:t=>rae(e,t),createBlockFilter:()=>oae(e),createContractEventFilter:t=>Zw(e,t),createEventFilter:t=>sT(e,t),createPendingTransactionFilter:()=>iT(e),estimateContractGas:t=>$0(e,t),estimateGas:t=>Ob(e,t),getBalance:t=>iae(e,t),getBlobBaseFee:()=>cae(e),getBlock:t=>xn(e,t),getBlockNumber:t=>Ta(e,t),getBlockReceipts:t=>uae(e,t),getBlockTransactionCount:t=>fae(e,t),getBytecode:t=>jg(e,t),getChainId:()=>hs(e),getCode:t=>jg(e,t),getContractEvents:t=>kb(e,t),getDelegation:t=>hae(e,t),getEip712Domain:t=>yae(e,t),getEnsAddress:t=>Die(e,t),getEnsAvatar:t=>Yie(e,t),getEnsName:t=>Qie(e,t),getEnsResolver:t=>eae(e,t),getEnsText:t=>oT(e,t),getFeeHistory:t=>vae(e,t),estimateFeesPerGas:t=>Mse(e,t),getFilterChanges:t=>J0(e,t),getFilterLogs:t=>Aae(e,t),getGasPrice:()=>Cb(e),getLogs:t=>F0(e,t),getProof:t=>Sle(e,t),estimateMaxPriorityFeePerGas:t=>Lse(e,t),fillTransaction:t=>Nb(e,t),getRawTransaction:t=>Tle(e,t),getStorageAt:t=>Ple(e,t),getStorageValues:t=>Rle(e,t),getTransaction:t=>cm(e,t),getTransactionConfirmations:t=>Ble(e,t),getTransactionCount:t=>k0(e,t),getTransactionReceipt:t=>lm(e,t),iterateLogs:t=>o9(e,t),multicall:t=>Ule(e,t),prepareTransactionRequest:t=>pu(e,t),readContract:t=>er(e,t),sendRawTransaction:t=>Gb(e,t),sendRawTransactionSync:t=>S6(e,t),simulate:t=>w6(e,t),simulateBlocks:t=>w6(e,t),simulateCalls:t=>eue(e,t),simulateContract:t=>Y0(e,t),verifyHash:t=>fm(e,t),verifyMessage:t=>sue(e,t),verifySiweMessage:t=>Eue(e,t),verifyTypedData:t=>aue(e,t),uninstallFilter:t=>X0(e,t),waitForTransactionReceipt:t=>Z3(e,t),watchBlockHeaders:t=>uue(e,t),watchBlocks:t=>fue(e,t),watchBlockNumber:t=>n_(e,t),watchContractEvent:t=>M9(e,t),watchEvent:t=>hue(e,t),watchPendingTransactions:t=>gue(e,t),token:oHe(e)}}function oHe(e){return{getAllowance:bu(e,T6),getBalance:bu(e,_6),getMetadata:bu(e,rH),getTotalSupply:bu(e,P6)}}var iH=b(()=>{l();Lie();Jie();Xie();tae();HL();G0();nae();sae();II();$L();FL();i3();ZD();r9();KD();t9();aae();lae();fu();zg();dae();pae();Zf();aT();s9();mae();wae();Eae();y3();Cae();qI();c3();Ile();_le();Nle();Ole();YT();kle();e3();LM();eL();Dle();oi();MM();tue();g3();w3();K3();iue();cue();ZM();due();KM();pue();IL();mue();yue();Aue();sH();Rb();H9();i_();nm()});function Nue(e){let{key:t="public",name:r="Public Client"}=e;return wu({...e,key:t,name:r,type:"publicClient"}).extend(l_)}var Rue=b(()=>{l();nm();iH()});async function Oue(e,{hash:t}){await e.request({method:`${e.mode}_dropTransaction`,params:[t]})}var Bue=b(()=>{l()});async function kue(e){return e.request({method:`${e.mode}_dumpState`})}var Uue=b(()=>{l()});async function Due(e){return e.mode==="ganache"?await e.request({method:"eth_mining"}):await e.request({method:`${e.mode}_getAutomine`})}var Lue=b(()=>{l()});async function Mue(e){return await e.request({method:"txpool_content"})}var Hue=b(()=>{l()});async function $ue(e){let{pending:t,queued:r}=await e.request({method:"txpool_status"});return{pending:wt(t),queued:wt(r)}}var Fue=b(()=>{l();Xr()});async function zue(e,{address:t}){await e.request({method:`${e.mode}_impersonateAccount`,params:[t]})}var Vue=b(()=>{l()});async function jue(e,{seconds:t}){return await e.request({method:"evm_increaseTime",params:[oe(t)]})}var que=b(()=>{l();qe()});async function Wue(e){return await e.request({method:"txpool_inspect"})}var Kue=b(()=>{l()});async function Zue(e,{state:t}){await e.request({method:`${e.mode}_loadState`,params:[t]})}var Gue=b(()=>{l()});async function Yue(e,{blocks:t,interval:r}){e.mode==="ganache"?await e.request({method:"evm_mine",params:[{blocks:oe(t)}]}):await e.request({method:`${e.mode}_mine`,params:[oe(t),oe(r||0)]})}var Jue=b(()=>{l();qe()});async function Que(e){await e.request({method:`${e.mode}_removeBlockTimestampInterval`})}var Xue=b(()=>{l()});async function ede(e,{blockNumber:t,jsonRpcUrl:r}={}){await e.request({method:`${e.mode}_reset`,params:[{forking:{blockNumber:Number(t),jsonRpcUrl:r}}]})}var tde=b(()=>{l()});async function rde(e,{id:t}){await e.request({method:"evm_revert",params:[t]})}var nde=b(()=>{l()});async function ode(e,t){let{accessList:r,data:n,from:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:f,...p}=t,h=e.chain?.formatters?.transactionRequest?.format,w=(h||Bn)({...Ri(p,{format:h}),accessList:r,data:n,from:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:f},"sendUnsignedTransaction");return await e.request({method:"eth_sendUnsignedTransaction",params:[w]})}var sde=b(()=>{l();P0();rl()});async function ide(e,t){e.mode==="ganache"?t?await e.request({method:"miner_start"}):await e.request({method:"miner_stop"}):await e.request({method:"evm_setAutomine",params:[t]})}var ade=b(()=>{l()});async function cde(e,{address:t,value:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountBalance",params:[t,oe(r)]}):await e.request({method:`${e.mode}_setBalance`,params:[t,oe(r)]})}var lde=b(()=>{l();qe()});async function ude(e,{gasLimit:t}){await e.request({method:"evm_setBlockGasLimit",params:[oe(t)]})}var dde=b(()=>{l();qe()});async function fde(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:`${e.mode}_setBlockTimestampInterval`,params:[r]})}var pde=b(()=>{l()});async function hde(e,{address:t,bytecode:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountCode",params:[t,r]}):await e.request({method:`${e.mode}_setCode`,params:[t,r]})}var mde=b(()=>{l()});async function gde(e,{address:t}){await e.request({method:`${e.mode}_setCoinbase`,params:[t]})}var yde=b(()=>{l()});async function wde(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:"evm_setIntervalMining",params:[r]})}var bde=b(()=>{l()});async function xde(e,t){await e.request({method:`${e.mode}_setLoggingEnabled`,params:[t]})}var vde=b(()=>{l()});async function Ede(e,{gasPrice:t}){await e.request({method:`${e.mode}_setMinGasPrice`,params:[oe(t)]})}var Ade=b(()=>{l();qe()});async function Cde(e,{baseFeePerGas:t}){await e.request({method:`${e.mode}_setNextBlockBaseFeePerGas`,params:[oe(t)]})}var Sde=b(()=>{l();qe()});async function Ide(e,{timestamp:t}){await e.request({method:"evm_setNextBlockTimestamp",params:[oe(t)]})}var Tde=b(()=>{l();qe()});async function _de(e,{address:t,nonce:r}){await e.request({method:`${e.mode}_setNonce`,params:[t,oe(r)]})}var Pde=b(()=>{l();qe()});async function Nde(e,t){await e.request({method:`${e.mode}_setRpcUrl`,params:[t]})}var Rde=b(()=>{l()});async function Ode(e,{address:t,index:r,value:n}){await e.request({method:`${e.mode}_setStorageAt`,params:[t,typeof r=="number"?oe(r):r,n]})}var Bde=b(()=>{l();qe()});async function kde(e){return await e.request({method:"evm_snapshot"})}var Ude=b(()=>{l()});async function Dde(e,{address:t}){await e.request({method:`${e.mode}_stopImpersonatingAccount`,params:[t]})}var Lde=b(()=>{l()});function u_({mode:e}){return t=>{let r=t.extend(()=>({mode:e}));return{dropTransaction:n=>Oue(r,n),dumpState:()=>kue(r),getAutomine:()=>Due(r),getTxpoolContent:()=>Mue(r),getTxpoolStatus:()=>$ue(r),impersonateAccount:n=>zue(r,n),increaseTime:n=>jue(r,n),inspectTxpool:()=>Wue(r),loadState:n=>Zue(r,n),mine:n=>Yue(r,n),removeBlockTimestampInterval:()=>Que(r),reset:n=>ede(r,n),revert:n=>rde(r,n),sendUnsignedTransaction:n=>ode(r,n),setAutomine:n=>ide(r,n),setBalance:n=>cde(r,n),setBlockGasLimit:n=>ude(r,n),setBlockTimestampInterval:n=>fde(r,n),setCode:n=>hde(r,n),setCoinbase:n=>gde(r,n),setIntervalMining:n=>wde(r,n),setLoggingEnabled:n=>xde(r,n),setMinGasPrice:n=>Ede(r,n),setNextBlockBaseFeePerGas:n=>Cde(r,n),setNextBlockTimestamp:n=>Ide(r,n),setNonce:n=>_de(r,n),setRpcUrl:n=>Nde(r,n),setStorageAt:n=>Ode(r,n),snapshot:()=>kde(r),stopImpersonatingAccount:n=>Dde(r,n)}}}var aH=b(()=>{l();Bue();Uue();Lue();Hue();Fue();Vue();que();Kue();Gue();Jue();Xue();tde();nde();sde();ade();lde();dde();pde();mde();yde();bde();vde();Ade();Sde();Tde();Pde();Rde();Bde();Ude();Lde()});function Mde(e){let{key:t="test",name:r="Test Client",mode:n}=e;return wu({...e,key:t,name:r,type:"testClient"}).extend(s=>({mode:n,...u_({mode:n})(s)}))}var Hde=b(()=>{l();nm();aH()});async function $de(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:s,blockExplorers:i}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:oe(r),chainName:n,nativeCurrency:o,rpcUrls:s.default.http,blockExplorerUrls:i?Object.values(i).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}var Fde=b(()=>{l();qe()});function zde(e,t){let{abi:r,args:n,bytecode:o,...s}=t,i=tp({abi:r,args:n,bytecode:o});return ue(e,tm,"sendTransaction")({...s,...s.authorizationList?{to:null}:{},data:i})}var Vde=b(()=>{l();p3();_t();x3()});async function jde(e){return e.account?.type==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(r=>Kc(r))}var qde=b(()=>{l();Zs()});async function Wde(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?ft(r):void 0,s=n?[o?.address,[oe(n)]]:[o?.address],i=await e.request({method:"wallet_getCapabilities",params:s}),a={};for(let[c,u]of Object.entries(i)){a[Number(c)]={};for(let[d,f]of Object.entries(u))d==="addSubAccount"&&(d="unstable_addSubAccount"),a[Number(c)][d]=f}return typeof n=="number"?a[n]:a}var Kde=b(()=>{l();tn();qe()});async function Zde(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}var Gde=b(()=>{l()});async function d_(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new kn({docsPath:"/docs/eip7702/prepareAuthorization"});let s=ft(r),i=(()=>{if(t.executor)return t.executor==="self"?t.executor:ft(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};return typeof a.chainId>"u"&&(a.chainId=e.chain?.id??await ue(e,hs,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ue(e,k0,"getTransactionCount")({address:s.address,blockTag:"pending"}),(i==="self"||i?.address&&xr(i.address,s.address))&&(a.nonce+=1)),a}var cH=b(()=>{l();tn();yu();Oi();_t();Zf();e3()});async function Yde(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Gr(r))}var Jde=b(()=>{l();Zs()});async function Qde(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}var Xde=b(()=>{l()});async function efe(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5e3),o=await ue(e,F9,"sendCalls")(t);return await ue(e,j9,"waitForCallsStatus")({...t,id:o.id,timeout:n})}var tfe=b(()=>{l();_t();z9();q9()});async function rfe(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}var nfe=b(()=>{l()});async function ofe(e,t){let{account:r=e.account}=t;if(!r)throw new kn({docsPath:"/docs/eip7702/signAuthorization"});let n=ft(r);if(!n.signAuthorization)throw new fc({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await ue(e,d_,"prepareAuthorization")(t);return n.signAuthorization(o)}var sfe=b(()=>{l();tn();yu();_t();cH()});async function ife(e,{account:t=e.account,message:r}){if(!t)throw new kn({docsPath:"/docs/actions/wallet/signMessage"});let n=ft(t);if(n.signMessage)return n.signMessage({message:r});let o=typeof r=="string"?ec(r):r.raw instanceof Uint8Array?wr(r.raw):r.raw;return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}var afe=b(()=>{l();tn();yu();qe()});async function cfe(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new kn({docsPath:"/docs/actions/wallet/signTransaction"});let s=ft(r);jn({account:s,...t});let i=await ue(e,hs,"getChainId")({});n!==null&&em({currentChainId:i,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||Bn;return s.signTransaction?s.signTransaction({...o,account:s,chainId:i},{serializer:e.chain?.serializers?.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...o,account:s},"signTransaction"),chainId:oe(i),from:s.address}]},{retryCount:0})}var lfe=b(()=>{l();tn();yu();b3();qe();rl();_t();nl();Zf()});async function ufe(e,t){let{account:r=e.account,domain:n,message:o,primaryType:s}=t;if(!r)throw new kn({docsPath:"/docs/actions/wallet/signTypedData"});let i=ft(r),a={EIP712Domain:Zg({domain:n}),...t.types};if(f6({domain:n,message:o,primaryType:s,types:a}),i.signTypedData)return i.signTypedData({domain:n,message:o,primaryType:s,types:a});let c=vT({domain:n,message:o,primaryType:s,types:a});return e.request({method:"eth_signTypedData_v4",params:[i.address,c]},{retryCount:0})}var dfe=b(()=>{l();tn();yu();ET()});async function ffe(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:oe(t)}]},{retryCount:0})}var pfe=b(()=>{l();qe()});async function hfe(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}var mfe=b(()=>{l()});function f_(e){return{addChain:t=>$de(e,t),deployContract:t=>zde(e,t),fillTransaction:t=>Nb(e,t),getAddresses:()=>jde(e),getCallsStatus:t=>V9(e,t),getCapabilities:t=>Wde(e,t),getChainId:()=>hs(e),getPermissions:()=>Zde(e),prepareAuthorization:t=>d_(e,t),prepareTransactionRequest:t=>pu(e,t),requestAddresses:()=>Yde(e),requestPermissions:t=>Qde(e,t),sendCalls:t=>F9(e,t),sendCallsSync:t=>efe(e,t),sendRawTransaction:t=>Gb(e,t),sendRawTransactionSync:t=>S6(e,t),sendTransaction:t=>tm(e,t),sendTransactionSync:t=>a_(e,t),showCallsStatus:t=>rfe(e,t),signAuthorization:t=>ofe(e,t),signMessage:t=>ife(e,t),signTransaction:t=>cfe(e,t),signTypedData:t=>ufe(e,t),switchChain:t=>ffe(e,t),waitForCallsStatus:t=>j9(e,t),watchAsset:t=>hfe(e,t),writeContract:t=>_a(e,t),writeContractSync:t=>I6(e,t),token:{approve:bu(e,ap),approveSync:bu(e,tH),transfer:bu(e,cp),transferSync:bu(e,oH)}}}var lH=b(()=>{l();t9();Zf();sH();Fde();Vde();qde();BL();Kde();Gde();cH();Rb();Jde();Xde();z9();tfe();H9();i_();x3();eH();nfe();sfe();afe();lfe();dfe();pfe();q9();mfe();Yb();c_();nm()});function gfe(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return wu({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(f_)}var yfe=b(()=>{l();nm();lH()});function Au({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:s=150,timeout:i,type:a},c){let u=rm();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:s,timeout:i,type:a},request:Dae(n,{methods:t,retryCount:o,retryDelay:s,uid:u}),value:c}}var N6=b(()=>{l();Mae();A3()});function wfe(e,t={}){let{key:r="custom",methods:n,name:o="Custom Provider",retryDelay:s}=t;return({retryCount:i})=>Au({key:r,methods:n,name:o,request:e.request.bind(e),retryCount:t.retryCount??i,retryDelay:s,type:"custom"})}var bfe=b(()=>{l();N6()});function G3(e,t={}){let{key:r="fallback",name:n="Fallback",rank:o=!1,shouldThrow:s=uH,retryCount:i,retryDelay:a}=t;return(({chain:c,pollingInterval:u=4e3,timeout:d,...f})=>{let p=e,h=()=>{},y=Au({key:r,name:n,async request({method:w,params:x},v){let T,E=async(S=0)=>{let _=p[S]({...f,chain:c,retryCount:0,timeout:d});try{let O=await _.request({method:w,params:x},v);return h({method:w,params:x,response:O,transport:_,status:"success"}),O}catch(O){if(h({error:O,method:w,params:x,transport:_,status:"error"}),s(O)||w==="eth_sendRawTransactionSync"&&O instanceof G&&O.walk(D=>D?.code===4)||S===p.length-1||(T??=p.slice(S+1).some(D=>{let{include:M,exclude:N}=D({chain:c}).config.methods||{};return M?M.includes(w):N?!N.includes(w):!0}),!T))throw O;return E(S+1)}};return E()},retryCount:i,retryDelay:a,type:"fallback"},{onResponse:w=>h=w,transports:p.map(w=>w({chain:c,retryCount:0}))});if(o){let w=typeof o=="object"?o:{};sHe({chain:c,interval:w.interval??u,onTransports:x=>p=x,ping:w.ping,sampleCount:w.sampleCount,timeout:w.timeout,transports:p,weights:w.weights})}return y})}function uH(e){return!!("code"in e&&typeof e.code=="number"&&(e.code===iu.code||e.code===Xc.code||e.code===f0.code||ri.nodeMessage.test(e.message)||e.code===5e3))}function sHe({chain:e,interval:t=4e3,onTransports:r,ping:n,sampleCount:o=10,timeout:s=1e3,transports:i,weights:a={}}){let{stability:c=.7,latency:u=.3}=a,d=[],f=async()=>{let p=await Promise.all(i.map(async w=>{let x=w({chain:e,retryCount:0,timeout:s}),v=Date.now(),T,E;try{await(n?n({transport:x}):x.request({method:"net_listening"})),E=1}catch{E=0}finally{T=Date.now()}return{latency:T-v,success:E}}));d.push(p),d.length>o&&d.shift();let h=Math.max(...d.map(w=>Math.max(...w.map(({latency:x})=>x)))),y=i.map((w,x)=>{let v=d.map(O=>O[x].latency),E=1-v.reduce((O,D)=>O+D,0)/v.length/h,S=d.map(O=>O[x].success),_=S.reduce((O,D)=>O+D,0)/S.length;return _===0?[0,x]:[u*E+c*_,x]}).sort((w,x)=>x[0]-w[0]);r(y.map(([,w])=>i[w])),await $g(t),f()};f()}var xfe=b(()=>{l();nt();tl();Lf();D9();N6()});var pm,p_=b(()=>{l();nt();pm=class extends G{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}});function aHe(e){if(!e)return"default";let t=vfe.get(e);if(t!==void 0)return t;let r=iHe++;return vfe.set(e,r),r}function ry(e,t={}){let{batch:r,fetchFn:n,fetchOptions:o,key:s="http",maxResponseBodySize:i,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:u,onFetchResponse:d,retryDelay:f,raw:p}=t,h=rm();return({chain:y,retryCount:w,timeout:x})=>{let{batchSize:v=1e3,wait:T=0}=typeof r=="object"?r:{},E=t.retryCount??w,S=x??t.timeout??1e4,_=e||y?.rpcUrls.default.http[0];if(!_)throw new pm;let O=mce(_,{fetchFn:n,fetchOptions:o,maxResponseBodySize:i,onRequest:u,onResponse:d,timeout:S});return Au({key:s,methods:a,name:c,async request({method:D,params:M},N){let L={method:D,params:M},P=N?.signal?{signal:N.signal}:void 0,{schedule:R}=Z0({id:`${h}.${_}.${aHe(N?.signal)}`,wait:T,shouldSplitBatch(A){return A.length>v},fn:A=>O.request({body:A,fetchOptions:P}),sort:(A,U)=>A.id-U.id}),I=async A=>r?R(A):[await O.request({body:A,fetchOptions:P})],[{error:B,result:C}]=await I(L).catch(A=>{if(p&&A instanceof Rn)return[{error:A.cause,result:void 0}];throw A});if(p)return{error:B,result:C};if(B)throw new Rn({body:L,error:B,url:_});return C},retryCount:E,retryDelay:f,timeout:S,type:"http"},{fetchOptions:o,url:_})}}var iHe,vfe,Efe=b(()=>{l();fs();p_();h3();gce();A3();N6();iHe=0,vfe=new WeakMap});function Afe(e,t={}){let{keepAlive:r,key:n="webSocket",methods:o,name:s="WebSocket JSON-RPC",reconnect:i,retryDelay:a}=t;return({chain:c,retryCount:u,timeout:d})=>{let f=t.retryCount??u,p=d??t.timeout??1e4,h=e||c?.rpcUrls.default.webSocket?.[0],y={keepAlive:r,reconnect:i};if(!h)throw new pm;return Au({key:n,methods:o,name:s,async request({method:w,params:x}){let v={method:w,params:x},T=await c6(h,y),{error:E,result:S}=await T.requestAsync({body:v,timeout:p});if(E)throw new Rn({body:v,error:E,url:h});return S},retryCount:f,retryDelay:a,timeout:p,type:"webSocket"},{getSocket(){return Cce(h)},getRpcClient(){return c6(h,y)},async subscribe({params:w,onData:x,onError:v}){let T=await c6(h,y),E,S=!1;function _(){return S=!0,new Promise(O=>T.request({body:{method:"eth_unsubscribe",params:[E]},onResponse:O}))}return await new Promise((O,D)=>T.request({body:{method:"eth_subscribe",params:w},onError(M){D(M),v?.(M)},onResponse(M){if(M.error){D(M.error),v?.(M.error);return}if(typeof M.id=="number"){E=M.result,S&&_(),O(M);return}M.method==="eth_subscription"&&x(M.params)}})),{get subscriptionId(){return E},unsubscribe:_}}})}}var Cfe=b(()=>{l();fs();p_();Sce();GL();N6()});var Sfe,Ife,Tfe,_fe=b(()=>{l();Sfe={gwei:9,wei:18},Ife={ether:-9,wei:9},Tfe={ether:-18,gwei:-9}});var h_,Pfe=b(()=>{l();nt();h_=class extends G{constructor({value:t}){super(`Number \`${t}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}}});var m_,Nfe=b(()=>{l();m_=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}}});function Rfe(e){let{abi:t,bytecode:r,data:n}=e;if(n===r)return{bytecode:r};let o=t.find(i=>"type"in i&&i.type==="constructor");if(!o)throw new Oh({docsPath:dH});if(!("inputs"in o))throw new Gl({docsPath:dH});if(!o.inputs||o.inputs.length===0)throw new Gl({docsPath:dH});return{args:Ys(o.inputs,`0x${n.replace(r,"")}`),bytecode:r}}var dH,Ofe=b(()=>{l();Qr();zh();dH="/docs/contract/decodeDeployData"});function Bfe(e){let t=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),r=typeof e.blobs[0]=="string"?e.blobs.map(a=>qt(a)):e.blobs,n=r.reduce((a,c)=>a+c.length,0),o=Zc(new Uint8Array(n)),s=!0;for(let[a,c]of r.entries()){let u=Zc(c),d=a===r.length-1;for(;s&&u.position{l();Jw();Pr();qe()});function Ufe(e){let{sidecars:t,version:r}=e,n=e.to??(typeof t[0].blob=="string"?"hex":"bytes"),o=[];for(let{commitment:s}of t)o.push(Ib({commitment:s,to:n,version:r}));return o}var Dfe=b(()=>{l();ZI()});function Lfe(e){if(e===1)return 60n;if(e>=cHe||e<0)throw new r6({chainId:e});return BigInt((2147483648|e)>>>0)}var cHe,Mfe=b(()=>{l();rT();cHe=2147483648});function g_({blobToKzgCommitment:e,computeBlobKzgProof:t}){return{blobToKzgCommitment:e,computeBlobKzgProof:t}}var fH=b(()=>{l()});function Hfe(e,t){try{e.loadTrustedSetup(t)}catch(r){let n=r;if(!n.message.includes("trusted setup is already loaded"))throw n}return g_(e)}var $fe=b(()=>{l();fH()});function Ffe({r:e,yParityAndS:t}){let r=qt(Zr(t)),n=r[0]&128?1:0,o=r;return n===1&&(o[0]&=127),{r:Zr(e),s:yt(o),yParity:n}}var zfe=b(()=>{l();Xa();Pr();qe()});function pH(e){let{r:t,s:r}=ei.Signature.fromCompact(e.slice(2,130));return{r:oe(t,{size:32}),yParityAndS:oe(r,{size:32})}}var Vfe=b(()=>{l();Bg();qe()});function hH(e){let{r:t,s:r}=ei.Signature.fromCompact(e.slice(2,130)),n=+`0x${e.slice(130)}`,[o,s]=(()=>{if(n===0||n===1)return[void 0,n];if(n===27)return[BigInt(n),0];if(n===28)return[BigInt(n),1];throw new Error("Invalid yParityOrV value")})();return typeof o<"u"?{r:oe(t,{size:32}),s:oe(r,{size:32}),v:o,yParity:s}:{r:oe(t,{size:32}),s:oe(r,{size:32}),yParity:s}}var jfe=b(()=>{l();Bg();qe()});async function qfe(e){let{serializedTransaction:t,signature:r}=e,n=WT(t),o=r??{r:n.r,s:n.s,v:n.v,yParity:n.yParity},s=fT({...n,r:void 0,s:void 0,v:void 0,yParity:void 0,sidecars:void 0});return await ti({hash:Pt(s),signature:o})}var Wfe=b(()=>{l();Ks();kM();pT();w0()});function mH({r:e,yParityAndS:t}){return`0x${new ei.Signature(dt(e),dt(t)).toCompactHex()}`}var Kfe=b(()=>{l();Bg();Xr()});function Zfe(e){let{r:t,s:r,v:n,yParity:o}=e,s=(()=>{if(o===0||o===1)return o;if(n===0n||n===1n)return Number(n);if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),i=qt(Zr(r));if(i[0]&128)throw new Error("Invalid `s` value");return s===1&&(i[0]|=128),{r:Zr(t),yParityAndS:yt(i)}}var Gfe=b(()=>{l();Xa();Pr();qe()});var Yfe={};Te(Yfe,{AbiConstructorNotFoundError:()=>Oh,AbiConstructorParamsNotFoundError:()=>Gl,AbiDecodingDataSizeInvalidError:()=>yI,AbiDecodingDataSizeTooSmallError:()=>Bh,AbiDecodingSizeLimitExceededError:()=>Xw,AbiDecodingZeroDataError:()=>Ci,AbiEncodingArrayLengthMismatchError:()=>Nw,AbiEncodingBytesSizeMismatchError:()=>Rw,AbiEncodingLengthMismatchError:()=>kh,AbiErrorInputsNotFoundError:()=>Ow,AbiErrorNotFoundError:()=>pg,AbiErrorSignatureNotFoundError:()=>Uh,AbiEventAmbiguityError:()=>Gf,AbiEventNotFoundError:()=>hg,AbiEventSignatureEmptyTopicsError:()=>Yl,AbiEventSignatureNotFoundError:()=>Jl,AbiFunctionNotFoundError:()=>wa,AbiFunctionOutputsNotFoundError:()=>Dh,AbiFunctionSignatureNotFoundError:()=>Bw,AccountStateConflictError:()=>tb,AtomicReadyWalletRejectedUpgradeError:()=>d0,AtomicityNotSupportedError:()=>cu,BaseError:()=>G,BaseFeeScalarError:()=>O0,BlockNotFoundError:()=>du,BundleFailedError:()=>Jb,BundleTooLargeError:()=>u0,BytesSizeMismatchError:()=>Lh,CallExecutionError:()=>Yc,ChainDisconnectedError:()=>s0,ChainDoesNotSupportContract:()=>Wf,ChainMismatchError:()=>U0,ChainNotConfiguredError:()=>C3,ChainNotFoundError:()=>Sb,CircularReferenceError:()=>lg,ClientChainNotConfiguredError:()=>kg,ContractFunctionExecutionError:()=>ab,ContractFunctionRevertedError:()=>Uf,ContractFunctionZeroDataError:()=>cb,CounterfactualDeploymentFailedError:()=>lb,DecodeLogDataMismatch:()=>jc,DecodeLogTopicsMismatch:()=>Ql,DuplicateIdError:()=>c0,EIP1193ProviderRpcError:()=>m_,Eip1559FeesNotSupportedError:()=>uu,EnsAvatarInvalidNftUriError:()=>xu,EnsAvatarUnsupportedNamespaceError:()=>t6,EnsAvatarUriResolutionError:()=>om,EnsInvalidChainIdError:()=>r6,EstimateGasExecutionError:()=>bb,ExecutionRevertedError:()=>ri,FeeCapTooHighError:()=>Pi,FeeCapTooLowError:()=>x0,FeeConflictError:()=>BI,FeePayerNonceMismatchError:()=>Wh,FilterTypeNotSupportedError:()=>Lw,HttpRequestError:()=>Nr,InsufficientFundsError:()=>C0,IntegerOutOfRangeError:()=>Xl,InternalRpcError:()=>Qc,IntrinsicGasTooHighError:()=>S0,IntrinsicGasTooLowError:()=>I0,InvalidAbiDecodingTypeError:()=>Uw,InvalidAbiEncodingTypeError:()=>kw,InvalidAbiItemError:()=>Q1,InvalidAbiParameterError:()=>eg,InvalidAbiParametersError:()=>tg,InvalidAbiTypeParameterError:()=>ig,InvalidAddressError:()=>br,InvalidArrayError:()=>Mh,InvalidBytesBooleanError:()=>Mw,InvalidChainIdError:()=>Kf,InvalidDecimalNumberError:()=>h_,InvalidDefinitionTypeError:()=>Pw,InvalidDomainError:()=>l6,InvalidFunctionModifierError:()=>sg,InvalidHexBooleanError:()=>Hw,InvalidHexValueError:()=>$w,InvalidInputRpcError:()=>Ti,InvalidLegacyVError:()=>Kh,InvalidModifierError:()=>og,InvalidParameterError:()=>rg,InvalidParamsRpcError:()=>Qh,InvalidParenthesisError:()=>ug,InvalidPrimaryTypeError:()=>u6,InvalidRequestRpcError:()=>Jh,InvalidSerializableTransactionError:()=>nb,InvalidSerializedTransactionError:()=>ru,InvalidSerializedTransactionTypeError:()=>ob,InvalidSignatureError:()=>ya,InvalidStorageKeySizeError:()=>sb,InvalidStructSignatureError:()=>cg,InvalidStructTypeError:()=>d6,InvalidTypedDataTypeError:()=>Kg,InvalidYParityError:()=>tu,JsonRpcVersionUnsupportedError:()=>t0,LimitExceededRpcError:()=>Df,MaxFeePerGasTooLowError:()=>vb,MethodNotFoundRpcError:()=>Jc,MethodNotSupportedRpcError:()=>Aa,NonceMaxValueError:()=>A0,NonceTooHighError:()=>v0,NonceTooLowError:()=>E0,ParseRpcError:()=>Yh,ProviderDisconnectedError:()=>o0,ProviderRpcError:()=>Ao,RawContractError:()=>sc,ResourceNotFoundRpcError:()=>Xh,ResourceUnavailableRpcError:()=>e0,ResponseBodyTooLargeError:()=>ic,RlpDepthLimitExceededError:()=>Fw,RlpListBoundaryExceededError:()=>zw,RlpTrailingBytesError:()=>Vw,RpcError:()=>Eo,RpcRequestError:()=>Rn,SizeExceedsPaddingSizeError:()=>gg,SizeOverflowError:()=>jw,SliceOffsetOutOfBoundsError:()=>mg,SocketClosedError:()=>su,SolidityProtectedKeywordError:()=>ng,StateAssignmentConflictError:()=>rb,SwitchChainError:()=>i0,TimeoutError:()=>ds,TipAboveFeeCapError:()=>ac,TransactionExecutionError:()=>ib,TransactionNotFoundError:()=>Gc,TransactionReceiptNotFoundError:()=>nu,TransactionRejectedRpcError:()=>iu,TransactionTypeNotSupportedError:()=>T0,TransportNotConfiguredError:()=>S3,UnauthorizedProviderError:()=>r0,UnknownBundleIdError:()=>l0,UnknownNodeError:()=>Ni,UnknownRpcError:()=>ub,UnknownSignatureError:()=>ag,UnknownTypeError:()=>X1,UnsupportedChainIdError:()=>a0,UnsupportedNonOptionalCapabilityError:()=>au,UnsupportedPackedAbiType:()=>Dw,UnsupportedProviderMethodError:()=>n0,UrlRequiredError:()=>pm,UserRejectedRequestError:()=>Xc,WaitForCallsStatusTimeoutError:()=>E3,WaitForTransactionReceiptTimeoutError:()=>Gh,WebSocketRequestError:()=>_g,assertCurrentChain:()=>em,assertRequest:()=>jn,assertTransactionEIP1559:()=>sm,assertTransactionEIP2930:()=>n6,assertTransactionLegacy:()=>o6,blobsToCommitments:()=>D0,blobsToProofs:()=>L0,boolToBytes:()=>KU,boolToHex:()=>wg,bytesToBigInt:()=>B4,bytesToBool:()=>k4,bytesToHex:()=>yt,bytesToNumber:()=>Ea,bytesToRlp:()=>Mne,bytesToString:()=>U4,ccipFetch:()=>Hg,ccipReadTunnel:()=>Hae,ccipRequest:()=>Hg,checksumAddress:()=>Kc,commitmentToVersionedHash:()=>Ib,commitmentsToVersionedHashes:()=>Tb,compactSignatureToHex:()=>mH,compactSignatureToSignature:()=>Ffe,concat:()=>en,concatBytes:()=>eD,concatHex:()=>fr,createClient:()=>wu,createClientResolver:()=>Oie,createNonceManager:()=>WL,createPublicClient:()=>Nue,createTestClient:()=>Mde,createTransport:()=>Au,createWalletClient:()=>gfe,custom:()=>wfe,decodeAbiParameters:()=>Ys,decodeDeployData:()=>Rfe,decodeErrorResult:()=>Vh,decodeEventLog:()=>Yf,decodeFunctionData:()=>T9,decodeFunctionResult:()=>dn,defineBlock:()=>Dse,defineChain:()=>Fae,defineKzg:()=>g_,defineTransaction:()=>Use,defineTransactionReceipt:()=>Sie,defineTransactionRequest:()=>Wne,deploylessCallViaBytecodeBytecode:()=>zb,deploylessCallViaFactoryBytecode:()=>v9,domainSeparator:()=>Ice,encodeAbiParameters:()=>oo,encodeDeployData:()=>tp,encodeErrorResult:()=>m3,encodeEventTopics:()=>nc,encodeFunctionData:()=>Wt,encodeFunctionResult:()=>_9,encodePacked:()=>Sae,erc1155Abi:()=>die,erc20Abi:()=>Hr,erc20Abi_bytes32:()=>uie,erc4626Abi:()=>pie,erc6492SignatureValidatorAbi:()=>Fb,erc6492SignatureValidatorByteCode:()=>f3,erc721Abi:()=>fie,ethAddress:()=>v6,etherUnits:()=>Sfe,extendSchema:()=>zae,extractChain:()=>jae,fallback:()=>G3,formatBlock:()=>qf,formatEther:()=>qh,formatGwei:()=>Pn,formatLog:()=>qn,formatTransaction:()=>jf,formatTransactionReceipt:()=>op,formatTransactionRequest:()=>Bn,formatUnits:()=>pc,fromBlobs:()=>Bfe,fromBytes:()=>zre,fromHex:()=>WU,fromRlp:()=>Wg,getAbiItem:()=>ls,getAddress:()=>Gr,getChainContractAddress:()=>Ui,getContract:()=>Aie,getContractAddress:()=>_ae,getContractError:()=>Js,getCreate2Address:()=>jL,getCreateAddress:()=>VL,getEventSelector:()=>Wc,getEventSignature:()=>Pf,getFunctionSelector:()=>va,getFunctionSignature:()=>Pf,getSerializedTransactionType:()=>qT,getTransactionType:()=>Pb,getTypesForEIP712Domain:()=>Zg,gweiUnits:()=>Ife,hashDomain:()=>_3,hashMessage:()=>im,hashStruct:()=>AT,hashTypedData:()=>p6,hexToBigInt:()=>dt,hexToBool:()=>qw,hexToBytes:()=>qt,hexToCompactSignature:()=>pH,hexToNumber:()=>wt,hexToRlp:()=>Hne,hexToSignature:()=>hH,hexToString:()=>bI,http:()=>ry,isAddress:()=>Ft,isAddressEqual:()=>xr,isBytes:()=>I3,isErc6492Signature:()=>IT,isErc8010Signature:()=>zT,isHash:()=>i6,isHex:()=>We,keccak256:()=>Pt,labelhash:()=>J9,maxInt104:()=>ioe,maxInt112:()=>aoe,maxInt120:()=>coe,maxInt128:()=>loe,maxInt136:()=>uoe,maxInt144:()=>doe,maxInt152:()=>foe,maxInt16:()=>Gne,maxInt160:()=>poe,maxInt168:()=>hoe,maxInt176:()=>moe,maxInt184:()=>goe,maxInt192:()=>yoe,maxInt200:()=>woe,maxInt208:()=>boe,maxInt216:()=>xoe,maxInt224:()=>voe,maxInt232:()=>Eoe,maxInt24:()=>Yne,maxInt240:()=>Aoe,maxInt248:()=>Coe,maxInt256:()=>Soe,maxInt32:()=>Jne,maxInt40:()=>Qne,maxInt48:()=>Xne,maxInt56:()=>eoe,maxInt64:()=>toe,maxInt72:()=>roe,maxInt8:()=>Zne,maxInt80:()=>noe,maxInt88:()=>ooe,maxInt96:()=>soe,maxUint104:()=>gse,maxUint112:()=>yse,maxUint120:()=>wse,maxUint128:()=>bse,maxUint136:()=>xse,maxUint144:()=>vse,maxUint152:()=>Ese,maxUint16:()=>sse,maxUint160:()=>Ase,maxUint168:()=>Cse,maxUint176:()=>Sse,maxUint184:()=>Ise,maxUint192:()=>Tse,maxUint200:()=>_se,maxUint208:()=>Pse,maxUint216:()=>Nse,maxUint224:()=>Rse,maxUint232:()=>Ose,maxUint24:()=>ise,maxUint240:()=>Bse,maxUint248:()=>kse,maxUint256:()=>R0,maxUint32:()=>ase,maxUint40:()=>cse,maxUint48:()=>lse,maxUint56:()=>use,maxUint64:()=>dse,maxUint72:()=>fse,maxUint8:()=>ose,maxUint80:()=>pse,maxUint88:()=>hse,maxUint96:()=>mse,minInt104:()=>Moe,minInt112:()=>Hoe,minInt120:()=>$oe,minInt128:()=>Foe,minInt136:()=>zoe,minInt144:()=>Voe,minInt152:()=>joe,minInt16:()=>Toe,minInt160:()=>qoe,minInt168:()=>Woe,minInt176:()=>Koe,minInt184:()=>Zoe,minInt192:()=>Goe,minInt200:()=>Yoe,minInt208:()=>Joe,minInt216:()=>Qoe,minInt224:()=>Xoe,minInt232:()=>ese,minInt24:()=>_oe,minInt240:()=>tse,minInt248:()=>rse,minInt256:()=>nse,minInt32:()=>Poe,minInt40:()=>Noe,minInt48:()=>Roe,minInt56:()=>Ooe,minInt64:()=>Boe,minInt72:()=>koe,minInt8:()=>Ioe,minInt80:()=>Uoe,minInt88:()=>Doe,minInt96:()=>Loe,multicall3Abi:()=>ki,namehash:()=>Vg,nonceManager:()=>dce,numberToBytes:()=>ZU,numberToHex:()=>oe,offchainLookup:()=>B9,offchainLookupAbiItem:()=>O9,offchainLookupSignature:()=>R9,pad:()=>Zr,padBytes:()=>qU,padHex:()=>cs,parseAbi:()=>Iw,parseAbiItem:()=>Tw,parseAbiParameter:()=>zU,parseAbiParameters:()=>_w,parseCompactSignature:()=>pH,parseErc6492Signature:()=>sle,parseErc8010Signature:()=>ale,parseEther:()=>ble,parseEventLogs:()=>cc,parseGwei:()=>vle,parseSignature:()=>hH,parseTransaction:()=>WT,parseUnits:()=>GT,prepareEncodeFunctionData:()=>TI,presignMessagePrefix:()=>bT,publicActions:()=>l_,recoverAddress:()=>ti,recoverMessageAddress:()=>VT,recoverPublicKey:()=>zI,recoverTransactionAddress:()=>qfe,recoverTypedDataAddress:()=>jT,ripemd160:()=>sce,rpcSchema:()=>Rie,rpcTransactionType:()=>qD,serializeAccessList:()=>qg,serializeCompactSignature:()=>mH,serializeErc6492Signature:()=>lle,serializeErc8010Signature:()=>dle,serializeSignature:()=>W3,serializeTransaction:()=>fT,serializeTypedData:()=>vT,setErrorConfig:()=>cre,setupKzg:()=>Hfe,sha256:()=>KI,shouldThrow:()=>uH,sidecarsToVersionedHashes:()=>Ufe,signatureToCompactSignature:()=>Zfe,signatureToHex:()=>W3,size:()=>gt,slice:()=>vo,sliceBytes:()=>_4,sliceHex:()=>xa,stringToBytes:()=>zo,stringToHex:()=>ec,stringify:()=>bt,testActions:()=>u_,toBlobSidecars:()=>M0,toBlobs:()=>XI,toBytes:()=>un,toCoinType:()=>Lfe,toEventHash:()=>Nf,toEventSelector:()=>Wc,toEventSignature:()=>Pf,toFunctionHash:()=>Nf,toFunctionSelector:()=>va,toFunctionSignature:()=>Pf,toHex:()=>wr,toPrefixedMessage:()=>xT,toRlp:()=>Vo,transactionType:()=>Q4,trim:()=>bn,universalSignatureValidatorAbi:()=>Fb,universalSignatureValidatorByteCode:()=>f3,validateTypedData:()=>f6,verifyHash:()=>ple,verifyMessage:()=>mle,verifyTypedData:()=>yle,walletActions:()=>f_,webSocket:()=>Afe,weiUnits:()=>Tfe,withCache:()=>L9,withRetry:()=>np,withTimeout:()=>sl,zeroAddress:()=>dm,zeroHash:()=>Nce});var R6=b(()=>{l();fg();Cie();q9();nm();Bie();Rue();Hde();yfe();iH();aH();lH();N6();bfe();xfe();Efe();Cfe();So();t_();ST();Vb();jI();YL();_fe();Qr();tc();nt();J4();PL();Ug();ou();C4();yg();rT();jD();Eb();jU();tl();fs();Lf();OI();zn();p_();QL();Pfe();Nfe();zh();Ofe();L4();a3();gL();lc();rc();p3();wL();Cg();us();xL();Tae();Bf();Dg();iD();Zs();Pae();Gs();Oi();t3();r3();GI();ZI();kfe();Dfe();n3();JD();k9();$ae();b3();Vae();qae();K0();Fn();zL();qs();Xa();Fo();Si();Hh();cD();Xr();mT();Pr();qe();wb();UL();Y9();Mfe();p0();X4();hu();Ab();Qb();rl();gT();Ks();ice();GD();ace();Kw();cce();lce();Ag();uce();fH();$fe();fce();SL();v3();Kb();zfe();T3();P3();XL();NM();Vfe();ile();cle();jfe();w0();RM();VD();Wfe();OM();Kfe();ule();fle();WM();Gfe();JL();hle();gle();wle();so();nl();dT();BM();e9();kM();qL();pT();ET();M4();Ig();z3();xle();Ele();UM()});async function Y3(...e){let t=await fetch(...e);if(!t.ok)throw new Error(`HTTP status code: ${t.status}`,{cause:t});return t}var Di,O6=b(()=>{l();Di=class{constructor({baseUrl:t,clientId:r}){this.baseUrl=t,this.clientId=r}async get({headers:t,signal:r,cache:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"GET",headers:t,signal:r,cache:n})).json()}async getBlob({headers:t,signal:r,...n}){let o=this.createUrl(n);return(await Y3(o,{method:"GET",headers:t,signal:r})).blob()}async post({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"POST",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}async put({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"PUT",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}async delete({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"DELETE",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}createUrl({path:t,params:r}){let n=new URL(t,this.baseUrl);return r&&Object.entries(r).forEach(([o,s])=>{s&&n.searchParams.append(o,s)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:t,...r}){let n=this.createUrl(r);return navigator.sendBeacon(n.toString(),t?JSON.stringify(t):void 0)}}});var J3,gH=b(()=>{l();Un();ha();$n();J3={getFeatureValue(e,t){let r=t?.[e];return r===void 0?Ye.DEFAULT_FEATURES[e]:r},filterSocialsByPlatform(e){if(!e||!e.length)return e;let t=e;return se.isTelegram()&&(se.isIos()&&(t=t.filter(r=>r!=="google")),se.isMac()&&(t=t.filter(r=>r!=="x")),se.isAndroid()&&(t=t.filter(r=>!["facebook","x"].includes(r)))),se.isMobile()&&(t=t.filter(r=>r!=="facebook")),t},isSocialsEnabled(){return Array.isArray(Y.state.features?.socials)&&Y.state.features?.socials.length>0||Array.isArray(Y.state.remoteFeatures?.socials)&&Y.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(Y.state.features?.email||Y.state.remoteFeatures?.email)}}});var Ze,Y,Un=b(()=>{l();Lr();Hn();ha();$n();gH();Ze=rt({features:Ye.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ye.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),Y={state:Ze,subscribeKey(e,t){return Tt(Ze,e,t)},setOptions(e){Object.assign(Ze,e)},setRemoteFeatures(e){if(!e)return;let t={...Ze.remoteFeatures,...e};Ze.remoteFeatures=t,Ze.remoteFeatures?.socials&&(Ze.remoteFeatures.socials=J3.filterSocialsByPlatform(Ze.remoteFeatures.socials)),Ze.features?.pay&&(Ze.remoteFeatures.email=!1,Ze.remoteFeatures.socials=!1)},setFeatures(e){if(!e)return;Ze.features||(Ze.features=Ye.DEFAULT_FEATURES);let t={...Ze.features,...e};Ze.features=t,Ze.features?.pay&&Ze.remoteFeatures&&(Ze.remoteFeatures.email=!1,Ze.remoteFeatures.socials=!1)},setProjectId(e){Ze.projectId=e},setCustomRpcUrls(e){Ze.customRpcUrls=e},setAllWallets(e){Ze.allWallets=e},setIncludeWalletIds(e){Ze.includeWalletIds=e},setExcludeWalletIds(e){Ze.excludeWalletIds=e},setFeaturedWalletIds(e){Ze.featuredWalletIds=e},setTokens(e){Ze.tokens=e},setTermsConditionsUrl(e){Ze.termsConditionsUrl=e},setPrivacyPolicyUrl(e){Ze.privacyPolicyUrl=e},setCustomWallets(e){Ze.customWallets=e},setIsSiweEnabled(e){Ze.isSiweEnabled=e},setIsUniversalProvider(e){Ze.isUniversalProvider=e},setSdkVersion(e){Ze.sdkVersion=e},setMetadata(e){Ze.metadata=e},setDisableAppend(e){Ze.disableAppend=e},setEIP6963Enabled(e){Ze.enableEIP6963=e},setDebug(e){Ze.debug=e},setEnableWalletGuide(e){Ze.enableWalletGuide=e},setEnableAuthLogger(e){Ze.enableAuthLogger=e},setEnableWallets(e){Ze.enableWallets=e},setPreferUniversalLinks(e){Ze.experimental_preferUniversalLinks=e},setSIWX(e){if(e)for(let[t,r]of Object.entries(Ye.SIWX_DEFAULTS))e[t]??=r;Ze.siwx=e},setConnectMethodsOrder(e){Ze.features={...Ze.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){Ze.features={...Ze.features,walletFeaturesOrder:e}},setSocialsOrder(e){Ze.remoteFeatures={...Ze.remoteFeatures,socials:e}},setCollapseWallets(e){Ze.features={...Ze.features,collapseWallets:e}},setEnableEmbedded(e){Ze.enableEmbedded=e},setAllowUnsupportedChain(e){Ze.allowUnsupportedChain=e},setManualWCControl(e){Ze.manualWCControl=e},setEnableNetworkSwitch(e){Ze.enableNetworkSwitch=e},setEnableMobileFullScreen(e){Ze.enableMobileFullScreen=se.isMobile()&&e},setEnableReconnect(e){Ze.enableReconnect=e},setCoinbasePreference(e){Ze.coinbasePreference=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([t,r])=>{r&&(Ze.defaultAccountTypes[t]=r)})},setUniversalProviderConfigOverride(e){Ze.universalProviderConfigOverride=e},getUniversalProviderConfigOverride(){return Ze.universalProviderConfigOverride},getSnapshot(){return Kl(Ze)}}});var ny,ao,lHe,Je,hm=b(()=>{l();Lr();Hn();$n();ny=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ao=rt({...ny}),lHe={state:ao,subscribeKey(e,t){return Tt(ao,e,t)},showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){let t=se.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){ao.message=ny.message,ao.variant=ny.variant,ao.svg=ny.svg,ao.open=ny.open,ao.autoClose=ny.autoClose},_showMessage({message:e,svg:t,variant:r="success",autoClose:n=ny.autoClose}){ao.open?(ao.open=!1,setTimeout(()=>{ao.message=e,ao.variant=r,ao.svg=t,ao.open=!0,ao.autoClose=n},150)):(ao.message=e,ao.variant=r,ao.svg=t,ao.open=!0,ao.autoClose=n)}},Je=lHe});var uHe,Jfe,si,ze,lp=b(()=>{l();Lr();ha();$n();O6();ma();$r();Un();hm();uHe={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Jfe=se.getBlockchainApiUrl(),si=rt({clientId:null,api:new Di({baseUrl:Jfe,clientId:null}),supportedChains:{http:[],ws:[]}}),ze={state:si,async get(e){let{st:t,sv:r}=ze.getSdkProperties(),n=Y.state.projectId,o={...e.params||{},st:t,sv:r,projectId:n};return si.api.get({...e,params:o})},getSdkProperties(){let{sdkType:e,sdkVersion:t}=Y.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{si.supportedChains.http.length||await ze.getSupportedNetworks()}catch{return!1}return si.supportedChains.http.includes(e)},async getSupportedNetworks(){try{let e=await ze.get({path:"v1/supported-chains"});return si.supportedChains=e,e}catch{return si.supportedChains}},async fetchIdentity({address:e}){let t=de.getIdentityFromCacheForAddress(e);if(t)return t;let r=await ze.get({path:`/v1/identity/${e}`,params:{sender:$.state.activeCaipAddress?se.getPlainAddress($.state.activeCaipAddress):void 0}});return de.updateIdentityCache({address:e,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:e,cursor:t,signal:r,cache:n,chainId:o}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};let i=de.getTransactionsCacheForAddress({address:e,chainId:o});if(i)return i;let a=await ze.get({path:`/v1/account/${e}/history`,params:{cursor:t,chainId:o},signal:r,cache:n});return de.updateTransactionsCache({address:e,chainId:o,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:e,userAddress:t,from:r,to:n,gasPrice:o}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:r,to:n,gasPrice:o}}):{quotes:[]}},async fetchSwapTokens({chainId:e}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]}},async getAddressBalance({caipNetworkId:e,address:t}){return si.api.post({path:`/v1?chainId=${e}&projectId=${Y.state.projectId}`,body:{id:"1",jsonrpc:"2.0",method:"getAddressBalance",params:{address:t}}}).then(r=>r.result)},async fetchTokenPrice({addresses:e,caipNetworkId:t=$.state.activeCaipNetwork?.caipNetworkId}){if(!await ze.isNetworkSupported(t))return{fungibles:[]};let n=de.getTokenPriceCacheForAddresses(e);if(n)return n;let o=await si.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:Y.state.projectId},headers:{"Content-Type":"application/json"}});return de.updateTokenPriceCache({addresses:e,timestamp:Date.now(),tokenPrice:o}),o},async fetchSwapAllowance({tokenAddress:e,userAddress:t}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:e}){let{st:t,sv:r}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return ze.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:t,sv:r}})},async generateSwapCalldata({amount:e,from:t,to:r,userAddress:n,disableEstimate:o}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return si.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:Ye.CONVERT_SLIPPAGE_TOLERANCE},projectId:Y.state.projectId,from:t,to:r,userAddress:n,disableEstimate:o}})},async generateApproveCalldata({from:e,to:t,userAddress:r}){let{st:n,sv:o}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ze.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:r,from:e,to:t,st:n,sv:o}})},async getBalance(e,t,r){let{st:n,sv:o}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return Je.showError("Token Balance Unavailable"),{balances:[]};let i=`${t}:${e}`,a=de.getBalanceCacheForCaipAddress(i);if(a)return a;let c=await ze.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:r,st:n,sv:o}});return de.updateBalanceCache({caipAddress:i,balance:c,timestamp:Date.now()}),c},async lookupEnsName(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:e}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return[];let r=$.getAccountData()?.address;return ze.get({path:`/v1/profile/reverse/${e}`,params:{sender:r,apiVersion:"2"}})},async getEnsNameSuggestions(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:e,address:t,message:r,signature:n}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?si.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:r,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:e,partnerUserId:t,defaultNetwork:r,purchaseAmount:n,paymentAmount:o}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?(await si.api.post({path:"/v1/generators/onrampurl",params:{projectId:Y.state.projectId},body:{destinationWallets:e,defaultNetwork:r,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:o}})).url:""},async getOnrampOptions(){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await ze.get({path:"/v1/onramp/options"})}catch{return uHe}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:r,network:n}){try{return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?await si.api.post({path:"/v1/onramp/quote",params:{projectId:Y.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:r,network:n}}):null}catch{return{networkFee:{amount:r,currency:t.id},paymentSubtotal:{amount:r,currency:t.id},paymentTotal:{amount:r,currency:t.id},purchaseAmount:{amount:r,currency:t.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/sessions/${e}`}):[]},async revokeSmartSession(e,t,r){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?si.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:Y.state.projectId},body:{pci:t,signature:r}}):{success:!1}},setClientId(e){si.clientId=e,si.api=new Di({baseUrl:Jfe,clientId:e})}}});var mm=b(()=>{l();g4()});var dHe,fHe,pHe,hHe,gm,Qfe,Xfe=b(()=>{l();Lr();Hn();$n();O6();Un();dHe=Object.freeze({enabled:!0,events:[]}),fHe=new Di({baseUrl:se.getAnalyticsUrl(),clientId:null}),pHe=5,hHe=60*1e3,gm=rt({...dHe}),Qfe={state:gm,subscribeKey(e,t){return Tt(gm,e,t)},async sendError(e,t){if(!gm.enabled)return;let r=Date.now();if(gm.events.filter(s=>{let i=new Date(s.properties.timestamp||"").getTime();return r-i=pHe)return;let o={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:new Date().toISOString()}};gm.events.push(o);try{if(typeof window>"u")return;let{projectId:s,sdkType:i,sdkVersion:a}=Y.state;await fHe.post({path:"/e",params:{projectId:s,st:i,sv:a||"html-wagmi-4.2.2"},body:{eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){gm.enabled=!0},disable(){gm.enabled=!1},clearEvents(){gm.events=[]}}});function epe(e,t){let r="";try{e instanceof Error?r=e.message:typeof e=="string"?r=e:typeof e=="object"&&e!==null?Object.keys(e).length===0?r="Unknown error":r=e?.message||JSON.stringify(e):r=String(e)}catch(o){r="Unknown error",console.error("Error parsing error message",o)}let n=e instanceof hc?e:new hc(r,t,e);throw Qfe.sendError(n,n.category),n}function vr(e,t="INTERNAL_SDK_ERROR"){let r={};return Object.keys(e).forEach(n=>{let o=e[n];if(typeof o=="function"){let s=o;o.constructor.name==="AsyncFunction"?s=async(...i)=>{try{return await o(...i)}catch(a){return epe(a,t)}}:s=(...i)=>{try{return o(...i)}catch(a){return epe(a,t)}},r[n]=s}else r[n]=o}),r}var hc,gs=b(()=>{l();Xfe();hc=class e extends Error{constructor(t,r,n){super(t),this.originalName="AppKitError",this.name="AppKitError",this.category=r,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,e.prototype);let o=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){let s=n.stack,i=s.indexOf(` +`),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(ac,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Ri=class extends G{constructor({cause:t}){super(`An error occurred while executing: ${t?.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}});function _0(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof G?e.walk(o=>o?.code===ri.code):e;return n instanceof G?new ri({cause:e,message:n.details}):ri.nodeMessage.test(r)?new ri({cause:e,message:e.details}):Ni.nodeMessage.test(r)?new Ni({cause:e,maxFeePerGas:t?.maxFeePerGas}):x0.nodeMessage.test(r)?new x0({cause:e,maxFeePerGas:t?.maxFeePerGas}):v0.nodeMessage.test(r)?new v0({cause:e,nonce:t?.nonce}):E0.nodeMessage.test(r)?new E0({cause:e,nonce:t?.nonce}):A0.nodeMessage.test(r)?new A0({cause:e,nonce:t?.nonce}):C0.nodeMessage.test(r)?new C0({cause:e}):S0.nodeMessage.test(r)?new S0({cause:e,gas:t?.gas}):I0.nodeMessage.test(r)?new I0({cause:e,gas:t?.gas}):T0.nodeMessage.test(r)?new T0({cause:e}):ac.nodeMessage.test(r)?new ac({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new Ri({cause:e})}var G4=b(()=>{l();nt();tl()});function jne(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ri?e:o})();return new bb(n,{docsPath:t,...r})}var qne=b(()=>{l();jD();tl();G4()});function Oi(e,{format:t}){if(!t)return{};let r={};function n(s){let i=Object.keys(s);for(let a of i)a in e&&(r[a]=e[a]),s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&n(s[a])}let o=t(e||{});return n(o),r}var P0=b(()=>{l()});function N0(e,t){return({exclude:r,format:n})=>({exclude:r,format:(o,s)=>{let i=t(o,s);if(r)for(let a of r)delete i[a];return{...i,...n(o,s)}},type:e})}var Y4=b(()=>{l()});function Bn(e,t){let r={};return typeof e.authorizationList<"u"&&(r.authorizationList=pDe(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>yt(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=oe(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=oe(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=oe(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=oe(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=oe(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=oe(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=qD[e.type]),typeof e.value<"u"&&(r.value=oe(e.value)),r}function pDe(e){return e.map(t=>({address:t.address,r:t.r?oe(BigInt(t.r)):t.r,s:t.s?oe(BigInt(t.s)):t.s,chainId:oe(t.chainId),nonce:oe(t.nonce),...typeof t.yParity<"u"?{yParity:oe(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:oe(t.v)}:{}}))}var qD,Wne,rl=b(()=>{l();qe();Y4();qD={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};Wne=N0("transactionRequest",Bn)});function Kne(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new A4({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new A4({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function hDe(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:s}=e,i={};if(s!==void 0&&(i.code=s),t!==void 0&&(i.balance=oe(t)),r!==void 0&&(i.nonce=oe(r)),n!==void 0&&(i.state=Kne(n)),o!==void 0){if(i.state)throw new rb;i.stateDiff=Kne(o)}return i}function xb(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!Ft(r,{strict:!1}))throw new br({address:r});if(t[r])throw new tb({address:r});t[r]=hDe(n)}return t}var VI=b(()=>{l();tc();C4();OI();Gs();qe()});var Zne,Gne,Yne,Jne,Qne,Xne,eoe,toe,roe,noe,ooe,soe,ioe,aoe,coe,loe,uoe,doe,foe,poe,hoe,moe,goe,yoe,woe,boe,xoe,voe,Eoe,Aoe,Coe,Soe,Ioe,Toe,_oe,Poe,Noe,Roe,Ooe,Boe,koe,Uoe,Doe,Loe,Moe,Hoe,$oe,Foe,zoe,Voe,joe,qoe,Woe,Koe,Zoe,Goe,Yoe,Joe,Qoe,Xoe,ese,tse,rse,nse,ose,sse,ise,ase,cse,lse,use,dse,fse,pse,hse,mse,gse,yse,wse,bse,xse,vse,Ese,Ase,Cse,Sse,Ise,Tse,_se,Pse,Nse,Rse,Ose,Bse,kse,R0,jI=b(()=>{l();Zne=2n**(8n-1n)-1n,Gne=2n**(16n-1n)-1n,Yne=2n**(24n-1n)-1n,Jne=2n**(32n-1n)-1n,Qne=2n**(40n-1n)-1n,Xne=2n**(48n-1n)-1n,eoe=2n**(56n-1n)-1n,toe=2n**(64n-1n)-1n,roe=2n**(72n-1n)-1n,noe=2n**(80n-1n)-1n,ooe=2n**(88n-1n)-1n,soe=2n**(96n-1n)-1n,ioe=2n**(104n-1n)-1n,aoe=2n**(112n-1n)-1n,coe=2n**(120n-1n)-1n,loe=2n**(128n-1n)-1n,uoe=2n**(136n-1n)-1n,doe=2n**(144n-1n)-1n,foe=2n**(152n-1n)-1n,poe=2n**(160n-1n)-1n,hoe=2n**(168n-1n)-1n,moe=2n**(176n-1n)-1n,goe=2n**(184n-1n)-1n,yoe=2n**(192n-1n)-1n,woe=2n**(200n-1n)-1n,boe=2n**(208n-1n)-1n,xoe=2n**(216n-1n)-1n,voe=2n**(224n-1n)-1n,Eoe=2n**(232n-1n)-1n,Aoe=2n**(240n-1n)-1n,Coe=2n**(248n-1n)-1n,Soe=2n**(256n-1n)-1n,Ioe=-(2n**(8n-1n)),Toe=-(2n**(16n-1n)),_oe=-(2n**(24n-1n)),Poe=-(2n**(32n-1n)),Noe=-(2n**(40n-1n)),Roe=-(2n**(48n-1n)),Ooe=-(2n**(56n-1n)),Boe=-(2n**(64n-1n)),koe=-(2n**(72n-1n)),Uoe=-(2n**(80n-1n)),Doe=-(2n**(88n-1n)),Loe=-(2n**(96n-1n)),Moe=-(2n**(104n-1n)),Hoe=-(2n**(112n-1n)),$oe=-(2n**(120n-1n)),Foe=-(2n**(128n-1n)),zoe=-(2n**(136n-1n)),Voe=-(2n**(144n-1n)),joe=-(2n**(152n-1n)),qoe=-(2n**(160n-1n)),Woe=-(2n**(168n-1n)),Koe=-(2n**(176n-1n)),Zoe=-(2n**(184n-1n)),Goe=-(2n**(192n-1n)),Yoe=-(2n**(200n-1n)),Joe=-(2n**(208n-1n)),Qoe=-(2n**(216n-1n)),Xoe=-(2n**(224n-1n)),ese=-(2n**(232n-1n)),tse=-(2n**(240n-1n)),rse=-(2n**(248n-1n)),nse=-(2n**(256n-1n)),ose=2n**8n-1n,sse=2n**16n-1n,ise=2n**24n-1n,ase=2n**32n-1n,cse=2n**40n-1n,lse=2n**48n-1n,use=2n**56n-1n,dse=2n**64n-1n,fse=2n**72n-1n,pse=2n**80n-1n,hse=2n**88n-1n,mse=2n**96n-1n,gse=2n**104n-1n,yse=2n**112n-1n,wse=2n**120n-1n,bse=2n**128n-1n,xse=2n**136n-1n,vse=2n**144n-1n,Ese=2n**152n-1n,Ase=2n**160n-1n,Cse=2n**168n-1n,Sse=2n**176n-1n,Ise=2n**184n-1n,Tse=2n**192n-1n,_se=2n**200n-1n,Pse=2n**208n-1n,Nse=2n**216n-1n,Rse=2n**224n-1n,Ose=2n**232n-1n,Bse=2n**240n-1n,kse=2n**248n-1n,R0=2n**256n-1n});function jn(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,s=t?ft(t):void 0;if(s&&!Ft(s.address))throw new br({address:s.address});if(o&&!Ft(o))throw new br({address:o});if(r&&r>R0)throw new Ni({maxFeePerGas:r});if(typeof n=="bigint"&&typeof r=="bigint"&&n>r)throw new ac({maxFeePerGas:r,maxPriorityFeePerGas:n})}var nl=b(()=>{l();tn();jI();tc();tl();Gs()});var O0,uu,vb,Eb=b(()=>{l();Ig();nt();O0=class extends G{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}},uu=class extends G{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}},vb=class extends G{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${Pn(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}});var du,J4=b(()=>{l();nt();du=class extends G{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}});function jf(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?wt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?wt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Q4[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=mDe(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}function mDe(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var Q4,Use,Ab=b(()=>{l();Xr();Y4();Q4={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};Use=N0("transaction",jf)});function qf(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:jf(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}var Dse,X4=b(()=>{l();Y4();Ab();Dse=N0("block",qf)});async function xn(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let s=o??!1,i=r!==void 0?oe(r):void 0,a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,s]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[i||n,s]},{dedupe:!!i}),!a)throw new du({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||qf)(a,"getBlock")}var fu=b(()=>{l();J4();qe();X4()});async function Cb(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}var qI=b(()=>{l()});async function Lse(e,t){return WD(e,t)}async function WD(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let s=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof s=="function"){let a=r||await ue(e,xn,"getBlock")({}),c=await s({block:a,client:e,request:o});if(c===null)throw new Error;return c}if(typeof s<"u")return s;let i=await e.request({method:"eth_maxPriorityFeePerGas"});return dt(i)}catch{let[s,i]=await Promise.all([r?Promise.resolve(r):ue(e,xn,"getBlock")({}),ue(e,Cb,"getGasPrice")({})]);if(typeof s.baseFeePerGas!="bigint")throw new uu;let a=i-s.baseFeePerGas;return a<0n?0n:a}}var KD=b(()=>{l();Eb();Xr();_t();fu();qI()});async function Mse(e,t){return WI(e,t)}async function WI(e,t){let{block:r,chain:n=e.chain,request:o,type:s="eip1559"}=t||{},i=await(async()=>typeof n?.fees?.baseFeeMultiplier=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:o}):n?.fees?.baseFeeMultiplier??1.2)();if(i<1)throw new O0;let c=10**(i.toString().split(".")[1]?.length??0),u=p=>p*BigInt(Math.round(i*c))/BigInt(c),d=r||await ue(e,xn,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas=="function"){let p=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:u,request:o,type:s});if(p!==null)return p}if(s==="eip1559"){if(typeof d.baseFeePerGas!="bigint")throw new uu;let p=typeof o?.maxPriorityFeePerGas=="bigint"?o.maxPriorityFeePerGas:await WD(e,{block:d,chain:n,request:o}),h=u(d.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+p,maxPriorityFeePerGas:p}}return{gasPrice:o?.gasPrice??u(await ue(e,Cb,"getGasPrice")({}))}}var ZD=b(()=>{l();Eb();_t();KD();fu();qI()});function ni(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new G("`requireCanonical` can only be provided when `blockHash` is set.");return t?o?{blockHash:t,requireCanonical:o}:{blockHash:t}:typeof r=="bigint"?oe(r):n??"latest"}var B0=b(()=>{l();nt();qe()});async function k0(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),a=await e.request({method:"eth_getTransactionCount",params:[t,i]},{dedupe:typeof n=="bigint"||r!==void 0});return wt(a)}var e3=b(()=>{l();B0();Xr()});var Wf,U0,Sb,kg,Kf,Ug=b(()=>{l();nt();Wf=class extends G{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}},U0=class extends G{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} \u2013 ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} \u2013 ${t.name}`],name:"ChainMismatchError"})}},Sb=class extends G{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(` +`),{name:"ChainNotFoundError"})}},kg=class extends G{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}},Kf=class extends G{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}});function D0(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>qt(s)):e.blobs,o=[];for(let s of n)o.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?o:o.map(s=>yt(s))}var t3=b(()=>{l();Pr();qe()});function L0(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>qt(i)):e.blobs,o=typeof e.commitments[0]=="string"?e.commitments.map(i=>qt(i)):e.commitments,s=[];for(let i=0;iyt(i))}var r3=b(()=>{l();Pr();qe()});var Hse,$se=b(()=>{l();mD();Hse=Pg});function KI(e,t){let r=t||"hex",n=Hse(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var GD=b(()=>{l();$se();qs();Pr();qe()});function Ib(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),o=KI(t,"bytes");return o.set([r],0),n==="bytes"?o:yt(o)}var ZI=b(()=>{l();qe();GD()});function Tb(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),o=[];for(let s of t)o.push(Ib({commitment:s,to:n,version:r}));return o}var GI=b(()=>{l();ZI()});var YI,_b,JI,QI,YD=b(()=>{l();nt();YI=class extends G{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}},_b=class extends G{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}},JI=class extends G{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}},QI=class extends G{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}});function XI(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?qt(e.data):e.data,n=gt(r);if(!n)throw new _b;if(n>761855)throw new YI({maxSize:761855,size:n});let o=[],s=!0,i=0;for(;s;){let a=Zc(new Uint8Array(131072)),c=0;for(;c<4096;){let u=r.slice(i,i+31);if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),s=!1;break}c++,i+=31}o.push(a)}return t==="bytes"?o.map(a=>a.bytes):o.map(a=>yt(a.bytes))}var JD=b(()=>{l();YD();Jw();Fo();Pr();qe()});function M0(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??XI({data:t,to:n}),s=e.commitments??D0({blobs:o,kzg:r,to:n}),i=e.proofs??L0({blobs:o,commitments:s,kzg:r,to:n}),a=[];for(let c=0;c{l();t3();r3();JD()});function Pb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new nb({transaction:e})}var e9=b(()=>{l();zn()});function H0(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ri?e:o})();return new ib(n,{docsPath:t,...r})}var o3=b(()=>{l();tl();zn();G4()});async function hs(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return wt(t)}var Zf=b(()=>{l();Xr()});async function Nb(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:s=e.chain,blobVersionedHashes:i,blobs:a,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:y,nonceManager:w,to:x,type:v,value:T,...E}=t,S=await(async()=>{if(!r||!w||typeof y<"u")return y;let M=ft(r),N=s?s.id:await ue(e,hs,"getChainId")({});return await w.consume({address:M.address,chainId:N,client:e})})();jn(t);let _=s?.formatters?.transactionRequest?.format,D=(_||Bn)({...Oi(E,{format:_}),account:r?ft(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:i,data:c,gas:u,gasPrice:d,maxFeePerBlobGas:f,maxFeePerGas:p,maxPriorityFeePerGas:h,nonce:S,to:x,type:v,value:T},"fillTransaction");try{let M=await e.request({method:"eth_fillTransaction",params:[D]}),L=(s?.formatters?.transaction?.format||jf)(M.tx);delete L.blockHash,delete L.blockNumber,delete L.r,delete L.s,delete L.transactionIndex,delete L.v,delete L.yParity,typeof L.maxFeePerGas<"u"&&delete L.gasPrice,L.data=L.input;let P=typeof L.feePayerSignature<"u"&&L.feePayerSignature!==null;if(P&&typeof S<"u"&&BigInt(L.nonce)!==BigInt(S))throw new Wh({filledNonce:L.nonce,requestedNonce:S});if(!P){L.gas&&(L.gas=t.gas??L.gas),L.gasPrice&&(L.gasPrice=t.gasPrice??L.gasPrice),L.maxFeePerBlobGas&&(L.maxFeePerBlobGas=t.maxFeePerBlobGas??L.maxFeePerBlobGas),L.maxFeePerGas&&(L.maxFeePerGas=t.maxFeePerGas??L.maxFeePerGas),L.maxPriorityFeePerGas&&(L.maxPriorityFeePerGas=t.maxPriorityFeePerGas??L.maxPriorityFeePerGas),typeof L.nonce<"u"&&typeof t.nonce<"u"&&(L.nonce=typeof L.nonce=="bigint"?BigInt(t.nonce):t.nonce);let R=await(async()=>{if(typeof s?.fees?.baseFeeMultiplier=="function"){let A=await ue(e,xn,"getBlock")({});return s.fees.baseFeeMultiplier({block:A,client:e,request:t})}return s?.fees?.baseFeeMultiplier??1.2})();if(R<1)throw new O0;let B=10**(R.toString().split(".")[1]?.length??0),C=A=>A*BigInt(Math.round(R*B))/BigInt(B);L.maxFeePerGas&&!t.maxFeePerGas&&(L.maxFeePerGas=C(L.maxFeePerGas)),L.gasPrice&&!t.gasPrice&&(L.gasPrice=C(L.gasPrice))}return{raw:M.raw,transaction:{from:D.from,...L},...M.capabilities?{capabilities:M.capabilities}:{}}}catch(M){throw H0(M,{...t,chain:e.chain})}}var t9=b(()=>{l();tn();Eb();zn();o3();P0();Ab();rl();_t();nl();fu();Zf()});async function pu(e,t){let r={...t};typeof r.account>"u"&&(r.account=e.account),r.parameters??=s3;let{account:n,chain:o=e.chain,nonceManager:s,parameters:i}=r,a=(()=>{if(typeof o?.prepareTransactionRequest=="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt}})(),c;async function u(){return c||(typeof r.chainId<"u"?r.chainId:o?o.id:(c=await ue(e,hs,"getChainId")({}),c))}let d=n&&ft(n),f=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"})??r,f??=r.nonce;let D=r.account??r.from;d=D?ft(D):void 0}if(i.includes("nonce")&&typeof f>"u"&&d&&s){let D=await u();f=await s.consume({address:d.address,chainId:D,client:e})}let p=(i.includes("blobVersionedHashes")||i.includes("sidecars"))&&r.kzg&&r.blobs?!1:i.length>0&&"feePayer"in r&&r.feePayer&&!("feePayerSignature"in r&&r.feePayerSignature)?!0:QD.get(e.uid)===!1||!["fees","gas"].some(M=>i.includes(M))?!1:!!(i.includes("chainId")&&typeof r.chainId!="number"||i.includes("nonce")&&typeof f!="number"||i.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||i.includes("gas")&&typeof r.gas!="bigint"),h,y=D=>ue(e,Nb,"fillTransaction")({...D,nonce:f}).then(M=>{let{chainId:N,from:L,gas:P,gasPrice:R,nonce:I,maxFeePerBlobGas:B,maxFeePerGas:C,maxPriorityFeePerGas:A,type:U,...H}=M.transaction,k="feeToken"in H?H.feeToken:void 0,F="feePayerSignature"in H&&H.feePayerSignature!==null&&typeof H.feePayerSignature<"u",j=typeof k<"u"&&k!==null&&(!("feeToken"in D)||F);QD.set(e.uid,!0),h=N;let{feeToken:W,...ae}=D;return{...F?ae:D,...L?{from:L}:{},...U&&!D.type?{type:U}:{},...typeof P<"u"?{gas:P}:{},...typeof R<"u"?{gasPrice:R}:{},...typeof I<"u"?{nonce:I}:{},...typeof B<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxFeePerBlobGas:B}:{},...typeof C<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxFeePerGas:C}:{},...typeof A<"u"&&D.type!=="legacy"&&D.type!=="eip2930"?{maxPriorityFeePerGas:A}:{},..."nonceKey"in H&&typeof H.nonceKey<"u"?{nonceKey:H.nonceKey}:{},..."validBefore"in H&&H.validBefore!==null&&typeof H.validBefore<"u"?{validBefore:H.validBefore}:{},..."validAfter"in H&&H.validAfter!==null&&typeof H.validAfter<"u"?{validAfter:H.validAfter}:{},..."keyAuthorization"in H&&typeof H.keyAuthorization<"u"&&H.keyAuthorization!==null&&!("keyAuthorization"in D)?{keyAuthorization:H.keyAuthorization}:{},..."feePayerSignature"in H&&typeof H.feePayerSignature<"u"&&H.feePayerSignature!==null?{feePayerSignature:H.feePayerSignature}:{},...j?{feeToken:k}:{},...M.capabilities?{_capabilities:M.capabilities}:{}}}),w=(D,M)=>{let N=D;if(N.name!=="TransactionExecutionError")return M;if(N.walk?.(I=>I instanceof Wh)||N.walk?.(I=>I.name==="ExecutionRevertedError"))throw D;return N.walk?.(I=>{let B=I;return B.name==="MethodNotFoundRpcError"||B.name==="MethodNotSupportedRpcError"||B.message?.includes("eth_fillTransaction is not available")})&&QD.set(e.uid,!1),M},x=p?await y(r).catch(async D=>{let M=a?.fn&&a.runAt?.includes("afterFillTransactionError")?await a.fn({...r,chain:o},{client:e,error:D,phase:"afterFillTransactionError"}):void 0;return M?y(M).catch(N=>w(N,M)):w(D,r)}):r;if(f??=x.nonce,r={...x,...d?{from:d?.address}:{},...typeof f<"u"?{nonce:f}:{}},typeof h<"u"&&(r.chainId??=o?.id??h,r.chainId!==h))throw new U0({chain:o?.id===r.chainId?o:{id:r.chainId,name:"Unknown"},currentChainId:h});let{blobs:v,gas:T,kzg:E,type:S}=r;a?.fn&&a.runAt?.includes("beforeFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"})??r);let _;async function O(){return _||(_=await ue(e,xn,"getBlock")({blockTag:"latest"}),_)}if(i.includes("nonce")&&typeof f>"u"&&d&&!s&&(r.nonce=await ue(e,k0,"getTransactionCount")({address:d.address,blockTag:"pending"})),(i.includes("blobVersionedHashes")||i.includes("sidecars"))&&v&&E){let D=D0({blobs:v,kzg:E});if(i.includes("blobVersionedHashes")){let M=Tb({commitments:D,to:"hex"});r.blobVersionedHashes=M}if(i.includes("sidecars")){let M=L0({blobs:v,commitments:D,kzg:E}),N=M0({blobs:v,commitments:D,proofs:M,to:"hex"});r.sidecars=N}}if(i.includes("chainId")&&(r.chainId=await u()),(i.includes("fees")||i.includes("type"))&&typeof S>"u")try{r.type=Pb(r)}catch{let D=Fse.get(e.uid);typeof D>"u"&&(D=typeof(await O())?.baseFeePerGas=="bigint",Fse.set(e.uid,D)),r.type=D?"eip1559":"legacy"}if(i.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let D=await O(),{maxFeePerGas:M,maxPriorityFeePerGas:N}=await WI(e,{block:D,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&typeof r.maxFeePerGas=="bigint"&&r.maxFeePerGas"u"){let D=await O(),{gasPrice:M}=await WI(e,{block:D,chain:o,request:r,type:"legacy"});r.gasPrice=M}}return i.includes("gas")&&typeof T>"u"&&(r.gas=await ue(e,Ob,"estimateGas")({...r,account:d,prepare:d?.type==="local"?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"})??r),jn(r),delete r.parameters,r}var s3,Fse,QD,Rb=b(()=>{l();tn();ZD();r9();fu();e3();Ug();Eb();zn();t3();r3();GI();n3();_t();_f();nl();e9();t9();Zf();s3=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Fse=new Map,QD=new xo(128)});async function Ob(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ft(r):void 0,s=t.stateOverride!==void 0||typeof t.blockNumber=="bigint"||t.blockTag!==void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local"||s)return["blobVersionedHashes"]})();try{let a=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await b0({authorization:t.authorizationList[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:c,authorizationList:u,blobs:d,blobVersionedHashes:f,blockNumber:p,blockTag:h,data:y,gas:w,gasPrice:x,maxFeePerBlobGas:v,maxFeePerGas:T,maxPriorityFeePerGas:E,nonce:S,value:_,stateOverride:O,...D}=n?await pu(e,{...t,parameters:i,to:a}):t;if(w&&t.gas!==w&&!s)return w;let N=(typeof p=="bigint"?oe(p):void 0)||h,L=xb(O);jn(t);let P=e.chain?.formatters?.transactionRequest?.format,I=(P||Bn)({...Oi(D,{format:P}),account:o,accessList:c,authorizationList:u,blobs:d,blobVersionedHashes:f,data:y,gasPrice:x,maxFeePerBlobGas:v,maxFeePerGas:T,maxPriorityFeePerGas:E,nonce:S,to:a,value:_},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:L?[I,N??e.experimental_blockTag??"latest",L]:N?[I,N]:[I]}))}catch(a){throw jne(a,{...t,account:o,chain:e.chain})}}var r9=b(()=>{l();tn();nt();Z4();qe();qne();P0();rl();VI();nl();Rb()});async function $0(e,t){let{abi:r,address:n,args:o,functionName:s,dataSuffix:i=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Wt({abi:r,args:o,functionName:s});try{return await ue(e,Ob,"estimateGas")({data:`${c}${i?i.replace("0x",""):""}`,to:n,...a})}catch(u){let d=a.account?ft(a.account):void 0;throw Js(u,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:d?.address})}}var i3=b(()=>{l();tn();us();p0();_t();r9()});function xr(e,t){if(!Ft(e,{strict:!1}))throw new br({address:e});if(!Ft(t,{strict:!1}))throw new br({address:t});return e.toLowerCase()===t.toLowerCase()}var Bi=b(()=>{l();tc();Gs()});function qn(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var hu=b(()=>{l()});function Yf(e){let{abi:t,data:r,eventName:n,strict:o,topics:s}=e,i=o??!0,a=t.filter(p=>p.type==="event"&&"name"in p),c=s[0],u=c?a.find(p=>!p.anonymous&&c===Wc(no(p))):void 0,d=u?[u]:wDe(a,s.length,n);if(d.length>1)throw new Gf(d.map(p=>p.name));let f=d[0];if(!f)throw c?new Jl(c,{docsPath:XD}):new Yl({docsPath:XD});return xDe({abiItem:f,argTopics:f.anonymous?s:s.slice(1),data:r,strict:i})}function wDe(e,t,r){return(r?e.filter(o=>o.name===r):e.every(o=>o.anonymous)?e:[]).filter(o=>o.anonymous&&bDe(o)===t)}function bDe(e){return e.inputs?.filter(t=>t.indexed).length??0}function xDe({abiItem:e,argTopics:t,data:r,strict:n}){let{name:o,inputs:s}=e,i=s?.some(p=>!("name"in p&&p.name)),a=i?[]:{},c=s.map((p,h)=>[p,h]).filter(([p])=>"indexed"in p&&p.indexed),u=[];for(let p=0;p!("indexed"in p&&p.indexed)),f=n?d:[...u.map(([p])=>p),...d];if(f.length>0){if(r&&r!=="0x")try{let p=Ys(f,r);if(p){let h=0;if(!n)for(let[y,w]of u)a[i?w:y.name||w]=p[h++];if(i)for(let y=0;y0?a:void 0}}function vDe({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Ys([e],t)||[])[0]}var XD,Gf,a3=b(()=>{l();Qr();nt();aD();Fo();Kw();zh();Cf();XD="/docs/contract/decodeEventLog";Gf=class extends G{constructor(t){let r=new Set(t).size===t.length;super("Ambiguous anonymous event log.",{docsPath:XD,metaMessages:[`Matched ${t.map(n=>`\`${n}\``).join(", ")}.`,"These events take the same number of indexed topics.",r?"Pass `eventName` to choose one.":"Pass an `abi` that holds only the event to decode."],name:"AbiEventAmbiguityError"})}}});function cc(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),i=t.filter(c=>c.type==="event").map(c=>({abi:c,selector:Wc(c)})),a=s?i.filter(c=>c.abi.anonymous&&s.includes(c.abi.name)):i.every(c=>c.abi.anonymous)?i:[];return n.map(c=>{let u=typeof c.blockNumber=="string"?qn(c):c,d=i.filter(y=>!y.abi.anonymous&&u.topics[0]===y.selector),f=(()=>{if(d.length>0)return s?d.filter(w=>s.includes(w.abi.name)):d;let y=a.filter(w=>(w.abi.inputs?.filter(x=>x.indexed).length??0)===u.topics.length);return y.length===1?y:[]})();if(f.length===0)return null;let p,h;for(let y of f)try{p=Yf({...u,abi:[y.abi],strict:!0}),h=y;break}catch{}if(!p&&!o){let y=f[0];if(!y||y.abi.anonymous)return null;h=y;try{p=Yf({data:u.data,topics:u.topics,abi:[h.abi],strict:!1})}catch{let w=h.abi.inputs?.some(x=>!("name"in x&&x.name));p={eventName:h.abi.name,args:w?[]:{}}}}return!p||!h||s&&!s.includes(p.eventName)||!EDe({anonymous:h.abi.anonymous,args:p.args,inputs:h.abi.inputs,matchArgs:r,topics:u.topics})?null:{...p,...u}}).filter(Boolean)}function EDe(e){let{anonymous:t,args:r,inputs:n,matchArgs:o,topics:s}=e;if(!o)return!0;if(!r)return!1;let i=n.filter(c=>c.indexed).slice(0,t?s.length:s.length-1);function a(c,u,d){try{if(c.type==="address")return xr(u,d);if(i.includes(c)&&(c.type==="string"||c.type==="bytes")){let f=c.type==="string"?zo(u):un(u);return Pt(f)===d}return typeof u=="string"&&typeof d=="string"&&Eg.test(c.type)?u.toLowerCase()===d.toLowerCase():Rf.test(c.type)&&(typeof u=="number"||typeof u=="bigint")&&(typeof d=="number"||typeof d=="bigint")?BigInt(u)===BigInt(d):u===d}catch{return!1}}return Array.isArray(r)&&Array.isArray(o)?o.every((c,u)=>{if(c==null)return!0;let d=n[u];return d?(Array.isArray(c)?c:[c]).some(p=>a(d,p,r[u])):!1}):typeof r=="object"&&!Array.isArray(r)&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).every(([c,u])=>{if(u==null)return!0;let d=n.find(p=>p.name===c);return d?(Array.isArray(u)?u:[u]).some(p=>a(d,p,r[c])):!1}):!1}var Dg=b(()=>{l();Bi();Pr();hu();Ks();Kw();P4();a3()});function Bb(e){if(!(e instanceof G))return!0;let t=e.walk(r=>r instanceof Nr||r instanceof Rn);return t?t instanceof Rn&&t.code===429||t instanceof Nr&&t.status===void 0?!1:t.status!==401&&t.status!==403&&t.status!==429:!0}var n9=b(()=>{l();nt();fs()});async function*o9(e,t){let{address:r,args:n,blockRange:o=1000n,event:s,events:i,fromBlock:a,strict:c,toBlock:u="latest"}=t;if(o<1n)throw new G("`blockRange` must be at least 1n.");let d=typeof u=="bigint"?u:(await ue(e,xn,"getBlock")({blockTag:u})).number,f=o,p=a;for(;p<=d;){let h=p+f-1n,y=h{if(p===y||!Bb(x))throw x});if(!w){f=(y-p+1n)/2n;continue}yield{endBlock:d,fromBlock:p,logs:w,toBlock:y},p=y+1n,f=f*2n{l();nt();_t();fu();c3();n9()});async function F0(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:s,events:i,args:a,blockRange:c,strict:u}={}){if(c!==void 0){let w=[];for await(let x of o9(e,{address:t,args:a,blockRange:c,event:s,events:i,fromBlock:n,strict:u,toBlock:o}))for(let v of x.logs)w.push(v);return w}let d=u??!1,f=i??(s?[s]:void 0),p=[];f&&(p=[f.flatMap(x=>nc({abi:[x],eventName:x.name,args:i?void 0:a}))],s&&(p=p[0]));let h;r?h=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]}):h=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n=="bigint"?oe(n):n,toBlock:typeof o=="bigint"?oe(o):o}]});let y=h.map(w=>qn(w));return f?cc({abi:f,args:a,logs:y,strict:d}):y}var c3=b(()=>{l();Cg();Dg();qe();hu();eL()});async function kb(e,t){let{abi:r,address:n,args:o,blockHash:s,eventName:i,fromBlock:a,toBlock:c,strict:u}=t,d=i?ls({abi:r,name:i}):void 0,f=d?void 0:r.filter(p=>p.type==="event");return ue(e,F0,"getLogs")({address:n,args:o,blockHash:s,event:d,events:f,fromBlock:a,toBlock:c,strict:u})}var s9=b(()=>{l();Bf();_t();c3()});function dn(e){let{abi:t,args:r,functionName:n,data:o}=e,s=t[0];if(n){let a=ls({abi:t,args:r,name:n});if(!a)throw new wa(n,{docsPath:tL});s=a}if(s.type!=="function")throw new wa(void 0,{docsPath:tL});if(!s.outputs)throw new Dh(s.name,{docsPath:tL});let i=Ys(s.outputs,o);if(i&&i.length>1)return i;if(i&&i.length===1)return i[0]}var tL,lc=b(()=>{l();Qr();zh();Bf();tL="/docs/contract/decodeFunctionResult"});var zse,Vse=b(()=>{l();zse="0.1.1"});function jse(){return zse}var qse=b(()=>{l();Vse()});function Wse(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?Wse(e.cause,t):t?null:e}var Ke,ki=b(()=>{l();qse();Ke=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=r.docsOrigin??e.prototype.docsOrigin,i=`${s}${o??""}`,a=!!(r.version??e.prototype.showVersion),c=r.version??e.prototype.version,u=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o||a?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(d=>typeof d=="string").join(` +`);super(u,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=i,this.docsOrigin=s,this.docsPath=o,this.shortMessage=t,this.showVersion=a,this.version=c}walk(t){return Wse(this,t)}};Object.defineProperty(Ke,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${jse()}`}});Ke.setStaticOptions(Ke.defaultStaticOptions)});function Ub(e,t){if(uc(e)>t)throw new i9({givenSize:uc(e),maxSize:t})}function Kse(e,t){if(typeof t=="number"&&t>0&&t>uc(e)-1)throw new l3({offset:t,position:"start",size:uc(e)})}function Zse(e,t,r){if(typeof t=="number"&&typeof r=="number"&&uc(e)!==r-t)throw new l3({offset:r,position:"end",size:uc(e)})}function rL(e){if(e>=Jf.zero&&e<=Jf.nine)return e-Jf.zero;if(e>=Jf.A&&e<=Jf.F)return e-(Jf.A-10);if(e>=Jf.a&&e<=Jf.f)return e-(Jf.a-10)}function Gse(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new a9({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;s{l();mu();Jf={zero:48,nine:57,A:65,F:70,a:97,f:102}});function Db(e,t){if(Mr(e)>t)throw new c9({givenSize:Mr(e),maxSize:t})}function Jse(e,t){if(typeof t=="number"&&t>0&&t>Mr(e)-1)throw new u3({offset:t,position:"start",size:Mr(e)})}function Qse(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Mr(e)!==r-t)throw new u3({offset:r,position:"end",size:Mr(e)})}function oL(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new l9({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function Xse(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;s{l();io()});function z0(e,t,r){return JSON.stringify(e,(n,o)=>typeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+CDe:o,r)}var CDe,d3=b(()=>{l();CDe="#__bigint"});function TDe(e){if(!(e instanceof Uint8Array)){if(!e)throw new Lb(e);if(typeof e!="object")throw new Lb(e);if(!("BYTES_PER_ELEMENT"in e))throw new Lb(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new Lb(e)}}function aL(e){return e instanceof Uint8Array?e:typeof e=="string"?Lg(e):_De(e)}function _De(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Lg(e,t={}){let{size:r}=t,n=e.slice(2);n.length%2&&(n=`0${n}`),r&&(Db(e,r),n=n.padEnd(r*2,"0"));let o=n.length/2,s=new Uint8Array(o);for(let i=0,a=0;i1||n[0]>1)throw new iL(n);return!!n[0]}function Xf(e,t={}){let{size:r}=t;typeof r<"u"&&Ub(e,r);let n=vn(e,t);return f9(n,t)}function d9(e,t={}){let{size:r}=t,n=e;return typeof r<"u"&&(Ub(n,r),n=NDe(n)),SDe.decode(n)}function cL(e){return nL(e,{dir:"left"})}function NDe(e){return nL(e,{dir:"right"})}function oie(e){try{return TDe(e),!0}catch{return!1}}var SDe,IDe,iL,Lb,i9,l3,a9,mu=b(()=>{l();ki();io();Yse();sL();d3();SDe=new TextDecoder,IDe=new TextEncoder;iL=class extends Ke{constructor(t){super(`Bytes value \`${t}\` is not a valid boolean.`,{metaMessages:["The bytes array must contain a single byte of either a `0` or `1` value."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesBooleanError"})}},Lb=class extends Ke{constructor(t){super(`Value \`${typeof t=="object"?z0(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},i9=class extends Ke{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},l3=class extends Ke{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SliceOffsetOutOfBoundsError"})}},a9=class extends Ke{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function kDe(e,t={}){let{even:r=!1,strict:n=!1}=t;if(!e)throw new p9(e);if(typeof e!="string")throw new p9(e);if(n&&!BDe.test(e))throw new h9(e);if(!e.startsWith("0x"))throw new h9(e);if(r&&e.length%2!==0)throw new m9(e)}function fn(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Hb(e){return e instanceof Uint8Array?vn(e):Array.isArray(e)?vn(new Uint8Array(e)):e}function g9(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Db(r,t.size),ep(r,t.size)):r}function vn(e,t={}){let r="";for(let o=0;os||o>1n;return n<=s?n:n-o-1n}function f9(e,t={}){let{signed:r,size:n}=t;return Number(!r&&!n?e:lL(e,t))}function q0(e,t={}){let{even:r=!1,strict:n=!1}=t;try{return kDe(e,{even:r,strict:n}),!0}catch{return!1}}var RDe,ODe,BDe,V0,p9,h9,m9,c9,u3,l9,io=b(()=>{l();ki();sL();d3();RDe=new TextEncoder,ODe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")),BDe=/^0x[0-9a-fA-F]*$/;V0=class extends Ke{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},p9=class extends Ke{constructor(t){super(`Value \`${typeof t=="object"?z0(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},h9=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},m9=class extends Ke{constructor(t){super(`Hex value \`"${t}"\` is an odd length (${t.length-2} nibbles).`,{metaMessages:["It must be an even length."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidLengthError"})}},c9=class extends Ke{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},u3=class extends Ke{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},l9=class extends Ke{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function sie(e){return{address:e.address,amount:Yt(e.amount),index:Yt(e.index),validatorIndex:Yt(e.validatorIndex)}}var iie=b(()=>{l();io()});function w9(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Yt(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Yt(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Yt(e.gasLimit)},...typeof e.number=="bigint"&&{number:Yt(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Yt(e.prevRandao)},...typeof e.time=="bigint"&&{time:Yt(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(sie)}}}var uL=b(()=>{l();io();iie()});var Ui,W0,cie,b9,lie,dL,fL,x9,Fb,Hr,uie,die,fie,pie,So=b(()=>{l();Ui=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],W0=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],cie=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],b9=[...cie,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],lie=[...cie,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],dL=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],fL=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],x9=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],Fb=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],Hr=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],uie=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],die=[{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC1155InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC1155InvalidApprover",type:"error"},{inputs:[{internalType:"uint256",name:"idsLength",type:"uint256"},{internalType:"uint256",name:"valuesLength",type:"uint256"}],name:"ERC1155InvalidArrayLength",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC1155InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC1155InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC1155InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC1155MissingApprovalForAll",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"values",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}],fie=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"event",name:"ApprovalForAll",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"operator",type:"address"},{indexed:!1,name:"approved",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"payable",inputs:[{name:"spender",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"getApproved",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"address"}]},{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"operator",type:"address"}],outputs:[{type:"bool"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"owner",type:"address"}]},{type:"function",name:"safeTransferFrom",stateMutability:"payable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"safeTransferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"id",type:"uint256"},{name:"data",type:"bytes"}],outputs:[]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"index",type:"uint256"}],outputs:[{type:"uint256"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"index",type:"uint256"}],outputs:[{name:"tokenId",type:"uint256"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transferFrom",stateMutability:"payable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}],pie=[{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!0,name:"owner",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],name:"allowance",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],name:"approve",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"asset",outputs:[{name:"assetTokenAddress",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"convertToAssets",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"convertToShares",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"}],name:"deposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxDeposit",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxMint",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxRedeem",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxWithdraw",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"}],name:"mint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewDeposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewMint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewRedeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewWithdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"redeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"totalAssets",outputs:[{name:"totalManagedAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"withdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"}]});var hie,mie=b(()=>{l();hie="0x82ad56cb"});var zb,v9,f3,Mg,Vb=b(()=>{l();zb="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",v9="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",f3="0x608060405234801561001057600080fd5b506040516106ad3803806106ad83398101604081905261002f91610537565b600061003c848484610048565b9050806000526001601ff35b60007f649264926492649264926492649264926492649264926492649264926492649261007483610425565b036101e7576000606080848060200190518101906100929190610590565b60405192955090935091506000906001600160a01b038516906100b69085906105f6565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b908790600401610612565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d1919061064c565b6001600160e01b0319161494505050505061041e565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e906102279087908790600401610612565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610268919061064c565b6001600160e01b03191614905061041e565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061068d83398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e761043e565b5060208201516040808401518451859392600091859190811061030c5761030c610676565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061068d83398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b604080516000808252602082018084528a905260ff841692820192909252606081018590526080810184905260019060a0016020604051602081039080840390855afa1580156103e0573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116158015906104165750886001600160a01b0316816001600160a01b0316145b955050505050505b9392505050565b600060208251101561043657600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461047157600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b838110156104a557818101518382015260200161048d565b50506000910152565b600082601f8301126104bf57600080fd5b81516001600160401b038111156104d8576104d8610474565b604051601f8201601f19908116603f011681016001600160401b038111828210171561050657610506610474565b60405281815283820160200185101561051e57600080fd5b61052f82602083016020870161048a565b949350505050565b60008060006060848603121561054c57600080fd5b83516105578161045c565b6020850151604086015191945092506001600160401b0381111561057a57600080fd5b610586868287016104ae565b9150509250925092565b6000806000606084860312156105a557600080fd5b83516105b08161045c565b60208501519093506001600160401b038111156105cc57600080fd5b6105d8868287016104ae565b604086015190935090506001600160401b0381111561057a57600080fd5b6000825161060881846020870161048a565b9190910192915050565b828152604060208201526000825180604084015261063781606085016020870161048a565b601f01601f1916919091016060019392505050565b60006020828403121561065e57600080fd5b81516001600160e01b03198116811461041e57600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",Mg="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"});function tp(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find(i=>"type"in i&&i.type==="constructor");if(!o)throw new Oh({docsPath:pL});if(!("inputs"in o))throw new Gl({docsPath:pL});if(!o.inputs||o.inputs.length===0)throw new Gl({docsPath:pL});let s=oo(o.inputs,r);return fr([n,s])}var pL,p3=b(()=>{l();Qr();Fn();rc();pL="/docs/contract/encodeDeployData"});function Di({blockNumber:e,chain:t,contract:r}){let n=t?.contracts?.[r];if(!n)throw new Wf({chain:t,contract:{name:r}});if(e!==void 0&&n.blockCreated!==void 0&&n.blockCreated>e)throw new Wf({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}var K0=b(()=>{l();Ug()});function E9(e,{docsPath:t,...r}){let n=(()=>{let o=_0(e,r);return o instanceof Ri?e:o})();return new Yc(n,{docsPath:t,...r})}var hL=b(()=>{l();ou();tl();G4()});function jb(){let e=()=>{},t=()=>{};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}var A9=b(()=>{l()});function Z0({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let s=async()=>{let d=c();i();let f=d.map(({args:p})=>p);f.length!==0&&new Promise(p=>p(e(f))).then(p=>{o&&Array.isArray(p)&&p.sort(o);for(let h=0;h{for(let h=0;hmL.delete(t),a=()=>c().map(({args:d})=>d),c=()=>mL.get(t)||[],u=d=>mL.set(t,[...c(),d]);return{flush:i,async schedule(d){let{promise:f,resolve:p,reject:h}=jb();return r?.([...a(),d])&&s(),c().length>0?(u({args:d,resolve:p,reject:h}),f):(u({args:d,resolve:p,reject:h}),setTimeout(s,n),f)}}}var mL,h3=b(()=>{l();A9();mL=new Map});var C9,S9,I9,gie=b(()=>{l();so();nt();oc();C9=class extends G{constructor({callbackSelector:t,cause:r,data:n,extraData:o,sender:s,urls:i}){super(r.shortMessage||"An error occurred while fetching for an offchain result.",{cause:r,metaMessages:[...r.metaMessages||[],r.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map(a=>` ${kf(a)}`)],` Sender: ${s}`,` Data: ${n}`,` Callback selector: ${t}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}},S9=class extends G{constructor({result:t,url:r}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${kf(r)}`,`Response: ${bt(t)}`],name:"OffchainLookupResponseMalformedError"})}},I9=class extends G{constructor({sender:t,to:r}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${r}`,`OffchainLookup sender address: ${t}`],name:"OffchainLookupSenderMismatchError"})}}});function T9(e){let{abi:t,data:r}=e,n=vo(r,0,4),o=t.find(s=>s.type==="function"&&n===va(no(s)));if(!o)throw new Bw(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:o.name,args:"inputs"in o&&o.inputs&&o.inputs.length>0?Ys(o.inputs,vo(r,4)):void 0}}var gL=b(()=>{l();Qr();Ii();Ag();zh();Cf()});function m3(e){let{abi:t,errorName:r,args:n}=e,o=t[0];if(r){let c=ls({abi:t,args:n,name:r});if(!c)throw new pg(r,{docsPath:yL});o=c}if(o.type!=="error")throw new pg(void 0,{docsPath:yL});let s=no(o),i=va(s),a="0x";if(n&&n.length>0){if(!o.inputs)throw new Ow(o.name,{docsPath:yL});a=oo(o.inputs,n)}return fr([i,a])}var yL,wL=b(()=>{l();Qr();Fn();Ag();rc();Cf();Bf();yL="/docs/contract/encodeErrorResult"});function _9(e){let{abi:t,functionName:r,result:n}=e,o=t[0];if(r){let i=ls({abi:t,name:r});if(!i)throw new wa(r,{docsPath:bL});o=i}if(o.type!=="function")throw new wa(void 0,{docsPath:bL});if(!o.outputs)throw new Dh(o.name,{docsPath:bL});let s=(()=>{if(o.outputs.length===0)return[];if(o.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new Mh(n)})();return oo(o.outputs,s)}var bL,xL=b(()=>{l();Qr();rc();Bf();bL="/docs/contract/encodeFunctionResult"});function vL(){let e=0,t=[];return{bytes:ol.bytes,queries:ol.queries,async run(r){e>=ol.concurrency?await new Promise(n=>t.push(n)):e++;try{return await r()}finally{let n=t.shift();n?n():e--}}}}async function EL(e){let{data:t,ccipRequest:r,budget:n=vL(),depth:o=0}=e,{args:[s]}=T9({abi:W0,data:t}),i=[],a=[];return await Promise.all(s.map(async(c,u)=>{try{let d=c.urls.includes(Ia);if(d&&o+1>=ol.depth)throw new Nr({details:`CCIP Read exceeded the maximum batch depth (${ol.depth}).`,url:Ia});if(d)a[u]=await EL({data:c.data,ccipRequest:r,budget:n,depth:o+1});else{if(n.queries<=0)throw new Nr({details:`CCIP Read exceeded the maximum number of queries (${ol.queries}).`,url:c.urls[0]??""});let f=c.urls.slice(0,n.queries);n.queries-=Math.max(1,f.length);let p=await n.run(async()=>n.bytes<0?"0x":r({...c,urls:f}));if(n.bytes-=gt(p),n.bytes<0)throw new Nr({details:`CCIP Read exceeded the maximum response size (${ol.bytes} bytes).`,url:Ia});a[u]=p}i[u]=!1}catch(d){if(n.bytes<0)throw d;i[u]=!0,a[u]=DDe(d)}})),_9({abi:W0,functionName:"query",result:[i,a]})}function DDe(e){return e.name==="HttpRequestError"&&e.status?m3({abi:W0,errorName:"HttpError",args:[e.status,e.shortMessage]}):m3({abi:[Gw],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}var Ia,ol,qb=b(()=>{l();So();R4();fs();gL();wL();xL();Fo();Ia="x-batch-gateway:true",ol={bytes:10485760,concurrency:16,depth:4,queries:256}});function P9(e){let t=e.filter(s=>!!s);if(t.length<2)return{signal:t[0]??null,cleanup:()=>{}};let r=new AbortController,n=()=>{o(),r.abort(t.find(s=>s.aborted)?.reason)},o=()=>{for(let s of t)s.removeEventListener("abort",n)};for(let s of t){if(s.aborted){o(),r.abort(s.reason);break}s.addEventListener("abort",n)}return{signal:r.signal,cleanup:o}}async function Wb(e,{maxResponseBodySize:t}){if(t===!1)return e.text();let r=e.headers.get("Content-Length");if(r){let a=Number(r);if(a>t)throw await e.body?.cancel(),new ic({maxSize:t,size:a})}if(!e.body){let a=await e.text(),c=new TextEncoder().encode(a).length;if(c>t)throw new ic({maxSize:t,size:c});return a}let n=e.body.getReader(),o=new TextDecoder,s="",i=0;try{for(;;){let{done:a,value:c}=await n.read();if(a)break;if(i+=c.byteLength,i>t)throw await n.cancel(),new ic({maxSize:t,size:i});s+=o.decode(c,{stream:!0})}return s+=o.decode(),s}finally{n.releaseLock()}}var N9=b(()=>{l();fs()});function sl(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((o,s)=>{(async()=>{let i,a=new AbortController;try{r>0&&(i=setTimeout(()=>{n?a.abort():s(t)},r)),o(await e({signal:a?.signal||null}))}catch(c){if(a?.signal.aborted&&Ti(c)){s(t);return}s(c)}finally{clearTimeout(i)}})()})}var Kb=b(()=>{l();oc()});var wie={};Te(wie,{ccipRequest:()=>Hg,offchainLookup:()=>B9,offchainLookupAbiItem:()=>O9,offchainLookupSignature:()=>R9});async function B9(e,{blockHash:t,blockNumber:r,blockTag:n,budget:o=vL(),data:s,depth:i=0,requestOptions:a,requireCanonical:c,to:u}){let{args:d}=Vh({data:s,abi:[O9]}),[f,p,h,y,w]=d,{ccipRead:x}=e,v=x&&typeof x?.request=="function"?x.request:Hg,T=yie(e.transport);try{if(i>=ol.depth)throw new Nr({details:`CCIP Read exceeded the maximum callback depth (${ol.depth}).`,url:p[0]??""});if(!xr(u,f))throw new I9({sender:f,to:u});let E=await(async()=>{if(p.includes(Ia))return EL({budget:o,ccipRequest:O=>v({...O,requestOptions:a,timeout:O.timeout??T}),data:h});if(o.queries<=0)throw new Nr({details:`CCIP Read exceeded the maximum number of queries (${ol.queries}).`,url:p[0]??""});let _=p.slice(0,o.queries);return o.queries-=Math.max(1,_.length),o.run(()=>v({data:h,requestOptions:a,sender:f,timeout:T,urls:_}))})(),S=en([y,oo([{type:"bytes"},{type:"bytes"}],[E,w])]);try{let{data:_}=await ms({...e,ccipRead:!1},{blockHash:t,blockNumber:r,blockTag:n,data:S,requestOptions:a,requireCanonical:c,to:u});return _}catch(_){let O=AL(_);if(O?.slice(0,10)!==R9)throw _;return await B9(e,{blockHash:t,blockNumber:r,blockTag:n,budget:o,data:O,depth:i+1,requestOptions:a,requireCanonical:c,to:u})}}catch(E){throw a?.signal?.aborted?Nn(a.signal):Ti(E)?E:new C9({callbackSelector:y,cause:E,data:s,extraData:w,sender:f,urls:p})}}async function Hg({data:e,requestOptions:t,sender:r,timeout:n=LDe,urls:o}){let s=new Error("An unknown error occurred.");for(let i of o){if(t?.signal?.aborted)throw Nn(t.signal);let a=i.replace("{sender}",r.toLowerCase()).replace("{data}",e),c=i.includes("{data}")?"GET":"POST",u=c==="POST"?{data:e,sender:r}:void 0,d=c==="POST"?{"Content-Type":"application/json"}:{};try{HDe(a);let{response:f,responseBody:p}=await sl(async({signal:y})=>{let{signal:w,cleanup:x}=P9([t?.signal,n>0?y:null]);try{let v=await fetch(a,{body:JSON.stringify(u),headers:d,method:c,...w?{signal:w}:{}}),T=await Wb(v,{maxResponseBodySize:MDe});return{response:v,responseBody:T}}finally{x()}},{errorInstance:new ds({body:u??{data:e,sender:r},url:i}),signal:!0,timeout:n}),h;if(f.headers.get("Content-Type")?.startsWith("application/json")?h=JSON.parse(p).data:h=p,!f.ok){s=new Nr({body:u,details:h?.error?bt(h.error):f.statusText,headers:f.headers,status:f.status,url:i});continue}if(!We(h)){s=new S9({result:h,url:i});continue}return h}catch(f){if(t?.signal?.aborted)throw Nn(t.signal);if(Ti(f))throw f;if(f instanceof Nr||f instanceof ds||f instanceof ic){s=f;continue}s=new Nr({body:u,cause:f,url:i})}}throw s}function HDe(e){let t=(()=>{try{return new URL(e)}catch{throw new Nr({details:"CCIP Read URL is invalid.",url:e})}})();if(!(t.protocol==="http:"||t.protocol==="https:"))throw new Nr({details:`CCIP Read URL scheme "${t.protocol.slice(0,-1)}" is not allowed.`,url:e})}function yie(e){let t=e.timeout??e.config?.timeout;if(t!==void 0)return t;let r=(e.transports??e.value?.transports??[]).map(yie).filter(n=>n!==void 0);return r.length?Math.max(...r):void 0}var LDe,MDe,R9,O9,k9=b(()=>{l();G0();gie();fs();oc();L4();rc();Bi();Fn();qs();qb();N9();Kb();so();LDe=1e4,MDe=10485760,R9="0x556f1830",O9={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function ms(e,t){let{account:r=e.account,authorizationList:n,batch:o=!!e.batch?.multicall,blockHash:s,blockNumber:i,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:u,blobs:d,blockOverrides:f,code:p,data:h,factory:y,factoryData:w,gas:x,gasPrice:v,maxFeePerBlobGas:T,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:_,requestOptions:O,to:D,value:M,stateOverride:N,...L}=t,P=r?ft(r):void 0;if(p&&(y||w))throw new G("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(p&&D)throw new G("Cannot provide both `code` & `to` as parameters.");let R=p&&h,I=y&&w&&D&&h,B=R||I,C=R?vie({code:p,data:h}):I?qDe({data:h,factory:y,factoryData:w,to:D}):h;try{jn(t);let A=ni({blockHash:s,blockNumber:i,blockTag:a,requireCanonical:c}),U=f?w9(f):void 0,H=xb(N),k=e.chain?.formatters?.transactionRequest?.format,j=(k||Bn)({...Oi(L,{format:k}),accessList:u,account:P,authorizationList:n,blobs:d,data:C,gas:x,gasPrice:v,maxFeePerBlobGas:T,maxFeePerGas:E,maxPriorityFeePerGas:S,nonce:_,to:B?void 0:D,value:M},"call");if(o&&$De({request:j})&&!U&&s===void 0)try{let{deployless:te=!1}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},X=xie(e,{blockNumber:i,deployless:te});if(!X||!jDe(H,X))return await VDe(e,{...j,blockHash:s,blockNumber:i,blockTag:a,multicallAddress:X,requestOptions:O,requireCanonical:c,rpcStateOverride:H})}catch(te){if(!(te instanceof kg)&&!(te instanceof Wf))throw te}let W=(()=>{let te=[j,A];return H&&U?[...te,H,U]:H?[...te,H]:U?[...te,{},U]:te})(),ae=await e.request({method:"eth_call",params:W},O);return ae==="0x"?{data:void 0}:{data:ae}}catch(A){if(O?.signal?.aborted)throw Nn(O.signal);if(Ti(A))throw A;let U=AL(A),{offchainLookup:H,offchainLookupSignature:k}=await Promise.resolve().then(()=>(k9(),wie));if(e.ccipRead!==!1&&U?.slice(0,10)===k&&D)return{data:await H(e,{blockHash:s,blockNumber:i,blockTag:a,data:U,requestOptions:O,requireCanonical:c,to:D})};throw B&&U?.slice(0,10)==="0x101bb98d"?new lb({factory:y}):E9(A,{...t,account:P,chain:e.chain})}}function $De({request:e}){let{data:t,to:r,...n}=e;return!(!t||t.startsWith(hie)||!r||Object.values(n).filter(o=>typeof o<"u").length>0)}function zDe(e){if(!e)return"default";let t=bie.get(e);if(t!==void 0)return t;let r=FDe++;return bie.set(e,r),r}async function VDe(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockHash:s,blockNumber:i,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:u,multicallAddress:d,requestOptions:f,rpcStateOverride:p,to:h}=t,y=d!==void 0?d:xie(e,{blockNumber:i,deployless:n}),w=ni({blockHash:s,blockNumber:i,blockTag:a,requireCanonical:c}),x=typeof w=="string"?w:JSON.stringify(w),v=p?`.${JSON.stringify(p)}`:"",{schedule:T}=Z0({id:`${e.uid}.${x}.${zDe(f)}${v}`,wait:o,shouldSplitBatch(_){return _.reduce((D,{data:M})=>D+(M.length-2),0)>r*2},fn:async _=>{let O=_.map(P=>({allowFailure:!0,callData:P.data,target:P.to})),D=Wt({abi:Ui,args:[O],functionName:"aggregate3"}),M={...y===null?{data:vie({code:Mg,data:D})}:{to:y,data:D}},N=await e.request({method:"eth_call",params:p?[M,w,p]:[M,w]},f),L=dn({abi:Ui,args:[O],functionName:"aggregate3",data:N||"0x"});if(L.length!==_.length)throw new G(`Multicall returned ${L.length} results for ${_.length} calls.`);return L}}),[{returnData:E,success:S}]=await T({data:u,to:h});if(!S)throw new sc({data:E});return E==="0x"?{data:void 0}:{data:E}}function xie(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return Di({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new kg}function jDe(e,t){return e?Object.keys(e).some(r=>xr(r,t)):!1}function vie(e){let{code:t,data:r}=e;return tp({abi:Iw(["constructor(bytes, bytes)"]),bytecode:zb,args:[t,r]})}function qDe(e){let{data:t,factory:r,factoryData:n,to:o}=e;return tp({abi:Iw(["constructor(address, bytes, address, bytes)"]),bytecode:v9,args:[o,t,r,n]})}function AL(e){if(!(e instanceof G))return;let t=e.walk();return typeof t?.data=="object"?t.data?.data:t.data}var FDe,bie,G0=b(()=>{l();fg();uL();tn();So();mie();Vb();nt();Ug();ou();oc();lc();p3();us();Bi();B0();K0();hL();P0();rl();h3();VI();nl();FDe=0,bie=new WeakMap});async function er(e,t){let{abi:r,address:n,args:o,functionName:s,...i}=t,a=Wt({abi:r,args:o,functionName:s});try{let{data:c}=await ue(e,ms,"call")({...i,data:a,to:n});return dn({abi:r,args:o,functionName:s,data:c||"0x"})}catch(c){throw Js(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:s})}}var oi=b(()=>{l();lc();us();p0();_t();G0()});async function Y0(e,t){let{abi:r,address:n,args:o,functionName:s,dataSuffix:i=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account===void 0?e.account:a.account&&ft(a.account),u=Wt({abi:r,args:o,functionName:s});try{let{data:d}=await ue(e,ms,"call")({batch:!1,data:`${u}${i?i.replace("0x",""):""}`,to:n,...a,account:c}),f=dn({abi:r,args:o,functionName:s,data:d||"0x"}),p=r.filter(h=>"name"in h&&h.name===t.functionName);return{result:f,request:{abi:p,address:n,args:o,dataSuffix:i,functionName:s,...a,account:c}}}catch(d){throw Js(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:s,sender:c?.address})}}var g3=b(()=>{l();tn();lc();us();p0();_t();G0()});function Io(e,t,r){let n=++WDe,o=()=>U9.get(e)||[],s=()=>{let f=o().filter(p=>p.id!==n);if(f.length===0){U9.delete(e),CL.delete(e);return}U9.set(e,f)},i=()=>{let d=o();if(!d.some(p=>p.id===n))return;let f=CL.get(e);if(d.length===1&&f){let p=f();p instanceof Promise&&p.catch(()=>{})}s()},a=o();if(U9.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return i;let c={};for(let d in t)c[d]=((...f)=>{let p=o();if(p.length!==0)for(let h of p)h.fns[d]?.(...f)});let u=r(c);return typeof u=="function"&&CL.set(e,u),i}var U9,CL,WDe,rp=b(()=>{l();U9=new Map,CL=new Map,WDe=0});async function $g(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(Nn(t));return}let o=()=>t?.removeEventListener("abort",i),s=setTimeout(()=>{o(),r()},Math.min(e,2**31-1)),i=()=>{clearTimeout(s),o(),n(Nn(t))};t?.addEventListener("abort",i,{once:!0})})}var D9=b(()=>{l();oc()});function dc(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,s=()=>o=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));let c=await r?.(a)??n;await $g(c);let u=async()=>{o&&(await e({unpoll:s}),await $g(n),u())};u()})(),s}var Fg=b(()=>{l();D9()});function Eie(e){let t=(o,s)=>({clear:()=>s.delete(o),get:()=>s.get(o),set:i=>s.set(o,i)}),r=t(e,KDe),n=t(e,ZDe);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function L9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=Eie(t),o=n.response.get();if(o&&r>0&&Date.now()-o.created.getTime(){l();KDe=new Map,ZDe=new Map});async function Ta(e,{cacheTime:t=e.cacheTime}={}){let r=await L9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:GDe(e.uid),cacheTime:t});return BigInt(r)}var GDe,zg=b(()=>{l();SL();GDe=e=>`blockNumber.${e}`});async function J0(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;let o=n.map(s=>qn(s));return!("abi"in t)||!t.abi?o:cc({abi:t.abi,eventName:t.eventName,logs:o,strict:r})}var y3=b(()=>{l();Dg();hu()});function gu(e){if(e.transport.type==="fallback"){let t=e.transport.transports.find(r=>r.config.type==="webSocket"||r.config.type==="ipc");return t?t.value:e.transport}return e.transport}function Q0(e){return!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))}var Zb=b(()=>{l()});async function X0(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}var w3=b(()=>{l()});function M9(e,t){let{abi:r,address:n,args:o,batch:s=!0,eventName:i,fromBlock:a,onError:c,onLogs:u,poll:d,pollingInterval:f=e.pollingInterval,strict:p}=t;return(typeof d<"u"?d:typeof a=="bigint"?!0:Q0(e))?(()=>{let x=p??!1,v=bt(["watchContractEvent",n,o,s,e.uid,i,f,x,a]);return Io(v,{onLogs:u,onError:c},T=>{let E=!0,S=a===void 0?void 0:a-1n,_,O=!1,D=L=>{if(L.length!==0)if(s)T.onLogs(L);else for(let P of L)T.onLogs([P])},M=(L,P)=>ue(e,kb,"getContractEvents")({abi:r,address:n,args:o,eventName:i,fromBlock:L,toBlock:P,strict:x}),N=dc(async()=>{if(!O){try{_=await ue(e,Zw,"createContractEventFilter")({abi:r,address:n,args:o,eventName:i,strict:x,fromBlock:a})}catch{}if(O=!0,_)return}try{if(_){let R=await ue(e,J0,"getFilterChanges")({filter:_});D(R);return}let L=await ue(e,Ta,"getBlockNumber")({});S??=L;let P=L-S;for(;S{if(R===B||!Bb(A))throw A});if(!E)return;if(!C){P=(B-R+1n)/2n;continue}S=B,D(C)}}catch(L){_&&L instanceof _i&&(O=!1),T.onError?.(L)}},{emitOnBegin:!0,interval:f});return async()=>{E=!1,_&&await ue(e,X0,"uninstallFilter")({filter:_}),N()}})})():(()=>{let x=p??!1,v=bt(["watchContractEvent",n,o,s,e.uid,i,f,x]),T=!0,E=()=>T=!1;return Io(v,{onLogs:u,onError:c},S=>((async()=>{try{let _=gu(e),O=!!(i||p),D=i?nc({abi:r,eventName:i,args:o}):[],{unsubscribe:M}=await _.subscribe({params:["logs",{address:n,topics:D}],onData(N){if(!T)return;let L=N.result;try{let P=Yf({abi:r,data:L.data,eventName:i,topics:L.topics,strict:p}),R=qn(L,{args:P.args,eventName:P.eventName});S.onLogs([R])}catch(P){if(O&&(P instanceof Gf||P instanceof Yl||P instanceof Jl))return;let R,I;if(P instanceof jc||P instanceof Ql){if(p)return;R=P.abiItem.name,I=P.abiItem.inputs?.some(C=>!("name"in C&&C.name))}let B=qn(L,{args:I?[]:{},eventName:R});S.onLogs([B])}},onError(N){S.onError?.(N)}});E=M,T||E()}catch(_){c?.(_)}})(),()=>E()))})()}var IL=b(()=>{l();Qr();Lf();a3();Cg();hu();_t();rp();Fg();so();II();zg();s9();y3();n9();Zb();w3()});var kn,fc,yu=b(()=>{l();nt();kn=class extends G{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(` +`),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}},fc=class extends G{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}});function em({chain:e,currentChainId:t}){if(!e)throw new Sb;if(t!==e.id)throw new U0({chain:e,currentChainId:t})}var b3=b(()=>{l();Ug()});async function Gb(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var H9=b(()=>{l()});async function tm(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:s,authorizationList:i,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,type:x,value:v,...T}=t;if(typeof r>"u")throw new kn({docsPath:"/docs/actions/wallet/sendTransaction"});let E=r?ft(r):null,S;try{jn(t);let _=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await b0({authorization:i[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if(E?.type==="json-rpc"||E===null){let O;o!==null&&(O=await ue(e,hs,"getChainId")({}),n&&em({currentChainId:O,chain:o}));let D=e.chain?.formatters?.transactionRequest?.format,N=(D||Bn)({...Oi(T,{format:D}),accessList:s,account:E,authorizationList:i,blobs:a,chainId:O,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,to:_,type:x,value:v},"sendTransaction"),L=TL.get(e.uid),P=L?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:P,params:[N]},{retryCount:0})}catch(R){if(L===!1)throw R;let I=R;if(I.name==="InvalidInputRpcError"||I.name==="InvalidParamsRpcError"||I.name==="MethodNotFoundRpcError"||I.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[N]},{retryCount:0}).then(B=>(TL.set(e.uid,!0),B)).catch(B=>{let C=B;throw C.name==="MethodNotFoundRpcError"||C.name==="MethodNotSupportedRpcError"?(TL.set(e.uid,!1),I):C});throw I}}if(E?.type==="local"){let O=(()=>{if(!E.nonceManager||typeof w<"u")return E.nonceManager;let R=E.nonceManager;return{async consume(I){S={address:I.address,chainId:I.chainId};let B=await R.consume(I);return S={...S,nonce:B},B},get(I){return R.get(I)},increment(I){return R.increment(I)},reset(I){return R.reset(I)}}})(),D=await ue(e,pu,"prepareTransactionRequest")({account:E,accessList:s,authorizationList:i,blobs:a,chain:o,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,nonceManager:O,parameters:[...s3,"sidecars"],type:x,value:v,...T,to:_}),M=o?.serializers?.transaction,N=await E.signTransaction(D,{serializer:M}),L=(o??e.chain)?.serializers?.transactionEnvelope,P=L?await L({serializedTransaction:N,transaction:D}):N;return await ue(e,Gb,"sendRawTransaction")({serializedTransaction:P})}throw E?.type==="smart"?new fc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new fc({docsPath:"/docs/actions/wallet/sendTransaction",type:E?.type})}catch(_){throw _ instanceof fc?_:(S&&E?.nonceManager?.reset(S),H0(_,{...t,account:E,chain:t.chain||void 0}))}}var TL,x3=b(()=>{l();tn();yu();nt();Z4();b3();Fn();o3();P0();rl();_t();_f();nl();Zf();Rb();H9();TL=new xo(128)});async function _a(e,t){return _a.internal(e,tm,"sendTransaction",t)}var Yb=b(()=>{l();tn();yu();us();p0();_t();x3();(function(e){async function t(r,n,o,s){let{abi:i,account:a=r.account,address:c,args:u,functionName:d,...f}=s;if(typeof a>"u")throw new kn({docsPath:"/docs/contract/writeContract"});let p=a?ft(a):null,h=Wt({abi:i,args:u,functionName:d});try{return await ue(r,n,o)({data:h,to:c,account:p,...f})}catch(y){throw Js(y,{abi:i,address:c,args:u,docsPath:"/docs/contract/writeContract",functionName:d,sender:p?.address})}}e.internal=t})(_a||(_a={}))});function Aie({abi:e,address:t,client:r}){let n=r,[o,s]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],i=o!=null,a=s!=null,c={},u=!1,d=!1,f=!1;for(let p of e)if(p.type==="function"?p.stateMutability==="view"||p.stateMutability==="pure"?u=!0:d=!0:p.type==="event"&&(f=!0),u&&d&&f)break;return i&&(u&&(c.read=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o,er,"readContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),d&&(c.simulate=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o,Y0,"simulateContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),f&&(c.createEventFilter=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,Zw,"createContractEventFilter")({abi:e,address:t,eventName:h,args:x,...v})}}}),c.getEvents=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,kb,"getContractEvents")({abi:e,address:t,eventName:h,args:x,...v})}}}),c.watchEvent=new Proxy({},{get(p,h){return(...y)=>{let w=e.find(T=>T.type==="event"&&T.name===h),{args:x,options:v}=_L(y,w);return ue(o,M9,"watchContractEvent")({abi:e,address:t,eventName:h,args:x,...v})}}}))),a&&d&&(c.write=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(s,_a,"writeContract")({abi:e,address:t,functionName:h,args:w,...x})}}})),(i||a)&&d&&(c.estimateGas=new Proxy({},{get(p,h){return(...y)=>{let{args:w,options:x}=$9(y);return ue(o??s,$0,"estimateContractGas")({abi:e,address:t,functionName:h,args:w,...x,account:x.account??s.account})}}})),c.address=t,c.abi=e,c}function $9(e){let t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function _L(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);let n=r?e[0]:void 0,o=(r?e[1]:e[0])??{};return{args:n,options:o}}var Cie=b(()=>{l();_t();II();i3();s9();oi();g3();IL();Yb()});var Jb,PL=b(()=>{l();nt();Jb=class extends G{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}}});function np(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((s,i)=>{let a=()=>i(Nn(o));o?.addEventListener("abort",a,{once:!0});let c=async({count:u=0}={})=>{if(o?.aborted){i(Nn(o));return}let d=async({error:f})=>{let p=typeof t=="function"?t({count:u,error:f}):t;if(p)try{await $g(p,{signal:o})}catch(h){i(h);return}return c({count:u+1})};try{let f=await e();s(f)}catch(f){if(o?.aborted){i(Nn(o));return}if(Ti(f)){i(f);return}if(uo?.removeEventListener("abort",a))})}var v3=b(()=>{l();oc();D9()});function op(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>qn(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?wt(e.transactionIndex):null,status:e.status?NL[e.status]:null,type:e.type?Q4[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}var NL,Sie,Qb=b(()=>{l();Xr();Y4();hu();Ab();NL={"0x0":"reverted","0x1":"success"};Sie=N0("transactionReceipt",op)});async function F9(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:s=32,forceAtomic:i=!1,id:a,version:c="2.0.0"}=t,u=r?ft(r):null,d=t.capabilities;e.dataSuffix&&!t.capabilities?.dataSuffix&&(typeof e.dataSuffix=="string"?d={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}}:d={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}});let f=t.calls.map(p=>{let h=p,y=h.abi?Wt({abi:h.abi,functionName:h.functionName,args:h.args}):h.data;return{data:h.dataSuffix?en([y??"0x",h.dataSuffix]):y,to:h.to,value:h.value?oe(h.value):void 0}});try{let p=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:i,calls:f,capabilities:d,chainId:oe(n.id),from:u?.address,id:a,version:c}]},{retryCount:0});return typeof p=="string"?{id:p}:p}catch(p){let h=p;if(o&&(h.name==="MethodNotFoundRpcError"||h.name==="MethodNotSupportedRpcError"||h.name==="UnknownRpcError"||h.details.toLowerCase()==="this request method is not supported"||h.details.toLowerCase().includes("does not exist / is not available")||h.details.toLowerCase().includes("missing or invalid. request()")||h.details.toLowerCase().includes("did not match any variant of untagged enum")||h.details.toLowerCase().includes("account upgraded to unsupported contract")||h.details.toLowerCase().includes("eip-7702 not supported")||h.details.toLowerCase().includes("unsupported wc_ method")||h.details.toLowerCase().includes("feature toggled misconfigured")||h.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(d&&Object.values(d).some(v=>!v.optional)){let v="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new au(new G(v,{details:v}))}if(i&&f.length>1){let x="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new cu(new G(x,{details:x}))}let y=[];for(let x of f){try{let v=await ue(e,tm,"sendTransaction")({account:u,chain:n,data:x.data,to:x.to,value:x.value?dt(x.value):void 0});y.push({status:"fulfilled",value:v})}catch(v){y.push({reason:v,status:"rejected"})}s>0&&await new Promise(v=>setTimeout(v,s))}if(y.every(x=>x.status==="rejected"))throw y[0].reason;let w=y.map(x=>x.status==="fulfilled"?x.value:OL);return{id:en([...w,oe(n.id,{size:32}),RL])}}throw H0(p,{...t,account:u,chain:t.chain})}}var RL,OL,z9=b(()=>{l();tn();nt();Lf();us();Fn();Xr();qe();o3();_t();x3();RL="0x5792579257925792579257925792579257925792579257925792579257925792",OL=oe(0,{size:32})});async function V9(e,t){async function r(d){if(d.endsWith(RL.slice(2))){let p=bn(xa(d,-64,-32)),h=xa(d,0,-64).slice(2).match(/.{1,64}/g),y=await Promise.all(h.map(x=>OL.slice(2)!==x?e.request({method:"eth_getTransactionReceipt",params:[`0x${x}`]},{dedupe:!0}):void 0)),w=y.some(x=>x===null)?100:y.every(x=>x?.status==="0x1")?200:y.every(x=>x?.status==="0x0")?500:600;return{atomic:!1,chainId:wt(p),receipts:y.filter(Boolean),status:w,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[d]})}let{atomic:n=!1,chainId:o,receipts:s,version:i="2.0.0",...a}=await r(t.id),[c,u]=(()=>{let d=a.status;return d>=100&&d<200?["pending",d]:d>=200&&d<300?["success",d]:d>=300&&d<700?["failure",d]:d==="CONFIRMED"?["success",200]:d==="PENDING"?["pending",100]:[void 0,d]})();return{...a,atomic:n,chainId:o?wt(o):void 0,receipts:s?.map(d=>({...d,blockNumber:dt(d.blockNumber),gasUsed:dt(d.gasUsed),status:NL[d.status]}))??[],statusCode:u,status:c,version:i}}var BL=b(()=>{l();Ii();Hh();Xr();Qb();z9()});function Tie(e){let t=Iie.get(e);return t===void 0&&(t=++YDe,Iie.set(e,t)),t}async function j9(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:w})=>w===200||w>=300,retryCount:s=4,retryDelay:i=({count:w})=>~~(1<{let x=dc(async()=>{let v=T=>{clearTimeout(h),x(),T(),y()};try{let T=await np(async()=>{let E=await ue(e,V9,"getCallsStatus")({id:r});if(c&&E.status==="failure")throw new Jb(E);return E},{retryCount:s,delay:i});if(!o(T))return;v(()=>w.resolve(T))}catch(T){v(()=>w.reject(T))}},{interval:n,emitOnBegin:!0});return x});return h=a?setTimeout(()=>{y(),clearTimeout(h),p(new E3({id:r}))},a):void 0,await d.finally(()=>y())}var Iie,YDe,E3,q9=b(()=>{l();nt();PL();_t();rp();Fg();A9();v3();so();BL();Iie=new WeakMap,YDe=0;E3=class extends G{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}});function rm(e=11){if(!K9||W9+e>256*2){K9="",W9=0;for(let t=0;t<256;t++)K9+=(256+Math.random()*256|0).toString(16).substring(1)}return K9.substring(W9,W9+++e)}var W9,K9,A3=b(()=>{l();W9=256});function wu(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:s="base",name:i="Base Client",tokens:a,type:c="base"}=e,u=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime=="number"?"pending":void 0),d=r?.blockTime??12e3,f=Math.min(Math.max(Math.floor(d/2),500),4e3),p=e.pollingInterval??f,h=e.cacheTime??Math.min(p,Math.floor(d/2)),y=e.account?ft(e.account):void 0,{config:w,request:x,value:v}=e.transport({account:y,chain:r,pollingInterval:p}),T={...w,...v},E={account:y,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:s,name:i,pollingInterval:p,request:x,tokens:a,transport:T,type:c,uid:rm(),...u?{experimental_blockTag:u}:{}};return Nie(E)}function Nie(e){function t(n,o){return s=>{let i=s(n);for(let d in e)d!=="scope"&&delete i[d];let a={...n,...i};for(let d in i){let f=n[d],p=i[d];Pie(f)&&Pie(p)&&(a[d]={...f,...p})}let c=[...o,s],{scope:u}=a;return Object.assign(a,{extend:t(a,c),scope:typeof u=="function"&&_ie.has(u)?r(c):u})}}function r(n){let o=new WeakMap,s=(i={})=>{let a=i.signal&&o.get(i.signal);if(a)return a;let c=`scope.${JDe++}`,u=new AbortController,{signal:d}=i;d?.aborted?u.abort(d.reason):d?.addEventListener("abort",()=>u.abort(d.reason),{once:!0});let f=(h,y)=>e.request(h,{...y,signal:y?.signal??u.signal,uid:y?.uid??c}),p=n.reduce((h,y)=>h.extend(y),Nie({...e,request:f,uid:c}));return d&&o.set(d,p),p};return _ie.add(s),s}return Object.assign(e,{extend:t(e,[]),scope:r([])})}function Pie(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bu(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(s={})=>o.length===1?o(s):o(e,s)}for(let n of["extractEvent","extractEvents"])Object.hasOwn(t,n)&&(r[n]=t[n]);return r}function Rie(){return null}var _ie,JDe,nm=b(()=>{l();tn();A3();_ie=new WeakSet,JDe=0});function Oie(e){let{chains:t,transport:r,...n}=e,o=new Map;return{getClient({chainId:s}){let i=o.get(s);if(i)return i;let a=t.find(d=>d.id===s);if(!a)throw new C3({chainId:s});let c=typeof r=="function"?r({chainId:s}):r[s];if(!c)throw new S3({chainId:s});let u=wu({...n,chain:a,transport:c});return o.set(s,u),u}}}var C3,S3,Bie=b(()=>{l();nt();nm();C3=class extends G{constructor({chainId:t}){super(`Chain with id ${t} is not configured.`,{name:"createClientResolver.ChainNotConfiguredError"})}},S3=class extends G{constructor({chainId:t}){super(`Transport for chain with id ${t} is not configured.`,{name:"createClientResolver.TransportNotConfiguredError"})}}});function Xb(e){if(!(e instanceof G))return!1;let t=e.walk(r=>r instanceof Uf);return t instanceof Uf?t.data?.errorName==="HttpError"||t.data?.errorName==="ResolverError"||t.data?.errorName==="ResolverNotContract"||t.data?.errorName==="ResolverNotFound"||t.data?.errorName==="ReverseAddressMismatch"||t.data?.errorName==="UnsupportedResolverProfile":!1}var Z9=b(()=>{l();nt();ou()});function G9(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;return We(t)?t:null}var kL=b(()=>{l();qs()});function Vg(e){let t=new Uint8Array(32).fill(0);if(!e)return yt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=G9(r[n]),s=o?un(o):Pt(zo(r[n]),"bytes");t=Pt(en([t,s]),"bytes")}return yt(t)}var Y9=b(()=>{l();Fn();Pr();qe();Ks();kL()});function kie(e){return`[${e.slice(2)}]`}var Uie=b(()=>{l()});function J9(e){let t=new Uint8Array(32).fill(0);return e?G9(e)||Pt(zo(e)):yt(t)}var UL=b(()=>{l();Pr();qe();Ks();kL()});function e6(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(zo(t).byteLength+2),n=0,o=t.split(".");for(let s=0;s255&&(i=zo(kie(J9(o[s])))),r[n]=i.length,r.set(i,n+1),n+=i.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}var Q9=b(()=>{l();Pr();Uie();UL()});async function Die(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:s,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Di({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(p=>s.endsWith(p)))return null;let f=o!=null?[Vg(s),BigInt(o)]:[Vg(s)];try{let p=Wt({abi:fL,functionName:"addr",args:f}),h={address:u,abi:b9,functionName:"resolveWithGateways",args:[wr(e6(s)),p,i??[Ia]],blockNumber:r,blockTag:n},w=await ue(e,er,"readContract")(h);if(w[0]==="0x")return null;let x=QDe({coinType:o,data:w[0],args:f});return x==="0x"||bn(x)==="0x00"?null:x}catch(p){if(a)throw p;if(Xb(p))return null;throw p}}function QDe({coinType:e,data:t,args:r}){try{return dn({abi:fL,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=20,s=32,i=bn(t),a=gt(i),c=gt(t);if((e===60n||e>=0x80000000n&&e<=0xffffffffn)&&(c===o||c===s)&&a{l();So();lc();us();Zs();K0();Xa();Fo();Hh();qe();Z9();qb();Y9();Q9();_t();oi()});function tLe(e,t={}){let{pad:r=!0,url:n=!1}=t,o=new Uint8Array(Math.ceil(e.length/3)*4);for(let c=0,u=0;u>18],o[c+1]=X9[d>>12&63],o[c+2]=X9[d>>6&63],o[c+3]=X9[d&63]}let s=e.length%3,i=Math.floor(e.length/3)*4+(s&&s+1),a=eLe.decode(new Uint8Array(o.buffer,0,i));return r&&s===1&&(a+="=="),r&&s===2&&(a+="="),n&&(a=a.replaceAll("+","-").replaceAll("/","_")),a}function Mie(e,t={}){return tLe(Mb(e),t)}function rLe(e){let t=e.replace(/=+$/,""),r=t.length,n=new Uint8Array(r+3);XDe.encodeInto(t+"===",n);for(let s=0,i=0;s>16,n[i+1]=a>>8&255,n[i+2]=a&255}let o=(r>>2)*3+(r%4&&r%4-1);return new Uint8Array(n.buffer,0,o)}function Hie(e){return d9(rLe(e))}var XDe,eLe,X9,eT,DL=b(()=>{l();mu();XDe=new TextEncoder,eLe=new TextDecoder,X9=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),eT={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var tT,xu,om,t6,r6,rT=b(()=>{l();nt();tT=class extends G{constructor({data:t}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(t)}`],name:"EnsAvatarInvalidMetadataError"})}},xu=class extends G{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}},om=class extends G{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}},t6=class extends G{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}},r6=class extends G{constructor({chainId:t}){super(`Invalid ENSIP-11 chainId: ${t}. Must be between 0 and 0x7fffffff, or 1.`,{name:"EnsInvalidChainIdError"})}}});async function cLe(e,{timeout:t=zie}={}){try{let r=await sl(({signal:n})=>fetch(e,{method:"HEAD",...n?{signal:n}:{}}),{errorInstance:new ds({body:{},url:e}),signal:!0,timeout:t});return r.status===200?r.headers.get("content-type")?.startsWith("image/"):!1}catch(r){return r instanceof ds||typeof r=="object"&&typeof r.response<"u"||!Object.hasOwn(globalThis,"Image")?!1:new Promise(n=>{let o=new Image;o.onload=()=>{n(!0)},o.onerror=()=>{n(!1)},o.src=e})}}function Fie(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function LL({uri:e,gatewayUrls:t}){let r=sLe.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=Fie(t?.ipfs,"https://ipfs.io"),o=Fie(t?.arweave,"https://arweave.net"),s=e.match(nLe),{protocol:i,subpath:a,target:c,subtarget:u=""}=s?.groups||{},d=i==="ipns:/"||a==="ipns/",f=i==="ipfs:/"||a==="ipfs/"||oLe.test(e);if(e.startsWith("http")&&!d&&!f){let h=e;return t?.arweave&&(h=e.replace(/https:\/\/arweave.net/g,t?.arweave)),{uri:h,isOnChain:!1,isEncoded:!1}}if((d||f)&&c)return{uri:`${n}/${d?"ipns":"ipfs"}/${c}${u}`,isOnChain:!1,isEncoded:!1};if(i==="ar:/"&&c)return{uri:`${o}/${c}${u||""}`,isOnChain:!1,isEncoded:!1};let p=e.replace(iLe,"");if(p.startsWith("{let i=await fetch(r,s?{signal:s}:{});return Wb(i,{maxResponseBodySize:aLe})},{errorInstance:new ds({body:{},url:r}),signal:!0,timeout:t});return await nT({gatewayUrls:e,uri:ML(JSON.parse(n))})}catch{throw new om({uri:r})}}async function nT({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=LL({uri:t,gatewayUrls:e});if(n||await cLe(r))return r;throw new om({uri:t})}function jie(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));let[r,n,o]=t.split("/"),[s,i]=r.split(":"),[a,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new xu({reason:"Only EIP-155 supported"});if(!i)throw new xu({reason:"Chain ID not found"});if(!c)throw new xu({reason:"Contract address not found"});if(!o)throw new xu({reason:"Token ID not found"});if(!a)throw new xu({reason:"ERC namespace not found"});return{chainID:Number.parseInt(i,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function qie(e,{nft:t}){if(t.namespace==="erc721")return er(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return er(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new t6({namespace:t.namespace})}function Wie({nft:e,uri:t}){let r=e.namespace==="erc1155"?oe(BigInt(e.tokenID),{size:32}).slice(2):e.tokenID;return t.replace(/(?:0x)?{id}/,r)}var nLe,oLe,sLe,iLe,zie,aLe,Kie=b(()=>{l();DL();oi();rT();fs();qe();N9();Kb();nLe=/(?https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/,oLe=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/,sLe=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,iLe=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/,zie=1e4,aLe=10485760});async function Zie(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?lLe(e,{gatewayUrls:t,record:r}):nT({uri:r,gatewayUrls:t})}async function lLe(e,{gatewayUrls:t,record:r}){let n=jie(r),o=await qie(e,{nft:n}),{uri:s,isOnChain:i,isEncoded:a}=LL({uri:o,gatewayUrls:t});if(i&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){let c=a?Hie(s.replace("data:application/json;base64,","").replace(/\s/g,"")):s,u=JSON.parse(c);return nT({uri:ML(u),gatewayUrls:t})}return Vie({gatewayUrls:t,uri:Wie({nft:n,uri:s})})}var Gie=b(()=>{l();DL();Kie()});async function oT(e,t){let{blockNumber:r,blockTag:n,key:o,name:s,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Di({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),d=c?.ensTlds;if(d&&!d.some(f=>s.endsWith(f)))return null;try{let f={address:u,abi:b9,args:[wr(e6(s)),Wt({abi:dL,functionName:"text",args:[Vg(s),o]}),i??[Ia]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await ue(e,er,"readContract")(f);if(h[0]==="0x")return null;let y=dn({abi:dL,functionName:"text",data:h[0]});return y===""?null:y}catch(f){if(a)throw f;if(Xb(f))return null;throw f}}var HL=b(()=>{l();So();lc();us();K0();qe();Z9();qb();Y9();Q9();_t();oi()});async function Yie(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:s,strict:i,universalResolverAddress:a}){let c=await ue(e,oT,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:s,strict:i});if(!c)return null;try{return await Zie(e,{record:c,gatewayUrls:n})}catch{return null}}var Jie=b(()=>{l();Gie();_t();HL()});async function Qie(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:s=60n,gatewayUrls:i,strict:a}=t,{chain:c}=e,u=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Di({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let d={address:u,abi:lie,args:[r,s,i??[Ia]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},f=ue(e,er,"readContract"),[p]=await f(d);return p||null}catch(d){if(a)throw d;if(Xb(d))return null;throw d}}var Xie=b(()=>{l();So();K0();Z9();qb();_t();oi()});async function eae(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:s}=e,i=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return Di({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),a=s?.ensTlds;if(a&&!a.some(u=>o.endsWith(u)))throw new Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);let[c]=await ue(e,er,"readContract")({address:i,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[wr(e6(o))],blockNumber:r,blockTag:n});return c}var tae=b(()=>{l();K0();qe();Q9();_t();oi()});async function rae(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:s,data:i,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,to:p,value:h,...y}=t,w=r?ft(r):void 0;try{jn(t);let v=(typeof n=="bigint"?oe(n):void 0)||o,T=e.chain?.formatters?.transactionRequest?.format,S=(T||Bn)({...Oi(y,{format:T}),account:w,blobs:s,data:i,gas:a,gasPrice:c,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:f,to:p,value:h},"createAccessList"),_=await e.request({method:"eth_createAccessList",params:[S,v]});if(_.error)throw new G(_.error,{details:_.error});return{accessList:_.accessList,gasUsed:BigInt(_.gasUsed)}}catch(x){throw E9(x,{...t,account:w,chain:e.chain})}}var nae=b(()=>{l();tn();nt();qe();hL();P0();rl();nl()});async function oae(e){let t=Fh(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}var sae=b(()=>{l();N4()});async function sT(e,{address:t,args:r,event:n,events:o,fromBlock:s,strict:i,toBlock:a}={}){let c=o??(n?[n]:void 0),u=Fh(e,{method:"eth_newFilter"}),d=[];c&&(d=[c.flatMap(h=>nc({abi:[h],eventName:h.name,args:r}))],n&&(d=d[0]));let f=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?oe(s):s,toBlock:typeof a=="bigint"?oe(a):a,...d.length?{topics:d}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:f,request:u(f),strict:!!i,toBlock:a,type:"event"}}var $L=b(()=>{l();Cg();qe();N4()});async function iT(e){let t=Fh(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}var FL=b(()=>{l();N4()});async function iae(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,u=Wt({abi:Ui,functionName:"getEthBalance",args:[t]}),{data:d}=await ue(e,ms,"call")({to:c,data:u,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});return dn({abi:Ui,functionName:"getEthBalance",args:[t],data:d||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,i]});return BigInt(a)}var aae=b(()=>{l();So();lc();us();B0();_t();G0()});async function cae(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var lae=b(()=>{l()});async function uae(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?oe(r):void 0,s=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:!!(t||o)});if(!s)throw new du({blockHash:t,blockNumber:r});let i=e.chain?.formatters?.transactionReceipt?.format||op;return s.map(a=>i(a,"getBlockReceipts"))}var dae=b(()=>{l();J4();qe();Qb()});async function fae(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?oe(r):void 0,s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:!!o}),wt(s)}var pae=b(()=>{l();Xr();qe()});async function jg(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s}){let i=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),a=await e.request({method:"eth_getCode",params:[t,i]},{dedupe:typeof n=="bigint"||r!==void 0});if(a!=="0x")return a}var aT=b(()=>{l();B0()});async function hae(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await ue(e,jg,"getCode")({address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(o&>(o)===23&&o.startsWith("0xef0100"))return Gr(vo(o,3,23))}var mae=b(()=>{l();Zs();Fo();Ii();_t();aT()});var cT,gae=b(()=>{l();nt();cT=class extends G{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}});async function yae(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[s,i,a,c,u,d,f]=await ue(e,er,"readContract")({abi:uLe,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:i,version:a,chainId:Number(c),verifyingContract:u,salt:d},extensions:f,fields:s}}catch(s){let i=s;throw i.name==="ContractFunctionExecutionError"&&i.cause.name==="ContractFunctionZeroDataError"?new cT({address:r}):i}}var uLe,wae=b(()=>{l();gae();_t();oi();uLe=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}]});function bae(e){return{baseFeePerGas:e.baseFeePerGas.map(t=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map(t=>t.map(r=>BigInt(r)))}}var xae=b(()=>{l()});async function vae(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let s=typeof r=="bigint"?oe(r):void 0,i=await e.request({method:"eth_feeHistory",params:[oe(t),s||n,o]},{dedupe:!!s});return bae(i)}var Eae=b(()=>{l();qe();xae()});async function Aae(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>qn(s));return t.abi?cc({abi:t.abi,eventName:t.eventName,logs:o,strict:r}):o}var Cae=b(()=>{l();Dg();hu()});function Sae(e,t){if(e.length!==t.length)throw new kh({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n{l();Qr();tc();Gs();Fn();Xa();qe();P4()});function I3(e){return!e||typeof e!="object"||!("BYTES_PER_ELEMENT"in e)?!1:e.BYTES_PER_ELEMENT===1&&e.constructor.name==="Uint8Array"}var zL=b(()=>{l()});function _ae(e){return e.opcode==="CREATE2"?jL(e):VL(e)}function VL(e){let t=un(Gr(e.from)),r=un(e.nonce);return r[0]===0&&(r=new Uint8Array([])),Gr(`0x${Pt(Vo([t,r],"bytes")).slice(26)}`)}function jL(e){let t=un(Gr(e.from)),r=Zr(I3(e.salt)?e.salt:un(e.salt),{size:32}),n="bytecodeHash"in e?I3(e.bytecodeHash)?e.bytecodeHash:un(e.bytecodeHash):Pt(e.bytecode,"bytes");return Gr(vo(Pt(en([un("0xff"),t,r,n])),12))}var Pae=b(()=>{l();Fn();zL();Xa();Ii();Pr();wb();Ks();Zs()});function lT(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!Ft(o))throw new br({address:o});if(n<0)throw new Kf({chainId:n})}sm(e)}function uT(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new _b;for(let r of t){let n=gt(r),o=wt(vo(r,0,1));if(n!==32)throw new JI({hash:r,size:n});if(o!==1)throw new QI({hash:r,version:o})}}sm(e)}function sm(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new Kf({chainId:t});if(o&&!Ft(o))throw new br({address:o});if(n&&n>R0)throw new Ni({maxFeePerGas:n});if(typeof r=="bigint"&&typeof n=="bigint"&&r>n)throw new ac({maxFeePerGas:n,maxPriorityFeePerGas:r})}function n6(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(t<=0)throw new Kf({chainId:t});if(s&&!Ft(s))throw new br({address:s});if(r||o)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>R0)throw new Ni({maxFeePerGas:n})}function o6(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(s&&!Ft(s))throw new br({address:s});if(typeof t<"u"&&t<=0)throw new Kf({chainId:t});if(r||o)throw new G("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>R0)throw new Ni({maxFeePerGas:n})}var dT=b(()=>{l();jI();tc();nt();YD();Ug();tl();Gs();Fo();Ii();Xr()});function qg(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r{l();tc();zn();Gs()});function fT(e,t){let r=Pb(e);return r==="eip1559"?pLe(e,t):r==="eip2930"?hLe(e,t):r==="eip4844"?fLe(e,t):r==="eip7702"?dLe(e,t):mLe(e,t)}function dLe(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:s,to:i,value:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:f}=e;lT(e);let p=qg(d),h=Nae(r);return fr(["0x04",Vo([oe(n),s?oe(s):"0x",u?oe(u):"0x",c?oe(c):"0x",o?oe(o):"0x",i??"0x",a?oe(a):"0x",f??"0x",p,h,...s6(e,t)])])}function fLe(e,t){let{chainId:r,gas:n,nonce:o,to:s,value:i,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:u,accessList:d,data:f}=e;uT(e);let p=e.blobVersionedHashes,h=e.sidecars;if(e.blobs&&(typeof p>"u"||typeof h>"u")){let E=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(O=>yt(O)),S=e.kzg,_=D0({blobs:E,kzg:S});if(typeof p>"u"&&(p=Tb({commitments:_})),typeof h>"u"){let O=L0({blobs:E,commitments:_,kzg:S});h=M0({blobs:E,commitments:_,proofs:O})}}let y=qg(d),w=[oe(r),o?oe(o):"0x",u?oe(u):"0x",c?oe(c):"0x",n?oe(n):"0x",s??"0x",i?oe(i):"0x",f??"0x",y,a?oe(a):"0x",p??[],...s6(e,t)],x=[],v=[],T=[];if(h)for(let E=0;E{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new Kh({v:t.v});return h})(),f=bn(t.r),p=bn(t.s);u=[...u,oe(d),f==="0x00"?"0x":f,p==="0x00"?"0x":p]}else r>0&&(u=[...u,oe(r),"0x","0x"]);return Vo(u)}function s6(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let s=bn(r.r),i=bn(r.s);return[typeof o=="number"?o?oe(1):"0x":n===0n?"0x":n===1n?oe(1):n===27n?"0x":oe(1),s==="0x00"?"0x":s,i==="0x00"?"0x":i]}var pT=b(()=>{l();zn();Rae();t3();r3();GI();n3();Fn();Hh();qe();wb();dT();e9();qL()});function Nae(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...s}=r,i=r.address,a=s6({},s);a.length>0&&s.yParity&&(a[0]=wr(s.yParity)),t.push([n?wr(n):"0x",i,o?wr(o):"0x",...a])}return t}var Rae=b(()=>{l();qe();pT()});async function Oae({address:e,authorization:t,signature:r}){let n=await(async()=>{try{return await b0({authorization:t,signature:r})}catch(o){if(o instanceof tu)return;throw o}})();return n?xr(Gr(e),n):!1}var Bae=b(()=>{l();zn();Zs();Bi();Z4()});function kae(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(hT.get(r))return hT.get(r);let n=e().finally(()=>hT.delete(r));return hT.set(r,n),n}var hT,Uae=b(()=>{l();_f();hT=new xo(8192)});function Dae(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:s,retryDelay:i=150,retryCount:a=3,signal:c,uid:u}={...t,...n},{method:d}=r;if(s?.exclude?.includes(d))throw new Aa(new Error("method not supported"),{method:d});if(s?.include&&!s.include.includes(d))throw new Aa(new Error("method not supported"),{method:d});if(c?.aborted)throw Nn(c);let f=o?yLe(`${u}.${bt(r)}`):void 0;return kae(()=>np(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(p){if(c?.aborted)throw Nn(c);if(Ti(p))throw p;let h=p;switch(h.code){case Yh.code:throw new Yh(h);case Jh.code:throw new Jh(h);case Jc.code:throw new Jc(h,{method:r.method});case Qh.code:throw new Qh(h);case Qc.code:throw new Qc(h);case _i.code:throw new _i(h);case Xh.code:throw new Xh(h);case e0.code:throw new e0(h);case iu.code:throw new iu(h);case Aa.code:throw new Aa(h,{method:r.method});case Df.code:throw new Df(h);case t0.code:throw new t0(h);case Xc.code:throw new Xc(h);case r0.code:throw new r0(h);case n0.code:throw new n0(h);case o0.code:throw new o0(h);case s0.code:throw new s0(h);case i0.code:throw new i0(h);case au.code:throw new au(h);case a0.code:throw new a0(h);case c0.code:throw new c0(h);case l0.code:throw new l0(h);case u0.code:throw new u0(h);case d0.code:throw new d0(h);case cu.code:throw new cu(h);case 5e3:throw new Xc(h);case f0.code:throw new f0(h);default:throw p instanceof G?p:new ub(h)}}},{delay:({count:p,error:h})=>{let y=Lae(h)?.headers?.get("Retry-After");if(y){let w=Number.parseInt(y,10);if(!Number.isNaN(w))return w*1e3;let x=Date.parse(y)-Date.now();if(x>0)return x}return~~(1<gLe(p)}),{enabled:o,id:f})}}function gLe(e){if(Ti(e))return!1;let t=Lae(e)?.status;if("code"in e&&typeof e.code=="number"){if(e.code===-1||e.code===Df.code||e.code===Qc.code||e.code===429||e.code===-32007)return!0;if(e.code===Jc.code||e.code===Aa.code||!t)return!1}return t?t===403||t===408||t===413||t===429||t===500||t===502||t===503||t===504:!0}function Lae(e){if(e instanceof G)return e.walk(t=>t instanceof Nr||t instanceof Rn)}function yLe(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}var Mae=b(()=>{l();nt();fs();Lf();oc();Uae();v3();so()});function Hae({batchGateways:e,ccipRequest:t=Hg}){return{async request({data:r,requestOptions:n,sender:o,timeout:s,urls:i}){if(i.includes(Ia))return t({data:r,requestOptions:n,sender:o,timeout:s,urls:e});{let[a,c]=dn({abi:W0,functionName:"query",data:await t({data:Wt({abi:W0,functionName:"query",args:[[{sender:o,data:r,urls:i}]]}),requestOptions:n,sender:o,timeout:s,urls:e})});if(a[0]){let u;try{let d=Vh({abi:[...W0,Gw],data:c[0]});if(d.errorName==="HttpError")u=new Nr({body:{message:d.args[1]},status:d.args[0],url:i.join(" | ")});else{let f=d.args[0];f&&(u=new Error(f))}}catch{}throw u??new Error("An unknown error occurred.")}return c[0]}}}}var $ae=b(()=>{l();So();R4();fs();L4();lc();us();k9();qb()});function Fae(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return o=>{let s=typeof o=="function"?o(n):o,i={...n,...s};return Object.assign(i,{extend:r(i)})}}return Object.assign(t,{extend:r(t)})}function zae(){return{}}var Vae=b(()=>{l()});function jae({chains:e,id:t}){return e.find(r=>r.id===t)}var qae=b(()=>{l()});function Wg(e,t="hex"){let r=(()=>{if(typeof e=="string"){if(e.length>3&&e.length%2!==0)throw new $w(e);return qt(e)}return e})(),n=Zc(r,{recursiveReadLimit:Number.POSITIVE_INFINITY}),o=Zae(n,t);if(n.position=Wae)throw new Fw({limit:Wae});if(e.bytes.length===0)return t==="hex"?yt(e.bytes):e.bytes;let n=e.readByte();if(n<128&&e.decrementPosition(1),n<192){let s=Kae(e,n,128),i=e.readBytes(s);return t==="hex"?yt(i):i}let o=Kae(e,n,192);return wLe(e,o,t,r+1)}function Kae(e,t,r){if(r===128&&t<128)return 1;if(t<=r+55)return t-r;if(t===r+55+1)return e.readUint8();if(t===r+55+2)return e.readUint16();if(t===r+55+3)return e.readUint24();if(t===r+55+4)return e.readUint32();throw new G("Invalid RLP prefix")}function wLe(e,t,r,n){let o=e.position,s=[];for(;e.position-o{l();nt();yg();Jw();Pr();qe();Wae=1024});function i6(e){return We(e)&&e.length===66}var gT=b(()=>{l();qs()});function Gae(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}var bLe,Yae,xLe,Jae,Qae,Xae,ece,vLe,ELe,ALe,CLe,yT,wT,tce,rce=b(()=>{l();hD();Tf();bLe=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Yae=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),xLe=Yae.map(e=>(9*e+5)%16),Jae=(()=>{let r=[[Yae],[xLe]];for(let n=0;n<4;n++)for(let o of r)o.push(o[n].map(s=>bLe[s]));return r})(),Qae=Jae[0],Xae=Jae[1],ece=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),vLe=Qae.map((e,t)=>e.map(r=>ece[t][r])),ELe=Xae.map((e,t)=>e.map(r=>ece[t][r])),ALe=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),CLe=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);yT=new Uint32Array(16),wT=class extends db{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:t,h1:r,h2:n,h3:o,h4:s}=this;return[t,r,n,o,s]}set(t,r,n,o,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=o|0,this.h4=s|0}process(t,r){for(let h=0;h<16;h++,r+=4)yT[h]=t.getUint32(r,!0);let n=this.h0|0,o=n,s=this.h1|0,i=s,a=this.h2|0,c=a,u=this.h3|0,d=u,f=this.h4|0,p=f;for(let h=0;h<5;h++){let y=4-h,w=ALe[h],x=CLe[h],v=Qae[h],T=Xae[h],E=vLe[h],S=ELe[h];for(let _=0;_<16;_++){let O=S4(n+Gae(h,s,a,u)+yT[v[_]]+w,E[_])+f|0;n=f,f=u,u=S4(a,10)|0,a=s,s=O}for(let _=0;_<16;_++){let O=S4(o+Gae(y,i,c,d)+yT[T[_]]+x,S[_])+p|0;o=p,p=d,d=S4(c,10)|0,c=i,i=O}}this.set(this.h1+a+d|0,this.h2+u+p|0,this.h3+f+o|0,this.h4+n+i|0,this.h0+s+c|0)}roundClean(){ba(yT)}destroy(){this.destroyed=!0,ba(this.buffer),this.set(0,0,0,0,0)}},tce=Ww(()=>new wT)});var nce,oce=b(()=>{l();rce();nce=tce});function sce(e,t){let r=t||"hex",n=nce(We(e,{strict:!1})?un(e):e);return r==="bytes"?n:wr(n)}var ice=b(()=>{l();oce();qs();Pr();qe()});var ace=b(()=>{l();T4()});var cce=b(()=>{l();SI()});var lce=b(()=>{l();T4()});var uce=b(()=>{l();SI()});function WL(e){let{source:t}=e,r=new Map,n=new xo(8192),o=new Map,s=({address:a,chainId:c})=>`${a}.${c}`,i=a=>{r.delete(a),o.delete(a)};return{async consume({address:a,chainId:c,client:u}){let d=s({address:a,chainId:c}),f=this.get({address:a,chainId:c,client:u});this.increment({address:a,chainId:c});let p=await f;return await t.set({address:a,chainId:c},p),n.set(d,p),p},async increment({address:a,chainId:c}){let u=s({address:a,chainId:c}),d=r.get(u)??0;r.set(u,d+1)},async get({address:a,chainId:c,client:u}){let d=s({address:a,chainId:c}),f=o.get(d);return f||(f=(async()=>{try{let h=await t.get({address:a,chainId:c,client:u}),y=n.get(d);return y!==void 0&&h<=y?y+1:(n.delete(d),h)}finally{i(d)}})(),o.set(d,f)),(r.get(d)??0)+await f},reset({address:a,chainId:c}){let u=s({address:a,chainId:c});n.delete(u),i(u)}}}function SLe(){return{async get(e){let{address:t,client:r}=e;return k0(r,{address:t,blockTag:"pending"})},set(){}}}var dce,fce=b(()=>{l();e3();_f();dce=WL({source:SLe()})});function ILe(){return{current:0,take(){return this.current++},reset(){this.current=0}}}var a6,KL=b(()=>{l();a6=ILe()});function mce(e,t={}){let{url:r,headers:n}=_Le(e);return{async request(o){let{body:s,fetchFn:i=t.fetchFn??fetch,maxResponseBodySize:a=t.maxResponseBodySize??TLe,onRequest:c=t.onRequest,onResponse:u=t.onResponse,timeout:d=t.timeout??1e4}=o,f={...t.fetchOptions??{},...o.fetchOptions??{}},{headers:p,method:h,signal:y}=f;try{let{response:w,responseBody:x}=await sl(async({signal:E})=>{let{signal:S,cleanup:_}=P9([y,d>0?E:null]);try{let O={};for(let P of[n,{"Content-Type":"application/json"},p])new Headers(P).forEach((R,I)=>{O[I]=R});let D={...f,body:Array.isArray(s)?bt(s.map(P=>({jsonrpc:"2.0",id:P.id??a6.take(),...P}))):bt({jsonrpc:"2.0",id:s.id??a6.take(),...s}),headers:O,method:h||"POST",signal:S},M=(c&&await c(new Request(r,D),D))??{...D,url:r},N=await i(M.url??r,M);u&&await u(N);let L=await Wb(N,{maxResponseBodySize:a});return{response:N,responseBody:L}}finally{_()}},{errorInstance:pce,timeout:d,signal:!0}),v;if(w.headers.get("Content-Type")?.startsWith("application/json"))v=JSON.parse(x);else{v=x;try{v=JSON.parse(v||"{}")}catch(E){if(w.ok)throw E;v={error:v}}}let T=Array.isArray(s)&&Array.isArray(v)&&v.length===1?v[0]:v;if(!w.ok)throw hce(T)?new Rn({body:s,error:T.error,headers:w.headers,status:w.status,url:r}):new Nr({body:s,details:bt(v.error)||w.statusText,headers:w.headers,status:w.status,url:r});if(!Array.isArray(s)||!s.length||Array.isArray(v)&&v.length>=s.length)return v;if(!hce(T))throw new Error(`Expected ${s.length} responses to batch request.`);return s.map(()=>T)}catch(w){throw y?.aborted?Nn(y):w===pce?new ds({body:s,url:r}):Ti(w)||w instanceof Nr||w instanceof ic||w instanceof Rn||w instanceof ds?w:new Nr({body:s,cause:w,url:r})}}}}function hce(e){return typeof e?.error?.code=="number"&&typeof e?.error?.message=="string"}function _Le(e){try{let t=new URL(e),r=(()=>{if(t.username){let n=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:t.toString(),...r}}catch{return{url:e}}}var TLe,pce,gce=b(()=>{l();fs();oc();N9();Kb();so();KL();TLe=10485760,pce=new Error("timed out")});async function wce(e){let{getSocket:t,keepAlive:r=!0,key:n="socket",reconnect:o=!0,url:s}=e,{interval:i=3e4}=typeof r=="object"?r:{},{attempts:a=5,delay:c=2e3}=typeof o=="object"?o:{},u=JSON.stringify({keepAlive:r,key:n,url:s,reconnect:o}),d=ZL.get(u);if(d)return d;let f=0,{schedule:p}=Z0({id:u,fn:async()=>{let w=new Map,x=new Map,v,T,E,S,_=!1,O=!1;function D(){if(o&&!O&&f{if(S=void 0,O){_=!1;return}await M().catch(console.error),_=!1},c)}else w.clear(),x.clear()}async function M(){let N=await t({onClose(){for(let L of w.values())L.onError?.(new su({url:s}));for(let L of x.values())L.onError?.(new su({url:s}));D()},onError(L){v=L;for(let P of w.values())P.onError?.(v);for(let P of x.values())P.onError?.(v);D()},onOpen(){v=void 0,f=0},onResponse(L){let P=L.method==="eth_subscription",R=P?L.params.subscription:L.id,I=P?x:w,B=I.get(R);B&&B.onResponse(L),P||I.delete(R)}});if(O)return N.close(),N;if(T=N,r&&(E&&clearInterval(E),E=setInterval(()=>T.ping?.(),i)),o&&x.size>0){let L=x.entries();for(let[P,{onResponse:R,body:I,onError:B}]of L)I&&(x.delete(P),d?.request({body:I,onResponse:R,onError:B}))}return N}return await M(),v=void 0,d={close(){O=!0,E&&clearInterval(E),S&&(clearTimeout(S),S=void 0,_=!1),T.close(),ZL.delete(u)},get socket(){return T},request({body:N,onError:L,onResponse:P}){v&&L&&L(v);let R=N.id??a6.take(),I=B=>{typeof B.id=="number"&&R!==B.id||(N.method==="eth_subscribe"&&typeof B.result=="string"&&x.set(B.result,{onResponse:P,onError:L,body:N}),P(B))};N.method==="eth_unsubscribe"&&x.delete(N.params?.[0]),w.set(R,{onResponse:I,onError:L});try{T.request({body:{jsonrpc:"2.0",id:R,...N}})}catch(B){L?.(B)}},async requestAsync({body:N,timeout:L=1e4}){let P=N.id??a6.take();try{return await sl(()=>new Promise((R,I)=>this.request({body:{...N,id:P},onError:I,onResponse:R})),{errorInstance:yce,timeout:L})}catch(R){throw R===yce?new ds({body:N,url:s}):R}finally{w.delete(P)}},requests:w,subscriptions:x,url:s},ZL.set(u,d),[d]}}),[h,[y]]=await p();return y}var ZL,yce,bce=b(()=>{l();fs();h3();Kb();KL();ZL=new Map,yce=new Error("timed out")});function xce(){if(typeof m<"u")return m;if(typeof global.WebSocket<"u")return global.WebSocket;if(typeof window.WebSocket<"u")return window.WebSocket;if(typeof self.WebSocket<"u")return self.WebSocket;throw new Error("`WebSocket` is not supported in this environment")}var vce=b(()=>{l()});var Ece={};Te(Ece,{WebSocket:()=>PLe});var PLe,Ace=b(()=>{l();vce();PLe=xce()});async function c6(e,t={}){let{keepAlive:r,reconnect:n}=t;return wce({async getSocket({onClose:o,onError:s,onOpen:i,onResponse:a}){let c=await Promise.resolve().then(()=>(Ace(),Ece)).then(h=>h.WebSocket),u=new c(e);function d(){u.removeEventListener("close",d),u.removeEventListener("message",f),u.removeEventListener("error",s),u.removeEventListener("open",i),o()}function f({data:h}){if(!(typeof h=="string"&&h.trim().length===0))try{let y=JSON.parse(h);a(y)}catch(y){s(y)}}u.addEventListener("close",d),u.addEventListener("message",f),u.addEventListener("error",s),u.addEventListener("open",i),u.readyState===c.CONNECTING&&await new Promise((h,y)=>{u&&(u.onopen=h,u.onerror=y)});let{close:p}=u;return Object.assign(u,{close(){p.bind(u)(),d()},ping(){try{if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new _g({url:u.url,cause:new su({url:u.url})});let h={jsonrpc:"2.0",id:null,method:"net_version",params:[]};u.send(JSON.stringify(h))}catch(h){s(h)}},request({body:h}){if(u.readyState===u.CLOSED||u.readyState===u.CLOSING)throw new _g({body:h,url:u.url,cause:new su({url:u.url})});return u.send(JSON.stringify(h))}})},keepAlive:r,reconnect:n,url:e})}var GL=b(()=>{l();fs();bce()});async function Cce(e){let t=await c6(e);return Object.assign(t.socket,{requests:t.requests,subscriptions:t.subscriptions})}var Sce=b(()=>{l();GL()});var bT,YL=b(()=>{l();bT=`Ethereum Signed Message: +`});function xT(e){let t=typeof e=="string"?ec(e):typeof e.raw=="string"?e.raw:yt(e.raw),r=ec(`${bT}${gt(t)}`);return en([r,t])}var JL=b(()=>{l();YL();Fn();Fo();qe()});function im(e,t){return Pt(xT(e),t)}var T3=b(()=>{l();Ks();JL()});var l6,u6,d6,Kg,QL=b(()=>{l();so();nt();l6=class extends G{constructor({domain:t}){super(`Invalid domain "${bt(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."],name:"InvalidDomainError"})}},u6=class extends G{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."],name:"InvalidPrimaryTypeError"})}},d6=class extends G{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:['Struct type must contain only letters, digits, "_", "$" and ":", and must not be a Solidity type.'],name:"InvalidStructTypeError"})}},Kg=class extends G{constructor({type:t}){let r=/^u?int(\[[0-9]*\])*$/.test(t);super(`Type "${t}" is not a valid EIP-712 type.`,{metaMessages:r?[`Use "${t.replace(/^(u?int)/,"$&256")}" instead.`]:void 0,name:"InvalidTypedDataTypeError"})}}});function vT(e){let{domain:t,message:r,primaryType:n,types:o}=e,s=(c,u)=>{let d={...u};for(let f of c){let{name:p,type:h}=f;h==="address"&&(d[p]=d[p].toLowerCase())}return d},i=o.EIP712Domain?t?s(o.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return s(o[n],r)})();return bt({domain:i,message:a,primaryType:n,types:o})}function f6(e){let{domain:t,message:r,primaryType:n,types:o}=e,s=(i,a)=>{for(let c of i){let{name:u,type:d}=c,f=a[u],p=d.match(Rf);if(p&&(typeof f=="number"||typeof f=="bigint")){let[y,w,x]=p;oe(f,{signed:w==="int",size:Number.parseInt(x,10)/8})}if(d==="address"&&typeof f=="string"&&!Ft(f))throw new br({address:f});let h=d.match(Eg);if(h){let[y,w]=h;if(w&>(f)!==Number.parseInt(w,10))throw new Lh({expectedSize:Number.parseInt(w,10),givenSize:gt(f)})}Object.hasOwn(o,d)&&s(o[d],f)}};for(let i of Object.keys(o))OLe(i);for(let i of Object.values(o))for(let a of i??[])NLe(a.type,o);if(o.EIP712Domain&&t){if(typeof t!="object")throw new l6({domain:t});s(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])s(o[n],r);else throw new u6({primaryType:n,types:o})}function Zg({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},typeof e?.version=="string"&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function Ice({domain:e}){return _3({domain:e,types:{EIP712Domain:Zg({domain:e})}})}function NLe(e,t){let r=e.replace(/(\[[0-9]*\])+$/,"");if(r==="int"||r==="uint")throw new Kg({type:e});if(!Object.hasOwn(t,r)&&!RLe(r))throw new Kg({type:e})}function RLe(e){return e==="address"||e==="bool"||e==="string"||Eg.test(e)||Rf.test(e)}function OLe(e){if(!/^[A-Za-z0-9_$:]+$/.test(e)||e==="address"||e==="bool"||e==="string"||/^(u?int|bytes)[0-9]*$/.test(e))throw new d6({type:e})}var ET=b(()=>{l();Qr();tc();QL();Gs();Fo();qe();P4();P3();so()});function p6(e){let{domain:t={},message:r,primaryType:n}=e,o={EIP712Domain:Zg({domain:t}),...e.types};f6({domain:t,message:r,primaryType:n,types:o});let s=["0x1901"];return t&&s.push(_3({domain:t,types:o})),n!=="EIP712Domain"&&s.push(AT({data:r,primaryType:n,types:o})),Pt(en(s))}function _3({domain:e,types:t}){return AT({data:e,primaryType:"EIP712Domain",types:t})}function AT({data:e,primaryType:t,types:r}){let n=Tce({data:e,primaryType:t,types:r});return Pt(n)}function Tce({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],o=[BLe({primaryType:t,types:r})];for(let s of r[t]){let[i,a]=Pce({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(i),o.push(a)}return oo(n,o)}function BLe({primaryType:e,types:t}){let r=wr(kLe({primaryType:e,types:t}));return Pt(r)}function kLe({primaryType:e,types:t}){let r="",n=_ce({primaryType:e,types:t});n.delete(e);let o=[e,...Array.from(n).sort()];for(let s of o)r+=`${s}(${t[s].map(({name:i,type:a})=>`${a} ${i}`).join(",")})`;return r}function _ce({primaryType:e,types:t},r=new Set){let n=e.replace(/(\[[0-9]*\])+$/,"");if(r.has(n)||t[n]===void 0)return r;r.add(n);for(let o of t[n])_ce({primaryType:o.type,types:t},r);return r}function Pce({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},Pt(Tce({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},Pt(n)];if(r==="string")return[{type:"bytes32"},Pt(wr(n))];if(r.lastIndexOf("]")===r.length-1){let o=r.slice(0,r.lastIndexOf("[")),s=n.map(i=>Pce({name:t,type:o,types:e,value:i}));return[{type:"bytes32"},Pt(oo(s.map(([i])=>i),s.map(([,i])=>i)))]}return[{type:r},n]}var P3=b(()=>{l();rc();Fn();qe();Ks();ET()});var CT,Nce,ST=b(()=>{l();CT="0x6492649264926492649264926492649264926492649264926492649264926492",Nce="0x0000000000000000000000000000000000000000000000000000000000000000"});function IT(e){return xa(e,-32)===CT}var XL=b(()=>{l();ST();Ii()});var N3,Rce=b(()=>{l();N3=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});var R3,eM=b(()=>{l();Rce();R3={checksum:new N3(8192),signatureHash:new N3(8192)}});var TT,Oce=b(()=>{l();eM();TT=R3.checksum});function Gg(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=CI(aL(e));return r==="Bytes"?n:vn(n)}var _T=b(()=>{l();JU();mu();io()});function Bce(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new PT({prefix:n,cause:new oM});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new PT({prefix:n,cause:new nM});return}throw new rM({publicKey:e})}function kce(e){let t=(()=>{if(q0(e))return Uce(e);if(oie(e))return DLe(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return Bce(t),t}function DLe(e){return Uce(vn(e))}function Uce(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new sM({publicKey:e});if(e.length===130){let n=BigInt(rn(e,0,32)),o=BigInt(rn(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(rn(e,0,1)),o=BigInt(rn(e,1,33)),s=BigInt(rn(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(rn(e,0,1)),r=BigInt(rn(e,1,33));return{prefix:t,x:r}}function iM(e,t={}){Bce(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return fn(s?Yt(r,{size:1}):"0x",Yt(n,{size:32}),typeof o=="bigint"?Yt(o,{size:32}):"0x")}var rM,PT,nM,oM,sM,aM=b(()=>{l();mu();ki();io();d3();rM=class extends Ke{constructor({publicKey:t}){super(`Value \`${z0(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},PT=class extends Ke{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},nM=class extends Ke{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},oM=class extends Ke{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},sM=class extends Ke{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Mr(Hb(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});function Yg(e,t={}){let{strict:r=!0}=t;if(!LLe.test(e))throw new h6({address:e,cause:new O3});if(r){if(e.toLowerCase()===e)return;if(NT(e)!==e)throw new h6({address:e,cause:new cM})}}function NT(e){if(TT.has(e))return TT.get(e);Yg(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=Gg(Mb(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return TT.set(e,o),o}function MLe(e,t={}){let{checksum:r=!1}=t;return Yg(e),r?NT(e):e}function Lce(e,t={}){let r=Gg(`0x${iM(e).slice(4)}`).substring(26);return MLe(`0x${r}`,t)}function lM(e,t={}){let{strict:r=!0}=t??{};try{return Yg(e,{strict:r}),!0}catch{return!1}}var LLe,h6,O3,cM,B3=b(()=>{l();mu();Oce();ki();_T();aM();LLe=/^0x[a-fA-F0-9]{40}$/;h6=class extends Ke{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},O3=class extends Ke{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},cM=class extends Ke{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});var Mce,Hce,OT,AOt,COt,SOt,IOt,TOt,_Ot,POt,NOt,ROt,OOt,BOt,kOt,UOt,DOt,LOt,MOt,HOt,$Ot,FOt,zOt,VOt,jOt,qOt,WOt,KOt,ZOt,GOt,YOt,JOt,QOt,XOt,eBt,tBt,rBt,nBt,oBt,sBt,iBt,aBt,cBt,lBt,uBt,dBt,fBt,pBt,hBt,mBt,gBt,yBt,wBt,bBt,xBt,vBt,EBt,ABt,CBt,SBt,IBt,TBt,_Bt,PBt,NBt,RBt,OBt,BBt,kBt,UBt,DBt,LBt,MBt,HBt,$Bt,FBt,zBt,VBt,jBt,qBt,WBt,KBt,ZBt,GBt,YBt,JBt,QBt,XBt,ekt,tkt,rkt,nkt,okt,skt,ikt,akt,ckt,lkt,uM,BT=b(()=>{l();Mce=/^(.*)\[([0-9]*)\]$/,Hce=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,OT=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,AOt=2n**(8n-1n)-1n,COt=2n**(16n-1n)-1n,SOt=2n**(24n-1n)-1n,IOt=2n**(32n-1n)-1n,TOt=2n**(40n-1n)-1n,_Ot=2n**(48n-1n)-1n,POt=2n**(56n-1n)-1n,NOt=2n**(64n-1n)-1n,ROt=2n**(72n-1n)-1n,OOt=2n**(80n-1n)-1n,BOt=2n**(88n-1n)-1n,kOt=2n**(96n-1n)-1n,UOt=2n**(104n-1n)-1n,DOt=2n**(112n-1n)-1n,LOt=2n**(120n-1n)-1n,MOt=2n**(128n-1n)-1n,HOt=2n**(136n-1n)-1n,$Ot=2n**(144n-1n)-1n,FOt=2n**(152n-1n)-1n,zOt=2n**(160n-1n)-1n,VOt=2n**(168n-1n)-1n,jOt=2n**(176n-1n)-1n,qOt=2n**(184n-1n)-1n,WOt=2n**(192n-1n)-1n,KOt=2n**(200n-1n)-1n,ZOt=2n**(208n-1n)-1n,GOt=2n**(216n-1n)-1n,YOt=2n**(224n-1n)-1n,JOt=2n**(232n-1n)-1n,QOt=2n**(240n-1n)-1n,XOt=2n**(248n-1n)-1n,eBt=2n**(256n-1n)-1n,tBt=-(2n**(8n-1n)),rBt=-(2n**(16n-1n)),nBt=-(2n**(24n-1n)),oBt=-(2n**(32n-1n)),sBt=-(2n**(40n-1n)),iBt=-(2n**(48n-1n)),aBt=-(2n**(56n-1n)),cBt=-(2n**(64n-1n)),lBt=-(2n**(72n-1n)),uBt=-(2n**(80n-1n)),dBt=-(2n**(88n-1n)),fBt=-(2n**(96n-1n)),pBt=-(2n**(104n-1n)),hBt=-(2n**(112n-1n)),mBt=-(2n**(120n-1n)),gBt=-(2n**(128n-1n)),yBt=-(2n**(136n-1n)),wBt=-(2n**(144n-1n)),bBt=-(2n**(152n-1n)),xBt=-(2n**(160n-1n)),vBt=-(2n**(168n-1n)),EBt=-(2n**(176n-1n)),ABt=-(2n**(184n-1n)),CBt=-(2n**(192n-1n)),SBt=-(2n**(200n-1n)),IBt=-(2n**(208n-1n)),TBt=-(2n**(216n-1n)),_Bt=-(2n**(224n-1n)),PBt=-(2n**(232n-1n)),NBt=-(2n**(240n-1n)),RBt=-(2n**(248n-1n)),OBt=-(2n**(256n-1n)),BBt=2n**8n-1n,kBt=2n**16n-1n,UBt=2n**24n-1n,DBt=2n**32n-1n,LBt=2n**40n-1n,MBt=2n**48n-1n,HBt=2n**56n-1n,$Bt=2n**64n-1n,FBt=2n**72n-1n,zBt=2n**80n-1n,VBt=2n**88n-1n,jBt=2n**96n-1n,qBt=2n**104n-1n,WBt=2n**112n-1n,KBt=2n**120n-1n,ZBt=2n**128n-1n,GBt=2n**136n-1n,YBt=2n**144n-1n,JBt=2n**152n-1n,QBt=2n**160n-1n,XBt=2n**168n-1n,ekt=2n**176n-1n,tkt=2n**184n-1n,rkt=2n**192n-1n,nkt=2n**200n-1n,okt=2n**208n-1n,skt=2n**216n-1n,ikt=2n**224n-1n,akt=2n**232n-1n,ckt=2n**240n-1n,lkt=2n**248n-1n,uM=2n**256n-1n});function Jg(e,t,r){let{checksumAddress:n,staticPosition:o}=r,s=Qg(t.type);if(s){let[i,a]=s;return $Le(e,{...t,type:a},{checksumAddress:n,length:i,staticPosition:o})}if(t.type==="tuple")return jLe(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return HLe(e,{checksum:n});if(t.type==="bool")return FLe(e);if(t.type.startsWith("bytes"))return zLe(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return VLe(e,t);if(t.type==="string")return qLe(e,{staticPosition:o});throw new g6(t.type)}function HLe(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);for(let s=0;s<12;s++)if(n[s]!==0)throw new h6({address:vn(n),cause:new O3});return[(s=>r?NT(s):s)(vn(tie(n,-20))),32]}function $Le(e,t,r){let{checksumAddress:n,length:o,staticPosition:s}=r;if(o===null){let c=Xf(e.readBytes(dM)),u=s+c,d=u+Fce;e.setPosition(u);let f=Xf(e.readBytes(Fce)),p=m6(t),h=0,y=[];for(let w=0;ws||o48?o:Number(o),32]}function jLe(e,t,r){let{checksumAddress:n,staticPosition:o}=r,s=t.components.length===0||t.components.some(({name:c})=>!c),i=s?[]:{},a=0;if(m6(t)){let c=Xf(e.readBytes(dM)),u=o+c;for(let d=0;d0?fn(u,c):u}}if(i)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:fn(...a.map(({encoded:c})=>c))}}function ZLe(e,{type:t}){let[,r]=t.split("bytes"),n=Mr(e);if(!r){let o=e;return n%32!==0&&(o=j0(o,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:fn(ep(Yt(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new k3({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:j0(e)}}function GLe(e){if(typeof e!="boolean")throw new Ke(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:ep(g9(e))}}function YLe(e,{signed:t,size:r}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||ei))}}function Qg(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function m6(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(m6);let r=Qg(e.type);return!!(r&&m6({...e,type:r[1]}))}var Fce,dM,pM=b(()=>{l();y6();B3();mu();ki();io();BT();Fce=32,dM=32});function MT(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(eMe);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var eMe,LT,hM,mM,gM=b(()=>{l();ki();eMe={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new mM({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new hM({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new LT({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new LT({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};LT=class extends Ke{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}},hM=class extends Ke{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}},mM=class extends Ke{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}});function Xg(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,s=typeof t=="string"?Lg(t):t,i=MT(s);if(uc(s)===0&&e.length>0)throw new bM;if(uc(s)&&uc(s)<32)throw new wM({data:typeof t=="string"?t:vn(t),parameters:e,size:uc(s)});let a=0,c=n==="Array"?[]:{};for(let u=0;u{l();fg();B3();mu();ki();io();pM();gM();BT();(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return Yg(c),ep(c.toLowerCase(),o?32:0)}if(r==="string")return $b(n);if(r==="bytes")return n;if(r==="bool")return ep(g9(n),o?32:1);let s=r.match(OT);if(s){let[c,u,d="256"]=s,f=Number.parseInt(d,10)/8;return Yt(n,{size:o?32:f,signed:u==="int"})}let i=r.match(Hce);if(i){let[c,u]=i;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new k3({expectedSize:Number.parseInt(u,10),value:n});return j0(n,o?32:0)}let a=r.match(Mce);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let f=0;fqce(t))):nMe(e)}function rMe(e){let t=e.reduce((o,s)=>o+s.length,0),r=Wce(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function nMe(e){let t=typeof e=="string"?Lg(e):e,r=Wce(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function Wce(e){if(e<=255)return 1;if(e<=65535)return 2;if(e<=16777215)return 3;if(e<=4294967295)return 4;throw new Ke("Length is too large.")}var Kce=b(()=>{l();mu();ki();io();gM()});function H3(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new L3({signature:e});if(typeof e.s>"u")throw new L3({signature:e});if(r&&typeof e.yParity>"u")throw new L3({signature:e});if(e.r<0n||e.r>uM)throw new vM({value:e.r});if(e.s<0n||e.s>uM)throw new EM({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new M3({value:e.yParity})}function sMe(e){return Zce(vn(e))}function Zce(e){if(e.length!==130&&e.length!==132)throw new xM({signature:e});let t=BigInt(rn(e,0,32)),r=BigInt(rn(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return IM(o)}catch{throw new M3({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function Gce(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return CM(e)}function CM(e){let t=typeof e=="string"?Zce(e):e instanceof Uint8Array?sMe(e):typeof e.r=="string"?SM(e):e.v?iMe(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return H3(t),t}function iMe(e){return{r:e.r,s:e.s,yParity:IM(e.v)}}function SM(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=IM(r)),typeof n!="number")throw new M3({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function IM(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new AM({value:e})}var xM,L3,vM,EM,M3,AM,TM=b(()=>{l();ki();io();d3();BT();xM=class extends Ke{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Mr(Hb(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},L3=class extends Ke{constructor({signature:t}){super(`Signature \`${z0(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},vM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},EM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},M3=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},AM=class extends Ke{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}});function Jce(e,t={}){return typeof e.chainId=="string"?aMe(e):{...e,...t.signature}}function aMe(e){let{address:t,chainId:r,nonce:n}=e,o=SM(e);return H3({r:o.r,s:o.s}),Xce(o.yParity),{address:t,chainId:Number(r),nonce:BigInt(n),...o}}function Qce(e){return cMe(e,{presign:!0})}function cMe(e,t={}){let{presign:r}=t;return Gg(fn("0x05",jce(lMe(r?{address:e.address,chainId:e.chainId,nonce:e.nonce}:e))))}function lMe(e){let{address:t,chainId:r,nonce:n,r:o,s,yParity:i}=e,a=Gce({r:o,s});return a&&typeof i<"u"&&Xce(i),[r?Yt(r):"0x",t,n?Yt(n):"0x",...a?[i?Yt(i,{size:1}):"0x",a.r===0n?"0x":y9(Yt(a.r)),a.s===0n?"0x":y9(Yt(a.s))]:[]]}function Xce(e){if(!(Number.isInteger(e)&&e>=0&&e<256))throw new V0({max:"255",min:"0",signed:!1,size:1,value:`${e}`})}var ele=b(()=>{l();_T();io();Kce();TM()});function tle(e){return Lce(dMe(e))}function dMe(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new ei.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Hb(t).substring(2));return kce(a)}var Ekt,rle=b(()=>{l();Bg();B3();mu();io();aM();Ekt=Mb("ox.secp256k1.fromSeed.v1")});var il={};Te(il,{InvalidWrappedSignatureError:()=>$T,assert:()=>FT,from:()=>pMe,magicBytes:()=>_M,suffixParameters:()=>PM,unwrap:()=>nle,validate:()=>mMe,wrap:()=>hMe});function FT(e){if(typeof e=="string"){if(rn(e,-32)!==_M)throw new $T(e)}else H3(e.authorization)}function pMe(e){return typeof e=="string"?nle(e):e}function nle(e){FT(e);let t=f9(rn(e,-64,-32)),r=rn(e,-t-64,-64),n=rn(e,0,-t-64),[o,s,i]=Xg(PM,r);return{authorization:Jce({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...i&&i!=="0x"?{data:i,to:s}:{}}}function hMe(e){let{data:t,signature:r}=e;FT(e);let n=tle({payload:Qce(e.authorization),signature:CM(e.authorization)}),o=am(PM,[{...e.authorization,delegation:e.authorization.address,chainId:BigInt(e.authorization.chainId)},e.to??n,t??"0x"]),s=Yt(Mr(o),{size:32});return fn(r,o,s,_M)}function mMe(e){try{return FT(e),!0}catch{return!1}}var _M,PM,$T,ole=b(()=>{l();y6();ele();ki();io();rle();TM();_M="0x8010801080108010801080108010801080108010801080108010801080108010",PM=D3("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");$T=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid ERC-8010 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}});var $3=b(()=>{l();ole()});function zT(e){return il.validate(e)}var NM=b(()=>{l();$3()});function sle(e){if(!IT(e))return{signature:e};let[t,r,n]=Ys([{type:"address"},{type:"bytes"},{type:"bytes"}],e);return{address:t,data:r,signature:n}}var ile=b(()=>{l();zh();XL()});function ale(e){if(!zT(e))return{signature:e};let{authorization:t,to:r,...n}=il.unwrap(e);return{authorization:{address:t.address,chainId:t.chainId,nonce:Number(t.nonce),r:oe(t.r,{size:32}),s:oe(t.s,{size:32}),yParity:t.yParity},...r?{address:r}:{},...n}}var cle=b(()=>{l();$3();qe();NM()});async function VT({message:e,signature:t}){return ti({hash:im(e),signature:t})}var RM=b(()=>{l();T3();w0()});async function jT(e){let{domain:t,message:r,primaryType:n,signature:o,types:s}=e;return ti({hash:p6({domain:t,message:r,primaryType:n,types:s}),signature:o})}var OM=b(()=>{l();P3();w0()});function lle(e){let{address:t,data:r,signature:n,to:o="hex"}=e,s=fr([oo([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),CT]);return o==="hex"?s:qt(s)}var ule=b(()=>{l();ST();rc();Fn();Pr()});function dle(e){let{address:t,data:r,signature:n,to:o="hex"}=e,s=il.wrap({authorization:{address:e.authorization.address,chainId:e.authorization.chainId,nonce:BigInt(e.authorization.nonce),r:BigInt(e.authorization.r),s:BigInt(e.authorization.s),yParity:e.authorization.yParity},data:r,signature:n,to:t});return o==="hex"?s:qt(s)}var fle=b(()=>{l();$3();Pr()});async function ple({address:e,hash:t,signature:r}){return xr(Gr(e),await ti({hash:t,signature:r}))}var hle=b(()=>{l();Zs();Bi();w0()});async function mle({address:e,message:t,signature:r}){return xr(Gr(e),await VT({message:t,signature:r}))}var gle=b(()=>{l();Zs();Bi();RM()});async function yle(e){let{address:t,domain:r,message:n,primaryType:o,signature:s,types:i}=e;return xr(Gr(t),await jT({domain:r,message:n,primaryType:o,signature:s,types:i}))}var wle=b(()=>{l();Zs();Bi();OM()});function qT(e){let t=xa(e,0,1);if(t==="0x04")return"eip7702";if(t==="0x03")return"eip4844";if(t==="0x02")return"eip1559";if(t==="0x01")return"eip2930";if(t!=="0x"&&wt(t)>=192)return"legacy";throw new ob({serializedType:t})}var BM=b(()=>{l();zn();Ii();Xr()});function WT(e){let t=qT(e);return t==="eip1559"?wMe(e):t==="eip2930"?bMe(e):t==="eip4844"?yMe(e):t==="eip7702"?gMe(e):xMe(e)}function gMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p,h,y]=t;if(t.length!==10&&t.length!==13)throw new ru({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:o,maxFeePerGas:s,gas:i,to:a,value:c,data:u,accessList:d,authorizationList:f,...t.length>9?{v:p,r:h,s:y}:{}},serializedTransaction:e,type:"eip7702"});let w={chainId:wt(r),type:"eip7702"};return We(a)&&a!=="0x"&&(w.to=a),We(i)&&i!=="0x"&&(w.gas=dt(i)),We(u)&&u!=="0x"&&(w.data=u),We(n)&&(w.nonce=n==="0x"?0:wt(n)),We(c)&&c!=="0x"&&(w.value=dt(c)),We(o)&&o!=="0x"&&(w.maxPriorityFeePerGas=dt(o)),We(s)&&(s!=="0x"||w.maxPriorityFeePerGas)&&(w.maxFeePerGas=s==="0x"?0n:dt(s)),d.length!==0&&d!=="0x"&&(w.accessList=ZT(d)),f.length!==0&&f!=="0x"&&(w.authorizationList=vMe(f)),lT(w),{...t.length===13?F3(t):void 0,...w}}function yMe(e){let t=KT(e),r=t.length===4,n=r?t[0]:t,o=r?t.slice(1):[],[s,i,a,c,u,d,f,p,h,y,w,x,v,T]=n,[E,S,_]=o;if(!(n.length===11||n.length===14))throw new ru({attributes:{chainId:s,nonce:i,maxPriorityFeePerGas:a,maxFeePerGas:c,gas:u,to:d,value:f,data:p,accessList:h,...n.length>9?{v:x,r:v,s:T}:{}},serializedTransaction:e,type:"eip4844"});let O={blobVersionedHashes:w,chainId:wt(s),to:d,type:"eip4844"};return We(u)&&u!=="0x"&&(O.gas=dt(u)),We(p)&&p!=="0x"&&(O.data=p),We(i)&&(O.nonce=i==="0x"?0:wt(i)),We(f)&&f!=="0x"&&(O.value=dt(f)),We(y)&&y!=="0x"&&(O.maxFeePerBlobGas=dt(y)),We(a)&&a!=="0x"&&(O.maxPriorityFeePerGas=dt(a)),We(c)&&(c!=="0x"||O.maxPriorityFeePerGas)&&(O.maxFeePerGas=c==="0x"?0n:dt(c)),h.length!==0&&h!=="0x"&&(O.accessList=ZT(h)),E&&S&&_&&(O.sidecars=M0({blobs:E,commitments:S,proofs:_})),uT(O),{...n.length===14?F3(n):void 0,...O}}function wMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p,h]=t;if(!(t.length===9||t.length===12))throw new ru({attributes:{chainId:r,nonce:n,maxPriorityFeePerGas:o,maxFeePerGas:s,gas:i,to:a,value:c,data:u,accessList:d,...t.length>9?{v:f,r:p,s:h}:{}},serializedTransaction:e,type:"eip1559"});let y={chainId:wt(r),type:"eip1559"};return We(a)&&a!=="0x"&&(y.to=a),We(i)&&i!=="0x"&&(y.gas=dt(i)),We(u)&&u!=="0x"&&(y.data=u),We(n)&&(y.nonce=n==="0x"?0:wt(n)),We(c)&&c!=="0x"&&(y.value=dt(c)),We(o)&&o!=="0x"&&(y.maxPriorityFeePerGas=dt(o)),We(s)&&(s!=="0x"||y.maxPriorityFeePerGas)&&(y.maxFeePerGas=s==="0x"?0n:dt(s)),d.length!==0&&d!=="0x"&&(y.accessList=ZT(d)),sm(y),{...t.length===12?F3(t):void 0,...y}}function bMe(e){let t=KT(e),[r,n,o,s,i,a,c,u,d,f,p]=t;if(!(t.length===8||t.length===11))throw new ru({attributes:{chainId:r,nonce:n,gasPrice:o,gas:s,to:i,value:a,data:c,accessList:u,...t.length>8?{v:d,r:f,s:p}:{}},serializedTransaction:e,type:"eip2930"});let h={chainId:wt(r),type:"eip2930"};return We(i)&&i!=="0x"&&(h.to=i),We(s)&&s!=="0x"&&(h.gas=dt(s)),We(c)&&c!=="0x"&&(h.data=c),We(n)&&(h.nonce=n==="0x"?0:wt(n)),We(a)&&a!=="0x"&&(h.value=dt(a)),We(o)&&o!=="0x"&&(h.gasPrice=dt(o)),u.length!==0&&u!=="0x"&&(h.accessList=ZT(u)),n6(h),{...t.length===11?F3(t):void 0,...h}}function xMe(e){let t=Wg(e,"hex"),[r,n,o,s,i,a,c,u,d]=t;if(!(t.length===6||t.length===9))throw new ru({attributes:{nonce:r,gasPrice:n,gas:o,to:s,value:i,data:a,...t.length>6?{v:c,r:u,s:d}:{}},serializedTransaction:e,type:"legacy"});let f={type:"legacy"};if(We(s)&&s!=="0x"&&(f.to=s),We(o)&&o!=="0x"&&(f.gas=dt(o)),We(a)&&a!=="0x"&&(f.data=a),We(r)&&(f.nonce=r==="0x"?0:wt(r)),We(i)&&i!=="0x"&&(f.value=dt(i)),We(n)&&n!=="0x"&&(f.gasPrice=dt(n)),o6(f),t.length===6)return f;let p=We(c)&&c!=="0x"?dt(c):0n;if(d==="0x"&&u==="0x")return p>0&&(f.chainId=Number(p)),f;let h=p,y=Number((h-35n)/2n);if(y>0)f.chainId=y;else if(h!==27n&&h!==28n)throw new Kh({v:h});return f.v=h,f.s=d,f.r=u,f.yParity=h%2n===0n?1:0,f}function KT(e){return Wg(`0x${e.slice(4)}`,"hex")}function ZT(e){let t=[];for(let r=0;ri6(s)?s:bn(s))})}return t}function vMe(e){let t=[];for(let r=0;r1n&&u<256n?{r:cs(a,{size:32}),s:cs(c,{size:32}),yParity:Number(u)}:F3([i,a,c]);t.push({address:o,chainId:n==="0x"?0:wt(n),nonce:s==="0x"?0:wt(s),...d})}return t}function F3(e){let t=e.slice(-3),r=t[0]==="0x"?0n:dt(t[0]);if(r!==0n&&r!==1n)throw new tu({yParity:r});let n=r===0n?27n:28n;return{r:cs(t[1],{size:32}),s:cs(t[2],{size:32}),v:n,yParity:n===27n?0:1}}var kM=b(()=>{l();tc();zn();Gs();n3();qs();Xa();Hh();Xr();mT();gT();dT();BM()});function pc(e,t){return NI(e,t)}var z3=b(()=>{l();Sg()});function ble(e,t="wei"){return Kre(e,t)}var xle=b(()=>{l();Sg()});function vle(e,t="wei"){return Zre(e,t)}var Ele=b(()=>{l();Sg()});function GT(e,t){return RI(e,t)}var UM=b(()=>{l();Sg()});var DM=b(()=>{l();us();Xr()});function EMe(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function Ale(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?wt(e.nonce):void 0,storageProof:e.storageProof?EMe(e.storageProof):void 0}}var Cle=b(()=>{l();DM()});async function Sle(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s,storageKeys:i}){let a=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s}),c=await e.request({method:"eth_getProof",params:[t,i,a]});return Ale(c)}var Ile=b(()=>{l();B0();Cle()});async function Tle(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new Gc({hash:t});return r}var _le=b(()=>{l();zn()});async function Ple(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:s,slot:i}){let a=ni({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:s});return await e.request({method:"eth_getStorageAt",params:[t,i,a]})}var Nle=b(()=>{l();B0()});async function Rle(e,{blockHash:t,blockNumber:r,blockTag:n="latest",requireCanonical:o,requests:s}){let i=ni({blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o});return e.request({method:"eth_getStorageValues",params:[s,i]})}var Ole=b(()=>{l();B0()});async function cm(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:s,sender:i,nonce:a}){let c=n||"latest",u=r!==void 0?oe(r):void 0,d=null;if(o?d=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0}):t?d=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,oe(s)]},{dedupe:!0}):(u||c)&&typeof s=="number"?d=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[u||c,oe(s)]},{dedupe:!!u}):i&&typeof a=="number"&&(d=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[i,oe(a)]},{dedupe:!0})),!d)throw new Gc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:s});return(e.chain?.formatters?.transaction?.format||jf)(d,"getTransaction")}var YT=b(()=>{l();zn();qe();Ab()});async function Ble(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([ue(e,Ta,"getBlockNumber")({}),t?ue(e,cm,"getTransaction")({hash:t}):void 0]),s=r?.blockNumber||o?.blockNumber;if(!s)return 0n;let i=n{l();_t();zg();YT()});async function lm(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new nu({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||op)(r,"getTransactionReceipt")}var LM=b(()=>{l();zn();Qb()});async function Ule(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,requireCanonical:u,stateOverride:d}=t,f=t.contracts,p=typeof e.batch?.multicall=="object"?e.batch.multicall:{},h=t.batchSize??p.batchSize??1024,y=t.deployless??p.deployless??!1,w=(()=>{if(t.multicallAddress)return t.multicallAddress;if(y)return null;if(e.chain)return Di({blockNumber:i,chain:e.chain,contract:"multicall3"});throw new Error("client chain not configured. multicallAddress is required.")})(),x=[[]],v=0,T=0;for(let D=0;D0&&T>h&&x[v].length>0&&(v++,T=(R.length-2)/2,x[v]=[]),x[v]=[...x[v],{allowFailure:!0,callData:R,target:N}]}catch(R){let I=Js(R,{abi:M,address:N,args:L,docsPath:"/docs/contract/multicall",functionName:P,sender:r});if(!o)throw I;x[v]=[...x[v],{allowFailure:!0,callData:"0x",target:N}]}}let E=!!e.batch?.multicall,S=E?x.flatMap(D=>D.map(M=>[M])):x,_=await Promise.allSettled(S.map(D=>E?AMe(e,{account:r,authorizationList:n,batchSize:h,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,call:D[0],multicallAddress:w,requireCanonical:u,stateOverride:d}).then(M=>[M]):ue(e,er,"readContract")({...w===null?{code:Mg}:{address:w},abi:Ui,account:r,args:[D],authorizationList:n,blockHash:s,blockNumber:i,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:u,stateOverride:d}))),O=[];for(let D=0;D<_.length;D++){let M=_[D];if(M.status==="rejected"){if(!o)throw M.reason;for(let L=0;Lf+(p.length-2)/2,0)>r},fn:u=>ue(e,er,"readContract")({...o===null?{code:Mg}:{address:o},...s,abi:Ui,args:[u],functionName:"aggregate3"})}),[c]=await a(n);return c}var Dle=b(()=>{l();So();Vb();Qr();nt();ou();lc();us();K0();p0();_t();h3();so();oi()});async function w6(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:s,traceTransfers:i,validation:a}=t;try{let c=[];for(let p of o){let h=p.blockOverrides?w9(p.blockOverrides):void 0,y=p.calls.map(x=>{let v=x,T=v.account?ft(v.account):void 0,E=v.abi?Wt(v):v.data,S={...v,account:T,data:v.dataSuffix?en([E||"0x",v.dataSuffix]):E,from:v.from??T?.address};return jn(S),Bn(S)}),w=p.stateOverrides?xb(p.stateOverrides):void 0;c.push({blockOverrides:h,calls:y,stateOverrides:w})}let d=(typeof r=="bigint"?oe(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:i,validation:a},d]})).map((p,h)=>({...qf(p),calls:p.calls.map((y,w)=>{let{abi:x,args:v,functionName:T,to:E}=o[h].calls[w],S=y.error?.data??y.returnData,_=BigInt(y.gasUsed),O=y.maxUsedGas===void 0?void 0:BigInt(y.maxUsedGas),D=y.logs?.map(P=>qn(P)),M=y.status==="0x1"?"success":"failure",N=x&&M==="success"&&S!=="0x"?dn({abi:x,data:S,functionName:T}):null,L=(()=>{if(M==="success")return;let P;if(S==="0x"?P=new Si:S&&(P=new sc({data:S})),!!P)return Js(P,{abi:x??[],address:E??"0x",args:v,functionName:T??""})})();return{data:S,gasUsed:_,logs:D,...O===void 0?{}:{maxUsedGas:O},status:M,...M==="success"?{result:N}:{error:L}}})}))}catch(c){let u=c,d=_0(u,{});throw d instanceof Ri?u:d}}var MM=b(()=>{l();uL();tn();Qr();ou();tl();lc();us();Fn();qe();p0();G4();X4();hu();rl();VI();nl()});function XT(e){let t=!0,r="",n=0,o="",s=!1;for(let i=0;ir==="object"&&JT(Lle(e,i,a),i));let o=CMe.exec(n);if(o){if(typeof e!="bigint"&&typeof e!="number"||typeof e=="number"&&!Number.isInteger(e))return!1;let i=n.startsWith("int"),a=Number.parseInt(o[1]??"256",10),c=2n**(BigInt(a)-(i?1n:0n))-1n,u=i?-c-1n:0n;return e>=u&&e<=c}if(SMe.test(n)){if(typeof e!="string"&&!(e instanceof Uint8Array))return!1;let i=n.slice(5);return i?e instanceof Uint8Array?e.length===Number.parseInt(i,10):q0(e)?Mr(e)===Number.parseInt(i,10):!1:e instanceof Uint8Array||q0(e)}let s=Qg(n);if(s){let[i,a]=s;return Array.isArray(e)&&(i===null||e.length===i)&&e.every(c=>JT(c,{...t,type:a}))}return!1}}}function QT(e,t,r){for(let n in e){let o=e[n],s=t[n];if(!s)continue;if(o.type==="tuple"&&s.type==="tuple"&&"components"in o&&"components"in s){let f=r[n],p=QT(o.components,s.components,o.components.map((h,y)=>Lle(f,h,y)));if(p)return p;continue}let i=Qg(o.type),a=Qg(s.type);if(i&&a){let f=QT([{...o,type:i[1]}],[{...s,type:a[1]}],[r[n]?.[0]]);if(f)return f;if(i[1]===a[1]&&o.type!==s.type)return[o.type,s.type];continue}let c=[o.type,s.type],u=r[n];if(c.includes("address")&&(c.includes("string")||c.includes("bytes"))?u===void 0||lM(u,{strict:!1}):o.type!==s.type)return c}}function Lle(e,t,r){return Array.isArray(e)?e[r]:e?.[t.name]}var CMe,SMe,Mle=b(()=>{l();B3();ki();io();pM();CMe=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,SMe=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/});function b6(e,t={}){let{prepare:r=!0}=t,n=Array.isArray(e)?Tw(e):typeof e=="string"?Tw(e):e;return{...n,...r?{hash:ey(n)}:{}}}function x6(e,t,r){let{args:n=[],prepare:o=!0}=r??{},s=q0(t,{strict:!1}),i=e.filter(d=>s?d.type==="function"||d.type==="error"?$M(d)===rn(t,0,4):d.type==="event"?ey(d)===t:!1:"name"in d&&d.name===t);if(i.length===0)throw new sp({name:t});if(i.length===1)return{...i[0],...o?{hash:ey(i[0])}:{}};let a,c;for(let d of i){if(!("inputs"in d))continue;if(!n||n.length===0){!c&&(!d.inputs||d.inputs.length===0)&&(c=d);continue}if(!d.inputs||d.inputs.length===0||d.inputs.length!==n.length)continue;if(n.every((p,h)=>{let y="inputs"in d&&d.inputs[h];return y?JT(p,y):!1})){if(a&&"inputs"in a&&a.inputs){let p=QT(d.inputs,a.inputs,n);if(p)throw new HM({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let u=(()=>{if(a)return a;let d=c??i[0],f=i.filter(p=>p!==d);return{...d,overloads:f}})();if(!u)throw new sp({name:t});return{...u,...o?{hash:ey(u)}:{}}}function $M(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return x6(r,n)}return e[0]})();return rn(ey(t),0,4)}function TMe(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return x6(n,o)}return e[0]})(),r=typeof t=="string"?t:Af(t);return XT(r)}function ey(...e){let t=(()=>{if(Array.isArray(e[0])){let[s,i]=e;return x6(s,i)}return e[0]})();if(typeof t!="string"&&"hash"in t&&t.hash)return t.hash;let r=TMe(t),n=R3.signatureHash.get(r);if(n)return n;let o=Gg($b(r));return R3.signatureHash.set(r,o),o}var HM,sp,e_=b(()=>{l();fg();ki();_T();io();Mle();eM();HM=class extends Ke{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${XT(Af(t.abiItem))}\`, and`,`\`${r.type}\` in \`${XT(Af(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}},sp=class extends Ke{constructor({name:t,data:r,type:n="item"}){let o=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${o} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}});function Hle(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[s,i]=e;return[_Me(s),i]}return e})(),{bytecode:n,args:o}=r;return fn(n,t.inputs?.length&&o?.length?am(t.inputs,o):"0x")}function $le(e){return b6(e)}function _Me(e){let t=e.find(r=>r.type==="constructor");if(!t)throw new sp({name:"constructor"});return t}var Fle=b(()=>{l();e_();y6();io()});function zle(e,t={}){return b6(e,t)}function Vle(e){return ey(e)}var jle=b(()=>{l();e_()});function qle(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[s,i,a,c]=e;return[zM(s,i),a,c]}return e})(),o=Xg(t.outputs,r,n);if(!(o&&Object.keys(o).length===0))return o&&Object.keys(o).length===1?Array.isArray(o)?o[0]:Object.values(o)[0]:o}function um(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[u,d,f]=e;return[zM(u,d,{args:f}),f]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?zM([t,...n],t.name,{args:r}):t,s=RMe(o),i=r.length>0?am(o.inputs,r):void 0;return i?fn(s,i):s}function ty(e,t={}){return b6(e,t)}function zM(e,t,r){let n=x6(e,t,r);if(n.type!=="function")throw new sp({name:t,type:"function"});return n}function RMe(e){return $M(e)}var Wle=b(()=>{l();e_();y6();io()});var v6,dm,t_=b(()=>{l();v6="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",dm="0x0000000000000000000000000000000000000000"});async function eue(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:s,traceAssetChanges:i,traceTransfers:a,validation:c}=t,u=t.account?ft(t.account):void 0;if(i&&!u)throw new G("`account` is required when `traceAssetChanges` is true");let d=u?Hle($le("constructor(bytes, bytes)"),{bytecode:zb,args:[BMe,um(ty("function getBalance(address)"),[u.address])]}):void 0,f=n??e.experimental_blockTag??"latest",p=r;if(i&&typeof p!="bigint"&&f!=="earliest"&&f!=="pending")if(f==="latest")p=await Ta(e,{cacheTime:0});else{let W=await xn(e,{blockTag:f});if(typeof W.number!="bigint")throw new G(`Block tag \`${f}\` did not resolve to a number.`);p=W.number}let h=typeof p=="bigint"?{blockNumber:p}:{blockTag:f},y=i?await w6(e,{...h,blocks:[{calls:o.map(W=>({...W,from:u.address})),stateOverrides:s}],traceTransfers:a,validation:c}):void 0,w=y?[...new Set([...LMe(y[0].calls.flatMap(W=>W.logs??[]),u.address),...t.calls.map(W=>W.to?.toLowerCase())])].filter(W=>!!W&&W!==v6&&W!==dm):[],x=MMe([...u?[u.address]:[],...w,...s?.map(({address:W})=>W)??[]]),v=[{address:x,code:Xle}],[T,E]=await Promise.all([i?Promise.all([Qle(e,{account:u.address,...h,data:d,stateOverride:s}),...w.map(W=>Qle(e,{account:u.address,address:W,...h,data:um(Kle,[u.address]),staticCallAddress:x,stateOverride:s}))]):[],w6(e,{...h,blocks:[{calls:[...o,{to:dm}].map(W=>({...W,from:u?.address})),stateOverrides:s},...i?[{calls:[{data:d}]},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Kle,[u.address]))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Zle))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Gle,[0n]))})),stateOverrides:v},{calls:w.map(W=>({to:x,gas:V3,data:j3(W,um(Yle))})),stateOverrides:v}]:[]],traceTransfers:a,validation:c})]),S=E[0],[_,O,D,M,N]=i?E.slice(1):[],{calls:L,...P}=S,R=L.slice(0,-1),I=T.map(W=>Jle(W)?dt(W.data):null),B=_?.calls??[],C=O?.calls??[],U=[...B,...C].map(W=>Jle(W)?dt(W.data):null),H=(D?.calls??[]).map(W=>VM(W,Zle)),k=(N?.calls??[]).map(W=>VM(W,Yle)),F=(M?.calls??[]).map(W=>VM(W,Gle)),j=[];for(let[W,ae]of U.entries()){let te=I[W],X=T[W],pe=typeof te=="bigint"?te:W>0&&X?.status==="success"&&X.data==="0x"?0n:null;if(typeof ae!="bigint"||typeof pe!="bigint")continue;let me=H[W-1],Ne=k[W-1],ye=F[W-1],Re=W===0?{address:v6,decimals:18,symbol:"ETH"}:{address:w[W-1],decimals:ye||me?Number(me??1):void 0,symbol:Ne??void 0};j.push({token:Re,value:{pre:pe,post:ae,diff:ae-pe}})}return{assetChanges:j,block:P,results:R}}function j3(e,t){return um(DMe,[e,t])}function LMe(e,t){let r=Zr(t.toLowerCase(),{size:32});return e.filter(n=>n.topics[0]?.toLowerCase()!==UMe||n.address.toLowerCase()===v6?!1:n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r).map(n=>n.address.toLowerCase())}function Jle(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function VM(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return qle(t,e.data)}catch{return null}}async function Qle(e,t){let{account:r,address:n,blockNumber:o,blockTag:s,data:i,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await ms({...e,ccipRead:!1},{account:n?dm:r,data:n?j3(n,i):i,stateOverride:n&&a?[...c??[],{address:a,code:Xle}]:c,...n?{gas:V3,to:a}:{},...typeof o=="bigint"?{blockNumber:o}:{blockTag:s}})).data??"0x",status:"success"}}catch(u){if(!(u instanceof Yc)||!(u.cause instanceof ri))throw u;return{data:"0x",status:"failure"}}}function MMe(e){let t=new Set(e.map(n=>n.toLowerCase())),r=kMe;for(;t.has(`0x${r.toString(16).padStart(40,"0")}`);)r++;return`0x${r.toString(16).padStart(40,"0")}`}var BMe,Xle,V3,kMe,UMe,Kle,Zle,Gle,Yle,DMe,tue=b(()=>{l();Fle();jle();Wle();tn();t_();Vb();nt();ou();tl();Xa();Xr();G0();fu();zg();MM();BMe="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",Xle="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",V3=1000000n,kMe=0x00000000000000000000000000000000deadbeefn,UMe=Vle(zle("event Transfer(address indexed from, address indexed to, uint256 value)")),Kle=ty("function balanceOf(address) returns (uint256)"),Zle=ty("function decimals() returns (uint256)"),Gle=ty("function tokenURI(uint256) returns (string)"),Yle=ty("function symbol() returns (string)"),DMe=ty("function query(address target, bytes data)")});var q3={};Te(q3,{InvalidWrappedSignatureError:()=>r_,assert:()=>qM,from:()=>FMe,magicBytes:()=>jM,universalSignatureValidatorAbi:()=>$Me,universalSignatureValidatorBytecode:()=>HMe,unwrap:()=>rue,validate:()=>VMe,wrap:()=>zMe});function qM(e){if(rn(e,-32)!==jM)throw new r_(e)}function FMe(e){return typeof e=="string"?rue(e):e}function rue(e){qM(e);let[t,r,n]=Xg(D3("address, bytes, bytes"),e);return{data:r,signature:n,to:t}}function zMe(e){let{data:t,signature:r,to:n}=e;return fn(am(D3("address, bytes, bytes"),[n,t,r]),jM)}function VMe(e){try{return qM(e),!0}catch{return!1}}var jM,HMe,$Me,r_,nue=b(()=>{l();y6();ki();io();jM="0x6492649264926492649264926492649264926492649264926492649264926492",HMe="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572",$Me=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}];r_=class extends Ke{constructor(t){super(`Value \`${t}\` is an invalid ERC-6492 wrapped signature.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}});var oue=b(()=>{l();nue()});function W3({r:e,s:t,to:r="hex",v:n,yParity:o}){let s=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),i=`0x${new ei.Signature(dt(e),dt(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?i:qt(i)}var WM=b(()=>{l();Bg();Xr();Pr()});async function fm(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:s=t.universalSignatureVerifierAddress??(()=>{let{blockNumber:u}=t,d=n?.contracts?.erc6492Verifier;if(!(u!==void 0&&d?.blockCreated&&d.blockCreated>u))return d?.address})(),multicallAddress:i=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(r===dm)return!1;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let u=t.signature;return We(u)?u:typeof u=="object"&&"r"in u&&"s"in u?W3(u):yt(u)})();try{if(a==="eoa")try{if(xr(Gr(r),await ti({hash:o,signature:c})))return!0}catch{}return il.validate(c)?await jMe(e,{...t,multicallAddress:i,signature:c}):await qMe(e,{...t,verifierAddress:s,signature:c})}catch(u){if(a!=="eoa")try{if(xr(Gr(r),await ti({hash:o,signature:c})))return!0}catch{}if(u instanceof vu)return!1;throw u}}async function jMe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:s,hash:i,multicallAddress:a,requireCanonical:c}=t,{authorization:u,data:d,signature:f,to:p}=il.unwrap(t.signature);if(await jg(e,{address:r,blockHash:n,blockNumber:o,blockTag:s,requireCanonical:c})===fr(["0xef0100",u.address]))return await WMe(e,{...t,signature:f});let y={address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce),r:oe(u.r,{size:32}),s:oe(u.s,{size:32}),yParity:u.yParity};if(!await Oae({address:r,authorization:y}))throw new vu;let{data:x}=await ms({...e,ccipRead:!1},{...a?{to:a}:{code:Mg},authorizationList:[y],blockHash:n,blockNumber:o,blockTag:s??"pending",data:Wt({abi:Ui,functionName:"aggregate3",args:[[...d?[{allowFailure:!0,target:p??r,callData:d}]:[],{allowFailure:!0,target:r,callData:Wt({abi:x9,functionName:"isValidSignature",args:[i,f]})}]]}),requireCanonical:c}),v=dn({abi:Ui,functionName:"aggregate3",data:x??"0x"}),T=v[v.length-1];if(T?.success&&T.returnData.startsWith("0x1626ba7e"))return!0;throw new vu}async function qMe(e,t){let{address:r,factory:n,factoryData:o,hash:s,signature:i,verifierAddress:a,...c}=t,u=await(async()=>!n&&!o||q3.validate(i)?i:q3.wrap({data:o,signature:i,to:n}))(),d=a?{batch:!1,to:a,data:Wt({abi:Fb,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:tp({abi:Fb,args:[r,s,u],bytecode:f3}),...c},{data:f}=await ms({...e,ccipRead:!1},d).catch(p=>{throw p instanceof Yc?new vu:p});if(qw(f??"0x0"))return!0;throw new vu}async function WMe(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:s,hash:i,requireCanonical:a,signature:c}=t,{data:u}=await ms({...e,ccipRead:!1},{batch:!1,blockHash:n,blockNumber:o,blockTag:s,data:Wt({abi:x9,functionName:"isValidSignature",args:[i,c]}),requireCanonical:a,to:r}).catch(f=>{throw f instanceof Yc?new vu:f});if((()=>{try{return dn({abi:x9,functionName:"isValidSignature",data:u??"0x"})}catch{throw new vu}})().startsWith("0x1626ba7e"))return!0;throw new vu}var vu,K3=b(()=>{l();oue();$3();So();t_();Vb();ou();lc();p3();us();Zs();Bi();Bae();Fn();qs();Xr();qe();w0();WM();G0();aT();vu=class extends Error{}});async function sue(e,{address:t,message:r,factory:n,factoryData:o,signature:s,...i}){let a=im(r);return ue(e,fm,"verifyHash")({address:t,factory:n,factoryData:o,hash:a,signature:s,...i})}var iue=b(()=>{l();_t();T3();K3()});async function aue(e,t){let{address:r,factory:n,factoryData:o,signature:s,message:i,primaryType:a,types:c,domain:u,...d}=t,f=p6({message:i,primaryType:a,types:c,domain:u});return ue(e,fm,"verifyHash")({address:r,factory:n,factoryData:o,hash:f,signature:s,...d})}var cue=b(()=>{l();_t();P3();K3()});function n_(e,{emitOnBegin:t=!1,emitMissed:r,onBlockNumber:n,onError:o,poll:s,pollingInterval:i=e.pollingInterval}){let a=typeof s<"u"?s:Q0(e),c=e.chain?.blockTime,u=r??(c!==void 0&&i>c/2),d;return a?(()=>{let h=bt(["watchBlockNumber",e.uid,t,u,i]);return Io(h,{onBlockNumber:n,onError:o},y=>dc(async()=>{try{let w=await ue(e,Ta,"getBlockNumber")({cacheTime:0});if(d!==void 0){if(w===d)return;if(w-d>1&&u)for(let x=d+1n;xd)&&(y.onBlockNumber(w,d),d=w)}catch(w){y.onError?.(w)}},{emitOnBegin:t,interval:i}))})():(()=>{let h=bt(["watchBlockNumber",e.uid,t,u]);return Io(h,{onBlockNumber:n,onError:o},y=>{let w=!0,x=()=>w=!1;return(async()=>{try{let v=gu(e),{unsubscribe:T}=await v.subscribe({params:["newHeads"],onData(E){if(!w)return;let S=dt(E.result?.number);y.onBlockNumber(S,d),d=S},onError(E){y.onError?.(E)}});x=T,w||x()}catch(v){o?.(v)}})(),()=>x()})})()}var KM=b(()=>{l();Xr();_t();rp();Fg();so();zg();Zb()});async function Z3(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:s,retryCount:i=6,retryDelay:a=({count:L})=>~~(1<e.chain?.transactionReplacement?.getKey?.(L)??String(L.nonce),p=t.pollingInterval?t.pollingInterval:e.chain?.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval,h=bt(["waitForTransactionReceipt",e.uid,o,{checkReplacement:r,confirmations:n,pollingInterval:p,replacement:d,retryCount:i,signal:c?rm():void 0,timeout:u}]),y,w,x,v=!1,T,E,S,{promise:_,resolve:O,reject:D}=jb(),M=u?setTimeout(()=>{S?.(),E?.(),T=void 0,D(new Gh({hash:o}))},u):void 0,N=()=>{clearTimeout(M),S?.(),E?.(),D(Nn(c))};return c?.addEventListener("abort",N,{once:!0}),E=Io(h,{onReplaced:s,resolve:O,reject:D},async L=>{if(w=await ue(e,lm,"getTransactionReceipt")({hash:o}).catch(()=>{}),c?.aborted)return;if(w&&n<=1){clearTimeout(M),L.resolve(w),E?.();return}let P=async R=>{let I=C=>{T=void 0,clearTimeout(M),S?.(),C(),E?.()},B=R;try{if(w){if(n>1&&(!w.blockNumber||B-w.blockNumber+1nU instanceof nu?null:void 0);if(C===void 0)return;if(!C){w=void 0,x||(y=void 0),x=void 0;return}if(w=C,n>1&&(!C.blockNumber||B-C.blockNumber+1n{A&&L.onReplaced?.(A),L.resolve(C)});return}if(r&&!y&&(v=!0,await np(async()=>{y=await ue(e,cm,"getTransaction")({hash:o}),y.blockNumber&&(B=y.blockNumber)},{delay:a,retryCount:i,signal:c,shouldRetry:({error:C})=>!(d&&C instanceof Gc)}),v=!1),w=await ue(e,lm,"getTransactionReceipt")({hash:o}),n>1&&(!w.blockNumber||B-w.blockNumber+1nL.resolve(w))}catch(C){if(C instanceof Gc||C instanceof nu){v=!1;let A=y??(r&&d?{...d,hash:o.toLowerCase()}:void 0);if(!A||A.blockNumber)return;try{if(!y){v=!0;let F=await ue(e,cm,"getTransaction")({nonce:A.nonce,sender:A.from}).catch(j=>{(j instanceof Jc||j instanceof Aa)&&(y=A)});if(v=!1,F?.hash.toLowerCase()===A.hash){y=F;return}if(F){let j=await ue(e,lm,"getTransactionReceipt")({hash:F.hash}).catch(W=>{if(!(W instanceof nu))throw W});if(!j||(w=j,x={reason:e.chain?.transactionReplacement?.getReason?.({replaced:A,replacement:F})??lue(A,F),replacedTransaction:A,transaction:F,transactionReceipt:w},n>1&&(!w.blockNumber||B-w.blockNumber+1n{L.onReplaced?.(x),L.resolve(w)});return}}v=!0;let U=await np(()=>ue(e,xn,"getBlock")({blockNumber:B,includeTransactions:!0}),{delay:a,retryCount:i,signal:c,shouldRetry:({error:F})=>F instanceof du});v=!1;let H=f(A),k=U.transactions.find(F=>xr(F.from,A.from)&&F.hash!==A.hash&&f(F)===H);if(!k||(w=await ue(e,lm,"getTransactionReceipt")({hash:k.hash}),x={reason:e.chain?.transactionReplacement?.getReason?.({replaced:A,replacement:k})??lue(A,k),replacedTransaction:A,transaction:k,transactionReceipt:w},n>1&&(!w.blockNumber||B-w.blockNumber+1n{L.onReplaced?.(x),L.resolve(w)})}catch(U){I(()=>L.reject(U))}}else I(()=>L.reject(C))}};S=ue(e,n_,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:p,async onBlockNumber(R){for(T=R;T!==void 0&&!v;){let I=T;T=void 0,await P(I)}}})}),_.finally(()=>{c?.removeEventListener("abort",N),clearTimeout(M),E?.()})}function lue(e,t){return(t.to&&e.to?xr(t.to,e.to):t.to===e.to)&&t.value===e.value&&t.input===e.input?"repriced":t.from===t.to&&t.value===0n?"cancelled":"replaced"}var ZM=b(()=>{l();J4();Lf();zn();oc();Bi();_t();rp();A9();v3();so();A3();fu();YT();LM();KM()});function uue(e,{onBlockHeader:t,onError:r}){let n,o=bt(["watchBlockHeaders",e.uid]);return Io(o,{onBlockHeader:t,onError:r},s=>{let i=!0,a=!1,c=()=>i=!1;return(async()=>{try{let u=gu(e),{unsubscribe:d}=await u.subscribe({params:["newHeads"],onData(f){if(!i)return;let p=(e.chain?.formatters?.block?.format||qf)(f.result,"watchBlockHeaders");for(let h of KMe)delete p[h];s.onBlockHeader(p,n),n=p},onError(f){a&&s.onError?.(f)}});a=!0,c=d,i||c()}catch(u){s.onError?.(u)}})(),()=>c()})}var KMe,due=b(()=>{l();X4();rp();so();Zb();KMe=["size","totalDifficulty","transactions","uncles","withdrawals"]});function fue(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r,emitOnBegin:n=!1,onBlock:o,onError:s,includeTransactions:i,poll:a,pollingInterval:c=e.pollingInterval}){let u=typeof a<"u"?a:Q0(e),d=i??!1,f=e.chain?.blockTime,p=r??((t==="latest"||t==="pending")&&f!==void 0&&c>f/2),h=r===void 0?100:Number.POSITIVE_INFINITY,y;return u?(()=>{let v=bt(["watchBlocks",e.uid,t,p,n,d,h,c]);return Io(v,{onBlock:o,onError:s},T=>dc(async()=>{try{let E=await ue(e,xn,"getBlock")({blockTag:t,includeTransactions:d});if(E.number!==null&&y?.number!=null){if(E.number===y.number)return;let S=Number(E.number-y.number)-1;if(S>0&&S<=h&&p){let O=y.number+1n;for(let D=0;Due(e,xn,"getBlock")({blockNumber:O+BigInt(D+L),includeTransactions:d})));for(let N of M)T.onBlock(N,y),y=N}}}(y?.number==null||t==="pending"&&E?.number==null||E.number!==null&&E.number>y.number)&&(T.onBlock(E,y),y=E)}catch(E){T.onError?.(E)}},{emitOnBegin:n,interval:c}))})():(()=>{let v=!0,T=!0,E=()=>v=!1;return(async()=>{try{n&&ue(e,xn,"getBlock")({blockTag:t,includeTransactions:d}).then(O=>{v&&T&&(o(O,void 0),T=!1)}).catch(s);let S=gu(e),{unsubscribe:_}=await S.subscribe({params:["newHeads"],async onData(O){if(!v)return;let D=await ue(e,xn,"getBlock")({blockNumber:O.result?.number,includeTransactions:d}).catch(()=>{});v&&(o(D,y),T=!1,y=D)},onError(O){s?.(O)}});E=_,v||E()}catch(S){s?.(S)}})(),()=>E()})()}var pue=b(()=>{l();_t();rp();Fg();so();fu();Zb()});function hue(e,{address:t,args:r,batch:n=!0,event:o,events:s,fromBlock:i,onError:a,onLogs:c,poll:u,pollingInterval:d=e.pollingInterval,strict:f}){let p=typeof u<"u"?u:typeof i=="bigint"?!0:Q0(e),h=f??!1;return p?(()=>{let x=bt(["watchEvent",t,r,n,e.uid,o,s,d,h,i]);return Io(x,{onLogs:c,onError:a},v=>{let T=!0,E=i===void 0?void 0:i-1n,S,_=!1,O=N=>{if(N.length!==0)if(n)v.onLogs(N);else for(let L of N)v.onLogs([L])},D=(N,L)=>ue(e,F0,"getLogs")({address:t,args:r,event:o,events:s,fromBlock:N,strict:h,toBlock:L}),M=dc(async()=>{if(!_){try{S=await ue(e,sT,"createEventFilter")({address:t,args:r,event:o,events:s,strict:h,fromBlock:i})}catch{}if(_=!0,S)return}try{if(S){let P=await ue(e,J0,"getFilterChanges")({filter:S});O(P);return}let N=await ue(e,Ta,"getBlockNumber")({});E??=N;let L=N-E;for(;E{if(P===I||!Bb(C))throw C});if(!T)return;if(!B){L=(I-P+1n)/2n;continue}E=I,O(B)}}catch(N){S&&N instanceof _i&&(_=!1),v.onError?.(N)}},{emitOnBegin:!0,interval:d});return async()=>{T=!1,S&&await ue(e,X0,"uninstallFilter")({filter:S}),M()}})})():(()=>{let x=!0,v=()=>x=!1;return(async()=>{try{let T=gu(e),E=s??(o?[o]:void 0),S=[];E&&(S=[E.flatMap(D=>nc({abi:[D],eventName:D.name,args:r}))],o&&(S=S[0]));let{unsubscribe:_}=await T.subscribe({params:["logs",{address:t,topics:S}],onData(O){if(!x)return;let D=O.result;try{let{eventName:M,args:N}=Yf({abi:E??[],data:D.data,topics:D.topics,strict:h}),L=qn(D,{args:N,eventName:M});c([L])}catch(M){if((E||f)&&(M instanceof Gf||M instanceof Yl||M instanceof Jl))return;let N,L;if(M instanceof jc||M instanceof Ql){if(f)return;N=M.abiItem.name,L=M.abiItem.inputs?.some(R=>!("name"in R&&R.name))}let P=qn(D,{args:L?[]:{},eventName:N});c([P])}},onError(O){a?.(O)}});v=_,x||v()}catch(T){a?.(T)}})(),()=>v()})()}var mue=b(()=>{l();Qr();Lf();a3();Cg();hu();_t();rp();Fg();so();$L();zg();y3();c3();n9();Zb();w3()});function gue(e,{batch:t=!0,onError:r,onTransactions:n,poll:o,pollingInterval:s=e.pollingInterval}){return(typeof o<"u"?o:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let u=bt(["watchPendingTransactions",e.uid,t,s]);return Io(u,{onTransactions:n,onError:r},d=>{let f,p=dc(async()=>{try{if(!f)try{f=await ue(e,iT,"createPendingTransactionFilter")({});return}catch(y){throw p(),y}let h=await ue(e,J0,"getFilterChanges")({filter:f});if(h.length===0)return;if(t)d.onTransactions(h);else for(let y of h)d.onTransactions([y])}catch(h){d.onError?.(h)}},{emitOnBegin:!0,interval:s});return async()=>{f&&await ue(e,X0,"uninstallFilter")({filter:f}),p()}})})():(()=>{let u=!0,d=()=>u=!1;return(async()=>{try{let{unsubscribe:f}=await e.transport.subscribe({params:["newPendingTransactions"],onData(p){if(!u)return;let h=p.result;n([h])},onError(p){r?.(p)}});d=f,u||d()}catch(f){r?.(f)}})(),()=>d()})()}var yue=b(()=>{l();_t();rp();Fg();so();FL();y3();w3()});function GMe(e){return ZMe.test(e)?!Number.isNaN(new Date(e).getTime()):!1}function GM(e){return GMe(e)?new Date(e):new Date(Number.NaN)}function wue(e){let{scheme:t,statement:r,...n}=e.match(YMe)?.groups??{},{chainId:o,expirationTime:s,issuedAt:i,notBefore:a,requestId:c,resources:u,...d}=e.match(JMe)?.groups??{},f=u?.split(` +- `).slice(1);return{...n,...d,...o?{chainId:Number(o)}:{},...s?{expirationTime:GM(s)}:{},...i?{issuedAt:GM(i)}:{},...a?{notBefore:GM(a)}:{},...c?{requestId:c}:{},...f?{resources:f}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var ZMe,YMe,JMe,bue=b(()=>{l();ZMe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;YMe=/^(?:(?[a-zA-Z][a-zA-Z0-9+\-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/,JMe=/(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.*))?(?:\nResources:(?(?:\n- .+)*))?/});function xue(e){let{address:t,domain:r,message:n,nonce:o,scheme:s,time:i=new Date}=e;if(r&&n.domain!==r||o&&n.nonce!==o||s&&n.scheme!==s||n.nonce!==void 0&&!QMe.test(n.nonce)||n.version!==void 0&&n.version!=="1"||Number.isNaN(i.getTime())||n.expirationTime&&(Number.isNaN(n.expirationTime.getTime())||i>=n.expirationTime)||n.notBefore&&(Number.isNaN(n.notBefore.getTime())||i{l();Gs();Bi();QMe=/^[a-zA-Z0-9]{8,}$/});async function Eue(e,t){let{address:r,domain:n,message:o,nonce:s,scheme:i,signature:a,time:c=new Date,...u}=t,d=wue(o);if(!d.address||!xue({address:r,domain:n,message:d,nonce:s,scheme:i,time:c}))return!1;let p=im(o);return fm(e,{address:d.address,hash:p,signature:a,...u})}var Aue=b(()=>{l();T3();bue();vue();K3()});function E6(e,t){return{amount:e,decimals:t,formatted:pc(e,t)}}function o_(e,t){if(typeof e=="bigint")return e;let r=e.decimals??t;return GT(e.formatted,XMe(r))}function XMe(e){if(e===void 0)throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function s_(e,t){return typeof e=="bigint"?t:e.decimals??t}function jo(e,t){let{decimals:r,token:n}=t,o=JM(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(Ft(n,{strict:!1}))return{address:n,decimals:r??tHe(e,n)};throw new Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function JM(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=eHe(r,t);if(o)return YM(o,n);if(Ft(t,{strict:!1}))for(let s of r){let i=YM(s,n);if(i&&xr(i.address,t))return i}}function YM(e,t){if(e.addresses[t])return e(t)}function eHe(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n}function tHe(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let s=YM(o,n);if(s&&xr(s.address,t))return s.decimals}}async function A6(e,t){let{address:r,decimals:n}=jo(e,t);return n!==void 0?{address:r,decimals:n}:{address:r,decimals:await er(e,{abi:Hr,address:r,functionName:"decimals"})}}function C6(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:s,nonce:i}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:s,nonce:i}}function Eu(e){return{...e,data:Wt(e),to:e.address}}var ip=b(()=>{l();So();Gs();Bi();DM();z3();UM();oi()});async function ap(e,t){return ap.inner(_a,e,t)}function rHe(e,t){let{amount:r,spender:n,token:o}=t,{address:s,decimals:i}=jo(e,{token:o});return{abi:Hr,address:s,args:[n,o_(r,i)],functionName:"approve"}}var QM=b(()=>{l();So();Dg();i3();g3();Yb();ip();(function(e){async function t(i,a,c){return await i(a,{...c,...e.call(a,c)})}e.inner=t;function r(i,a){return Eu(rHe(i,a))}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:r,writable:!0});async function n(i,a){return $0(i,{...C6(a),...e.call(i,a)})}e.estimateGas=n;async function o(i,a){return Y0(i,{...C6(a),...e.call(i,a)})}e.simulate=o;function s(i){let[a]=cc({abi:Hr,logs:i,eventName:"Approval",strict:!0});if(!a)throw new Error("`Approval` event not found.");return a}e.extractEvent=s})(ap||(ap={}))});async function S6(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),i=(e.chain?.formatters?.transactionReceipt?.format||op)(o);if(i.status==="reverted"&&r)throw new Zh({receipt:i});return i}var i_=b(()=>{l();zn();Qb()});async function a_(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:s,authorizationList:i,blobs:a,data:c,dataSuffix:u=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,pollingInterval:x,throwOnReceiptRevert:v,type:T,value:E,...S}=t,_=t.timeout??Math.max((o?.blockTime??0)*3,5e3);if(typeof r>"u")throw new kn({docsPath:"/docs/actions/wallet/sendTransactionSync"});let O=r?ft(r):null,D;try{jn(t);let M=await(async()=>{if(t.to)return t.to;if(t.to!==null&&i&&i.length>0)return await b0({authorization:i[0]}).catch(()=>{throw new G("`to` is required. Could not infer from `authorizationList`.")})})();if(O?.type==="json-rpc"||O===null){let N;o!==null&&(N=await ue(e,hs,"getChainId")({}),n&&em({currentChainId:N,chain:o}));let L=e.chain?.formatters?.transactionRequest?.format,R=(L||Bn)({...Oi(S,{format:L}),accessList:s,account:O,authorizationList:i,blobs:a,chainId:N,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,to:M,type:T,value:E},"sendTransaction"),I=XM.get(e.uid),B=I?"wallet_sendTransaction":"eth_sendTransaction",C=await(async()=>{try{return await e.request({method:B,params:[R]},{retryCount:0})}catch(U){if(I===!1)throw U;let H=U;if(H.name==="InvalidInputRpcError"||H.name==="InvalidParamsRpcError"||H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[R]},{retryCount:0}).then(k=>(XM.set(e.uid,!0),k)).catch(k=>{let F=k;throw F.name==="MethodNotFoundRpcError"||F.name==="MethodNotSupportedRpcError"?(XM.set(e.uid,!1),H):F});throw H}})(),A=await ue(e,Z3,"waitForTransactionReceipt")({checkReplacement:!1,hash:C,pollingInterval:x,timeout:_});if(v&&A.status==="reverted")throw new Zh({receipt:A});return A}if(O?.type==="local"){let N=(()=>{if(!O.nonceManager||typeof w<"u")return O.nonceManager;let A=O.nonceManager;return{async consume(U){D={address:U.address,chainId:U.chainId};let H=await A.consume(U);return D={...D,nonce:H},H},get(U){return A.get(U)},increment(U){return A.increment(U)},reset(U){return A.reset(U)}}})(),L=await ue(e,pu,"prepareTransactionRequest")({account:O,accessList:s,authorizationList:i,blobs:a,chain:o,data:u?en([c??"0x",u]):c,gas:d,gasPrice:f,maxFeePerBlobGas:p,maxFeePerGas:h,maxPriorityFeePerGas:y,nonce:w,nonceManager:N,parameters:[...s3,"sidecars"],type:T,value:E,...S,to:M}),P=o?.serializers?.transaction,R=await O.signTransaction(L,{serializer:P}),I=(o??e.chain)?.serializers?.transactionEnvelope,B=I?await I({serializedTransaction:R,transaction:L}):R,C=Date.now();try{return await ue(e,S6,"sendRawTransactionSync")({serializedTransaction:B,throwOnReceiptRevert:v,timeout:t.timeout})}catch(A){let U=A instanceof G?A.walk(j=>j?.code===4):null;if(!U)throw A;D=void 0;let H=(()=>{let{data:j}=U;if(typeof j=="string"&&i6(j))return j;if(xa(B,0,1)==="0x03"){let W=Wg(xa(B,1));if(W.length===4&&Array.isArray(W[0]))return Pt(en(["0x03",Vo(W[0])]))}return Pt(B)})(),k=_-(Date.now()-C);if(k<=0)throw new Gh({hash:H});let F=await ue(e,Z3,"waitForTransactionReceipt")({checkReplacement:!1,hash:H,pollingInterval:x,timeout:k});if(v&&F.status==="reverted")throw new Zh({receipt:F});return F}}throw O?.type==="smart"?new fc({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new fc({docsPath:"/docs/actions/wallet/sendTransactionSync",type:O?.type})}catch(M){throw M instanceof fc?M:(D&&!(M instanceof Zh)&&O?.nonceManager?.reset(D),H0(M,{...t,account:O,chain:t.chain||void 0}))}}var XM,eH=b(()=>{l();tn();yu();nt();zn();Z4();b3();Fn();Ii();mT();wb();o3();P0();rl();_t();gT();Ks();_f();nl();Zf();ZM();Rb();i_();XM=new xo(128)});async function I6(e,t){return _a.internal(e,a_,"sendTransactionSync",t)}var c_=b(()=>{l();eH();Yb()});async function tH(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:s}=jo(e,{token:n}),i=s_(r,s),a=await ap.inner(I6,e,{...t,throwOnReceiptRevert:o}),{args:c}=ap.extractEvent(a.logs);return{...c,...i===void 0?{}:{decimals:i,formatted:pc(c.value,i)},receipt:a}}var Cue=b(()=>{l();z3();c_();QM();ip()});async function T6(e,t){let{account:r,decimals:n,spender:o,token:s,...i}=t,[a,{decimals:c}]=await Promise.all([er(e,{...i,...T6.call(e,{account:r,spender:o,token:s})}),A6(e,{decimals:n,token:s})]);return E6(a,c)}var Sue=b(()=>{l();So();oi();ip();(function(e){function t(r,n){return Eu({address:jo(r,n).address,abi:Hr,functionName:"allowance",args:[n.account,n.spender]})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(T6||(T6={}))});async function _6(e,t){let{account:r=e.account,decimals:n,token:o,...s}=t;if(!r)throw new kn;let i=ft(r).address,[a,{decimals:c}]=await Promise.all([er(e,{...s,..._6.call(e,{account:i,token:o})}),A6(e,{decimals:n,token:o})]);return E6(a,c)}var Iue=b(()=>{l();tn();So();yu();oi();ip();(function(e){function t(r,n){let o=n.account??r.account;if(!o)throw new kn;let s=ft(o).address;return Eu({address:jo(r,n).address,abi:Hr,functionName:"balanceOf",args:[s]})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(_6||(_6={}))});async function rH(e,t){let{token:r,...n}=t,{address:o}=jo(e,{token:r}),s=JM(e,r),[i,a,c]=await Promise.all([s?.decimals??er(e,{...n,abi:Hr,address:o,functionName:"decimals"}),s?.name??er(e,{...n,abi:Hr,address:o,functionName:"name"}),s?.symbol??er(e,{...n,abi:Hr,address:o,functionName:"symbol"})]);return{decimals:i,name:a,symbol:c}}var Tue=b(()=>{l();So();oi();ip()});async function P6(e,t){let{decimals:r,token:n,...o}=t,[s,{decimals:i}]=await Promise.all([er(e,{...o,...P6.call(e,{token:n})}),A6(e,{decimals:r,token:n})]);return E6(s,i)}var _ue=b(()=>{l();So();oi();ip();(function(e){function t(r,n){return Eu({address:jo(r,n).address,abi:Hr,args:[],functionName:"totalSupply"})}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:t,writable:!0})})(P6||(P6={}))});async function cp(e,t){return cp.inner(_a,e,t)}function nHe(e,t){let{amount:r,from:n,to:o,token:s}=t,{address:i,decimals:a}=jo(e,{token:s}),c=o_(r,a);return n?{abi:Hr,address:i,args:[n,o,c],functionName:"transferFrom"}:{abi:Hr,address:i,args:[o,c],functionName:"transfer"}}var nH=b(()=>{l();So();Dg();i3();g3();Yb();ip();(function(e){async function t(i,a,c){return await i(a,{...c,...e.call(a,c)})}e.inner=t;function r(i,a){return Eu(nHe(i,a))}Object.defineProperty(e,"call",{configurable:!0,enumerable:!0,value:r,writable:!0});async function n(i,a){return $0(i,{...C6(a),...e.call(i,a)})}e.estimateGas=n;async function o(i,a){return Y0(i,{...C6(a),...e.call(i,a)})}e.simulate=o;function s(i){let[a]=cc({abi:Hr,logs:i,eventName:"Transfer",strict:!0});if(!a)throw new Error("`Transfer` event not found.");return a}e.extractEvent=s})(cp||(cp={}))});async function oH(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:s}=jo(e,{token:n}),i=s_(r,s),a=await cp.inner(I6,e,{...t,throwOnReceiptRevert:o}),{args:c}=cp.extractEvent(a.logs);return{...c,...i===void 0?{}:{decimals:i,formatted:pc(c.value,i)},receipt:a}}var Pue=b(()=>{l();z3();c_();ip();nH()});var sH=b(()=>{l();QM();Cue();Sue();Iue();Tue();_ue();nH();Pue()});function l_(e){return{call:t=>ms(e,t),createAccessList:t=>rae(e,t),createBlockFilter:()=>oae(e),createContractEventFilter:t=>Zw(e,t),createEventFilter:t=>sT(e,t),createPendingTransactionFilter:()=>iT(e),estimateContractGas:t=>$0(e,t),estimateGas:t=>Ob(e,t),getBalance:t=>iae(e,t),getBlobBaseFee:()=>cae(e),getBlock:t=>xn(e,t),getBlockNumber:t=>Ta(e,t),getBlockReceipts:t=>uae(e,t),getBlockTransactionCount:t=>fae(e,t),getBytecode:t=>jg(e,t),getChainId:()=>hs(e),getCode:t=>jg(e,t),getContractEvents:t=>kb(e,t),getDelegation:t=>hae(e,t),getEip712Domain:t=>yae(e,t),getEnsAddress:t=>Die(e,t),getEnsAvatar:t=>Yie(e,t),getEnsName:t=>Qie(e,t),getEnsResolver:t=>eae(e,t),getEnsText:t=>oT(e,t),getFeeHistory:t=>vae(e,t),estimateFeesPerGas:t=>Mse(e,t),getFilterChanges:t=>J0(e,t),getFilterLogs:t=>Aae(e,t),getGasPrice:()=>Cb(e),getLogs:t=>F0(e,t),getProof:t=>Sle(e,t),estimateMaxPriorityFeePerGas:t=>Lse(e,t),fillTransaction:t=>Nb(e,t),getRawTransaction:t=>Tle(e,t),getStorageAt:t=>Ple(e,t),getStorageValues:t=>Rle(e,t),getTransaction:t=>cm(e,t),getTransactionConfirmations:t=>Ble(e,t),getTransactionCount:t=>k0(e,t),getTransactionReceipt:t=>lm(e,t),iterateLogs:t=>o9(e,t),multicall:t=>Ule(e,t),prepareTransactionRequest:t=>pu(e,t),readContract:t=>er(e,t),sendRawTransaction:t=>Gb(e,t),sendRawTransactionSync:t=>S6(e,t),simulate:t=>w6(e,t),simulateBlocks:t=>w6(e,t),simulateCalls:t=>eue(e,t),simulateContract:t=>Y0(e,t),verifyHash:t=>fm(e,t),verifyMessage:t=>sue(e,t),verifySiweMessage:t=>Eue(e,t),verifyTypedData:t=>aue(e,t),uninstallFilter:t=>X0(e,t),waitForTransactionReceipt:t=>Z3(e,t),watchBlockHeaders:t=>uue(e,t),watchBlocks:t=>fue(e,t),watchBlockNumber:t=>n_(e,t),watchContractEvent:t=>M9(e,t),watchEvent:t=>hue(e,t),watchPendingTransactions:t=>gue(e,t),token:oHe(e)}}function oHe(e){return{getAllowance:bu(e,T6),getBalance:bu(e,_6),getMetadata:bu(e,rH),getTotalSupply:bu(e,P6)}}var iH=b(()=>{l();Lie();Jie();Xie();tae();HL();G0();nae();sae();II();$L();FL();i3();ZD();r9();KD();t9();aae();lae();fu();zg();dae();pae();Zf();aT();s9();mae();wae();Eae();y3();Cae();qI();c3();Ile();_le();Nle();Ole();YT();kle();e3();LM();eL();Dle();oi();MM();tue();g3();w3();K3();iue();cue();ZM();due();KM();pue();IL();mue();yue();Aue();sH();Rb();H9();i_();nm()});function Nue(e){let{key:t="public",name:r="Public Client"}=e;return wu({...e,key:t,name:r,type:"publicClient"}).extend(l_)}var Rue=b(()=>{l();nm();iH()});async function Oue(e,{hash:t}){await e.request({method:`${e.mode}_dropTransaction`,params:[t]})}var Bue=b(()=>{l()});async function kue(e){return e.request({method:`${e.mode}_dumpState`})}var Uue=b(()=>{l()});async function Due(e){return e.mode==="ganache"?await e.request({method:"eth_mining"}):await e.request({method:`${e.mode}_getAutomine`})}var Lue=b(()=>{l()});async function Mue(e){return await e.request({method:"txpool_content"})}var Hue=b(()=>{l()});async function $ue(e){let{pending:t,queued:r}=await e.request({method:"txpool_status"});return{pending:wt(t),queued:wt(r)}}var Fue=b(()=>{l();Xr()});async function zue(e,{address:t}){await e.request({method:`${e.mode}_impersonateAccount`,params:[t]})}var Vue=b(()=>{l()});async function jue(e,{seconds:t}){return await e.request({method:"evm_increaseTime",params:[oe(t)]})}var que=b(()=>{l();qe()});async function Wue(e){return await e.request({method:"txpool_inspect"})}var Kue=b(()=>{l()});async function Zue(e,{state:t}){await e.request({method:`${e.mode}_loadState`,params:[t]})}var Gue=b(()=>{l()});async function Yue(e,{blocks:t,interval:r}){e.mode==="ganache"?await e.request({method:"evm_mine",params:[{blocks:oe(t)}]}):await e.request({method:`${e.mode}_mine`,params:[oe(t),oe(r||0)]})}var Jue=b(()=>{l();qe()});async function Que(e){await e.request({method:`${e.mode}_removeBlockTimestampInterval`})}var Xue=b(()=>{l()});async function ede(e,{blockNumber:t,jsonRpcUrl:r}={}){await e.request({method:`${e.mode}_reset`,params:[{forking:{blockNumber:Number(t),jsonRpcUrl:r}}]})}var tde=b(()=>{l()});async function rde(e,{id:t}){await e.request({method:"evm_revert",params:[t]})}var nde=b(()=>{l()});async function ode(e,t){let{accessList:r,data:n,from:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:f,...p}=t,h=e.chain?.formatters?.transactionRequest?.format,w=(h||Bn)({...Oi(p,{format:h}),accessList:r,data:n,from:o,gas:s,gasPrice:i,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:u,to:d,value:f},"sendUnsignedTransaction");return await e.request({method:"eth_sendUnsignedTransaction",params:[w]})}var sde=b(()=>{l();P0();rl()});async function ide(e,t){e.mode==="ganache"?t?await e.request({method:"miner_start"}):await e.request({method:"miner_stop"}):await e.request({method:"evm_setAutomine",params:[t]})}var ade=b(()=>{l()});async function cde(e,{address:t,value:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountBalance",params:[t,oe(r)]}):await e.request({method:`${e.mode}_setBalance`,params:[t,oe(r)]})}var lde=b(()=>{l();qe()});async function ude(e,{gasLimit:t}){await e.request({method:"evm_setBlockGasLimit",params:[oe(t)]})}var dde=b(()=>{l();qe()});async function fde(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:`${e.mode}_setBlockTimestampInterval`,params:[r]})}var pde=b(()=>{l()});async function hde(e,{address:t,bytecode:r}){e.mode==="ganache"?await e.request({method:"evm_setAccountCode",params:[t,r]}):await e.request({method:`${e.mode}_setCode`,params:[t,r]})}var mde=b(()=>{l()});async function gde(e,{address:t}){await e.request({method:`${e.mode}_setCoinbase`,params:[t]})}var yde=b(()=>{l()});async function wde(e,{interval:t}){let r=e.mode==="hardhat"?t*1e3:t;await e.request({method:"evm_setIntervalMining",params:[r]})}var bde=b(()=>{l()});async function xde(e,t){await e.request({method:`${e.mode}_setLoggingEnabled`,params:[t]})}var vde=b(()=>{l()});async function Ede(e,{gasPrice:t}){await e.request({method:`${e.mode}_setMinGasPrice`,params:[oe(t)]})}var Ade=b(()=>{l();qe()});async function Cde(e,{baseFeePerGas:t}){await e.request({method:`${e.mode}_setNextBlockBaseFeePerGas`,params:[oe(t)]})}var Sde=b(()=>{l();qe()});async function Ide(e,{timestamp:t}){await e.request({method:"evm_setNextBlockTimestamp",params:[oe(t)]})}var Tde=b(()=>{l();qe()});async function _de(e,{address:t,nonce:r}){await e.request({method:`${e.mode}_setNonce`,params:[t,oe(r)]})}var Pde=b(()=>{l();qe()});async function Nde(e,t){await e.request({method:`${e.mode}_setRpcUrl`,params:[t]})}var Rde=b(()=>{l()});async function Ode(e,{address:t,index:r,value:n}){await e.request({method:`${e.mode}_setStorageAt`,params:[t,typeof r=="number"?oe(r):r,n]})}var Bde=b(()=>{l();qe()});async function kde(e){return await e.request({method:"evm_snapshot"})}var Ude=b(()=>{l()});async function Dde(e,{address:t}){await e.request({method:`${e.mode}_stopImpersonatingAccount`,params:[t]})}var Lde=b(()=>{l()});function u_({mode:e}){return t=>{let r=t.extend(()=>({mode:e}));return{dropTransaction:n=>Oue(r,n),dumpState:()=>kue(r),getAutomine:()=>Due(r),getTxpoolContent:()=>Mue(r),getTxpoolStatus:()=>$ue(r),impersonateAccount:n=>zue(r,n),increaseTime:n=>jue(r,n),inspectTxpool:()=>Wue(r),loadState:n=>Zue(r,n),mine:n=>Yue(r,n),removeBlockTimestampInterval:()=>Que(r),reset:n=>ede(r,n),revert:n=>rde(r,n),sendUnsignedTransaction:n=>ode(r,n),setAutomine:n=>ide(r,n),setBalance:n=>cde(r,n),setBlockGasLimit:n=>ude(r,n),setBlockTimestampInterval:n=>fde(r,n),setCode:n=>hde(r,n),setCoinbase:n=>gde(r,n),setIntervalMining:n=>wde(r,n),setLoggingEnabled:n=>xde(r,n),setMinGasPrice:n=>Ede(r,n),setNextBlockBaseFeePerGas:n=>Cde(r,n),setNextBlockTimestamp:n=>Ide(r,n),setNonce:n=>_de(r,n),setRpcUrl:n=>Nde(r,n),setStorageAt:n=>Ode(r,n),snapshot:()=>kde(r),stopImpersonatingAccount:n=>Dde(r,n)}}}var aH=b(()=>{l();Bue();Uue();Lue();Hue();Fue();Vue();que();Kue();Gue();Jue();Xue();tde();nde();sde();ade();lde();dde();pde();mde();yde();bde();vde();Ade();Sde();Tde();Pde();Rde();Bde();Ude();Lde()});function Mde(e){let{key:t="test",name:r="Test Client",mode:n}=e;return wu({...e,key:t,name:r,type:"testClient"}).extend(s=>({mode:n,...u_({mode:n})(s)}))}var Hde=b(()=>{l();nm();aH()});async function $de(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:s,blockExplorers:i}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:oe(r),chainName:n,nativeCurrency:o,rpcUrls:s.default.http,blockExplorerUrls:i?Object.values(i).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}var Fde=b(()=>{l();qe()});function zde(e,t){let{abi:r,args:n,bytecode:o,...s}=t,i=tp({abi:r,args:n,bytecode:o});return ue(e,tm,"sendTransaction")({...s,...s.authorizationList?{to:null}:{},data:i})}var Vde=b(()=>{l();p3();_t();x3()});async function jde(e){return e.account?.type==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(r=>Kc(r))}var qde=b(()=>{l();Zs()});async function Wde(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?ft(r):void 0,s=n?[o?.address,[oe(n)]]:[o?.address],i=await e.request({method:"wallet_getCapabilities",params:s}),a={};for(let[c,u]of Object.entries(i)){a[Number(c)]={};for(let[d,f]of Object.entries(u))d==="addSubAccount"&&(d="unstable_addSubAccount"),a[Number(c)][d]=f}return typeof n=="number"?a[n]:a}var Kde=b(()=>{l();tn();qe()});async function Zde(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}var Gde=b(()=>{l()});async function d_(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new kn({docsPath:"/docs/eip7702/prepareAuthorization"});let s=ft(r),i=(()=>{if(t.executor)return t.executor==="self"?t.executor:ft(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};return typeof a.chainId>"u"&&(a.chainId=e.chain?.id??await ue(e,hs,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await ue(e,k0,"getTransactionCount")({address:s.address,blockTag:"pending"}),(i==="self"||i?.address&&xr(i.address,s.address))&&(a.nonce+=1)),a}var cH=b(()=>{l();tn();yu();Bi();_t();Zf();e3()});async function Yde(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>Gr(r))}var Jde=b(()=>{l();Zs()});async function Qde(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}var Xde=b(()=>{l()});async function efe(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5e3),o=await ue(e,F9,"sendCalls")(t);return await ue(e,j9,"waitForCallsStatus")({...t,id:o.id,timeout:n})}var tfe=b(()=>{l();_t();z9();q9()});async function rfe(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}var nfe=b(()=>{l()});async function ofe(e,t){let{account:r=e.account}=t;if(!r)throw new kn({docsPath:"/docs/eip7702/signAuthorization"});let n=ft(r);if(!n.signAuthorization)throw new fc({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await ue(e,d_,"prepareAuthorization")(t);return n.signAuthorization(o)}var sfe=b(()=>{l();tn();yu();_t();cH()});async function ife(e,{account:t=e.account,message:r}){if(!t)throw new kn({docsPath:"/docs/actions/wallet/signMessage"});let n=ft(t);if(n.signMessage)return n.signMessage({message:r});let o=typeof r=="string"?ec(r):r.raw instanceof Uint8Array?wr(r.raw):r.raw;return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}var afe=b(()=>{l();tn();yu();qe()});async function cfe(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new kn({docsPath:"/docs/actions/wallet/signTransaction"});let s=ft(r);jn({account:s,...t});let i=await ue(e,hs,"getChainId")({});n!==null&&em({currentChainId:i,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||Bn;return s.signTransaction?s.signTransaction({...o,account:s,chainId:i},{serializer:e.chain?.serializers?.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...o,account:s},"signTransaction"),chainId:oe(i),from:s.address}]},{retryCount:0})}var lfe=b(()=>{l();tn();yu();b3();qe();rl();_t();nl();Zf()});async function ufe(e,t){let{account:r=e.account,domain:n,message:o,primaryType:s}=t;if(!r)throw new kn({docsPath:"/docs/actions/wallet/signTypedData"});let i=ft(r),a={EIP712Domain:Zg({domain:n}),...t.types};if(f6({domain:n,message:o,primaryType:s,types:a}),i.signTypedData)return i.signTypedData({domain:n,message:o,primaryType:s,types:a});let c=vT({domain:n,message:o,primaryType:s,types:a});return e.request({method:"eth_signTypedData_v4",params:[i.address,c]},{retryCount:0})}var dfe=b(()=>{l();tn();yu();ET()});async function ffe(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:oe(t)}]},{retryCount:0})}var pfe=b(()=>{l();qe()});async function hfe(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}var mfe=b(()=>{l()});function f_(e){return{addChain:t=>$de(e,t),deployContract:t=>zde(e,t),fillTransaction:t=>Nb(e,t),getAddresses:()=>jde(e),getCallsStatus:t=>V9(e,t),getCapabilities:t=>Wde(e,t),getChainId:()=>hs(e),getPermissions:()=>Zde(e),prepareAuthorization:t=>d_(e,t),prepareTransactionRequest:t=>pu(e,t),requestAddresses:()=>Yde(e),requestPermissions:t=>Qde(e,t),sendCalls:t=>F9(e,t),sendCallsSync:t=>efe(e,t),sendRawTransaction:t=>Gb(e,t),sendRawTransactionSync:t=>S6(e,t),sendTransaction:t=>tm(e,t),sendTransactionSync:t=>a_(e,t),showCallsStatus:t=>rfe(e,t),signAuthorization:t=>ofe(e,t),signMessage:t=>ife(e,t),signTransaction:t=>cfe(e,t),signTypedData:t=>ufe(e,t),switchChain:t=>ffe(e,t),waitForCallsStatus:t=>j9(e,t),watchAsset:t=>hfe(e,t),writeContract:t=>_a(e,t),writeContractSync:t=>I6(e,t),token:{approve:bu(e,ap),approveSync:bu(e,tH),transfer:bu(e,cp),transferSync:bu(e,oH)}}}var lH=b(()=>{l();t9();Zf();sH();Fde();Vde();qde();BL();Kde();Gde();cH();Rb();Jde();Xde();z9();tfe();H9();i_();x3();eH();nfe();sfe();afe();lfe();dfe();pfe();q9();mfe();Yb();c_();nm()});function gfe(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return wu({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(f_)}var yfe=b(()=>{l();nm();lH()});function Au({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:s=150,timeout:i,type:a},c){let u=rm();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:s,timeout:i,type:a},request:Dae(n,{methods:t,retryCount:o,retryDelay:s,uid:u}),value:c}}var N6=b(()=>{l();Mae();A3()});function wfe(e,t={}){let{key:r="custom",methods:n,name:o="Custom Provider",retryDelay:s}=t;return({retryCount:i})=>Au({key:r,methods:n,name:o,request:e.request.bind(e),retryCount:t.retryCount??i,retryDelay:s,type:"custom"})}var bfe=b(()=>{l();N6()});function G3(e,t={}){let{key:r="fallback",name:n="Fallback",rank:o=!1,shouldThrow:s=uH,retryCount:i,retryDelay:a}=t;return(({chain:c,pollingInterval:u=4e3,timeout:d,...f})=>{let p=e,h=()=>{},y=Au({key:r,name:n,async request({method:w,params:x},v){let T,E=async(S=0)=>{let _=p[S]({...f,chain:c,retryCount:0,timeout:d});try{let O=await _.request({method:w,params:x},v);return h({method:w,params:x,response:O,transport:_,status:"success"}),O}catch(O){if(h({error:O,method:w,params:x,transport:_,status:"error"}),s(O)||w==="eth_sendRawTransactionSync"&&O instanceof G&&O.walk(D=>D?.code===4)||S===p.length-1||(T??=p.slice(S+1).some(D=>{let{include:M,exclude:N}=D({chain:c}).config.methods||{};return M?M.includes(w):N?!N.includes(w):!0}),!T))throw O;return E(S+1)}};return E()},retryCount:i,retryDelay:a,type:"fallback"},{onResponse:w=>h=w,transports:p.map(w=>w({chain:c,retryCount:0}))});if(o){let w=typeof o=="object"?o:{};sHe({chain:c,interval:w.interval??u,onTransports:x=>p=x,ping:w.ping,sampleCount:w.sampleCount,timeout:w.timeout,transports:p,weights:w.weights})}return y})}function uH(e){return!!("code"in e&&typeof e.code=="number"&&(e.code===iu.code||e.code===Xc.code||e.code===f0.code||ri.nodeMessage.test(e.message)||e.code===5e3))}function sHe({chain:e,interval:t=4e3,onTransports:r,ping:n,sampleCount:o=10,timeout:s=1e3,transports:i,weights:a={}}){let{stability:c=.7,latency:u=.3}=a,d=[],f=async()=>{let p=await Promise.all(i.map(async w=>{let x=w({chain:e,retryCount:0,timeout:s}),v=Date.now(),T,E;try{await(n?n({transport:x}):x.request({method:"net_listening"})),E=1}catch{E=0}finally{T=Date.now()}return{latency:T-v,success:E}}));d.push(p),d.length>o&&d.shift();let h=Math.max(...d.map(w=>Math.max(...w.map(({latency:x})=>x)))),y=i.map((w,x)=>{let v=d.map(O=>O[x].latency),E=1-v.reduce((O,D)=>O+D,0)/v.length/h,S=d.map(O=>O[x].success),_=S.reduce((O,D)=>O+D,0)/S.length;return _===0?[0,x]:[u*E+c*_,x]}).sort((w,x)=>x[0]-w[0]);r(y.map(([,w])=>i[w])),await $g(t),f()};f()}var xfe=b(()=>{l();nt();tl();Lf();D9();N6()});var pm,p_=b(()=>{l();nt();pm=class extends G{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}});function aHe(e){if(!e)return"default";let t=vfe.get(e);if(t!==void 0)return t;let r=iHe++;return vfe.set(e,r),r}function ry(e,t={}){let{batch:r,fetchFn:n,fetchOptions:o,key:s="http",maxResponseBodySize:i,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:u,onFetchResponse:d,retryDelay:f,raw:p}=t,h=rm();return({chain:y,retryCount:w,timeout:x})=>{let{batchSize:v=1e3,wait:T=0}=typeof r=="object"?r:{},E=t.retryCount??w,S=x??t.timeout??1e4,_=e||y?.rpcUrls.default.http[0];if(!_)throw new pm;let O=mce(_,{fetchFn:n,fetchOptions:o,maxResponseBodySize:i,onRequest:u,onResponse:d,timeout:S});return Au({key:s,methods:a,name:c,async request({method:D,params:M},N){let L={method:D,params:M},P=N?.signal?{signal:N.signal}:void 0,{schedule:R}=Z0({id:`${h}.${_}.${aHe(N?.signal)}`,wait:T,shouldSplitBatch(A){return A.length>v},fn:A=>O.request({body:A,fetchOptions:P}),sort:(A,U)=>A.id-U.id}),I=async A=>r?R(A):[await O.request({body:A,fetchOptions:P})],[{error:B,result:C}]=await I(L).catch(A=>{if(p&&A instanceof Rn)return[{error:A.cause,result:void 0}];throw A});if(p)return{error:B,result:C};if(B)throw new Rn({body:L,error:B,url:_});return C},retryCount:E,retryDelay:f,timeout:S,type:"http"},{fetchOptions:o,url:_})}}var iHe,vfe,Efe=b(()=>{l();fs();p_();h3();gce();A3();N6();iHe=0,vfe=new WeakMap});function Afe(e,t={}){let{keepAlive:r,key:n="webSocket",methods:o,name:s="WebSocket JSON-RPC",reconnect:i,retryDelay:a}=t;return({chain:c,retryCount:u,timeout:d})=>{let f=t.retryCount??u,p=d??t.timeout??1e4,h=e||c?.rpcUrls.default.webSocket?.[0],y={keepAlive:r,reconnect:i};if(!h)throw new pm;return Au({key:n,methods:o,name:s,async request({method:w,params:x}){let v={method:w,params:x},T=await c6(h,y),{error:E,result:S}=await T.requestAsync({body:v,timeout:p});if(E)throw new Rn({body:v,error:E,url:h});return S},retryCount:f,retryDelay:a,timeout:p,type:"webSocket"},{getSocket(){return Cce(h)},getRpcClient(){return c6(h,y)},async subscribe({params:w,onData:x,onError:v}){let T=await c6(h,y),E,S=!1;function _(){return S=!0,new Promise(O=>T.request({body:{method:"eth_unsubscribe",params:[E]},onResponse:O}))}return await new Promise((O,D)=>T.request({body:{method:"eth_subscribe",params:w},onError(M){D(M),v?.(M)},onResponse(M){if(M.error){D(M.error),v?.(M.error);return}if(typeof M.id=="number"){E=M.result,S&&_(),O(M);return}M.method==="eth_subscription"&&x(M.params)}})),{get subscriptionId(){return E},unsubscribe:_}}})}}var Cfe=b(()=>{l();fs();p_();Sce();GL();N6()});var Sfe,Ife,Tfe,_fe=b(()=>{l();Sfe={gwei:9,wei:18},Ife={ether:-9,wei:9},Tfe={ether:-18,gwei:-9}});var h_,Pfe=b(()=>{l();nt();h_=class extends G{constructor({value:t}){super(`Number \`${t}\` is not a valid decimal number.`,{name:"InvalidDecimalNumberError"})}}});var m_,Nfe=b(()=>{l();m_=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}}});function Rfe(e){let{abi:t,bytecode:r,data:n}=e;if(n===r)return{bytecode:r};let o=t.find(i=>"type"in i&&i.type==="constructor");if(!o)throw new Oh({docsPath:dH});if(!("inputs"in o))throw new Gl({docsPath:dH});if(!o.inputs||o.inputs.length===0)throw new Gl({docsPath:dH});return{args:Ys(o.inputs,`0x${n.replace(r,"")}`),bytecode:r}}var dH,Ofe=b(()=>{l();Qr();zh();dH="/docs/contract/decodeDeployData"});function Bfe(e){let t=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),r=typeof e.blobs[0]=="string"?e.blobs.map(a=>qt(a)):e.blobs,n=r.reduce((a,c)=>a+c.length,0),o=Zc(new Uint8Array(n)),s=!0;for(let[a,c]of r.entries()){let u=Zc(c),d=a===r.length-1;for(;s&&u.position{l();Jw();Pr();qe()});function Ufe(e){let{sidecars:t,version:r}=e,n=e.to??(typeof t[0].blob=="string"?"hex":"bytes"),o=[];for(let{commitment:s}of t)o.push(Ib({commitment:s,to:n,version:r}));return o}var Dfe=b(()=>{l();ZI()});function Lfe(e){if(e===1)return 60n;if(e>=cHe||e<0)throw new r6({chainId:e});return BigInt((2147483648|e)>>>0)}var cHe,Mfe=b(()=>{l();rT();cHe=2147483648});function g_({blobToKzgCommitment:e,computeBlobKzgProof:t}){return{blobToKzgCommitment:e,computeBlobKzgProof:t}}var fH=b(()=>{l()});function Hfe(e,t){try{e.loadTrustedSetup(t)}catch(r){let n=r;if(!n.message.includes("trusted setup is already loaded"))throw n}return g_(e)}var $fe=b(()=>{l();fH()});function Ffe({r:e,yParityAndS:t}){let r=qt(Zr(t)),n=r[0]&128?1:0,o=r;return n===1&&(o[0]&=127),{r:Zr(e),s:yt(o),yParity:n}}var zfe=b(()=>{l();Xa();Pr();qe()});function pH(e){let{r:t,s:r}=ei.Signature.fromCompact(e.slice(2,130));return{r:oe(t,{size:32}),yParityAndS:oe(r,{size:32})}}var Vfe=b(()=>{l();Bg();qe()});function hH(e){let{r:t,s:r}=ei.Signature.fromCompact(e.slice(2,130)),n=+`0x${e.slice(130)}`,[o,s]=(()=>{if(n===0||n===1)return[void 0,n];if(n===27)return[BigInt(n),0];if(n===28)return[BigInt(n),1];throw new Error("Invalid yParityOrV value")})();return typeof o<"u"?{r:oe(t,{size:32}),s:oe(r,{size:32}),v:o,yParity:s}:{r:oe(t,{size:32}),s:oe(r,{size:32}),yParity:s}}var jfe=b(()=>{l();Bg();qe()});async function qfe(e){let{serializedTransaction:t,signature:r}=e,n=WT(t),o=r??{r:n.r,s:n.s,v:n.v,yParity:n.yParity},s=fT({...n,r:void 0,s:void 0,v:void 0,yParity:void 0,sidecars:void 0});return await ti({hash:Pt(s),signature:o})}var Wfe=b(()=>{l();Ks();kM();pT();w0()});function mH({r:e,yParityAndS:t}){return`0x${new ei.Signature(dt(e),dt(t)).toCompactHex()}`}var Kfe=b(()=>{l();Bg();Xr()});function Zfe(e){let{r:t,s:r,v:n,yParity:o}=e,s=(()=>{if(o===0||o===1)return o;if(n===0n||n===1n)return Number(n);if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),i=qt(Zr(r));if(i[0]&128)throw new Error("Invalid `s` value");return s===1&&(i[0]|=128),{r:Zr(t),yParityAndS:yt(i)}}var Gfe=b(()=>{l();Xa();Pr();qe()});var Yfe={};Te(Yfe,{AbiConstructorNotFoundError:()=>Oh,AbiConstructorParamsNotFoundError:()=>Gl,AbiDecodingDataSizeInvalidError:()=>yI,AbiDecodingDataSizeTooSmallError:()=>Bh,AbiDecodingSizeLimitExceededError:()=>Xw,AbiDecodingZeroDataError:()=>Si,AbiEncodingArrayLengthMismatchError:()=>Nw,AbiEncodingBytesSizeMismatchError:()=>Rw,AbiEncodingLengthMismatchError:()=>kh,AbiErrorInputsNotFoundError:()=>Ow,AbiErrorNotFoundError:()=>pg,AbiErrorSignatureNotFoundError:()=>Uh,AbiEventAmbiguityError:()=>Gf,AbiEventNotFoundError:()=>hg,AbiEventSignatureEmptyTopicsError:()=>Yl,AbiEventSignatureNotFoundError:()=>Jl,AbiFunctionNotFoundError:()=>wa,AbiFunctionOutputsNotFoundError:()=>Dh,AbiFunctionSignatureNotFoundError:()=>Bw,AccountStateConflictError:()=>tb,AtomicReadyWalletRejectedUpgradeError:()=>d0,AtomicityNotSupportedError:()=>cu,BaseError:()=>G,BaseFeeScalarError:()=>O0,BlockNotFoundError:()=>du,BundleFailedError:()=>Jb,BundleTooLargeError:()=>u0,BytesSizeMismatchError:()=>Lh,CallExecutionError:()=>Yc,ChainDisconnectedError:()=>s0,ChainDoesNotSupportContract:()=>Wf,ChainMismatchError:()=>U0,ChainNotConfiguredError:()=>C3,ChainNotFoundError:()=>Sb,CircularReferenceError:()=>lg,ClientChainNotConfiguredError:()=>kg,ContractFunctionExecutionError:()=>ab,ContractFunctionRevertedError:()=>Uf,ContractFunctionZeroDataError:()=>cb,CounterfactualDeploymentFailedError:()=>lb,DecodeLogDataMismatch:()=>jc,DecodeLogTopicsMismatch:()=>Ql,DuplicateIdError:()=>c0,EIP1193ProviderRpcError:()=>m_,Eip1559FeesNotSupportedError:()=>uu,EnsAvatarInvalidNftUriError:()=>xu,EnsAvatarUnsupportedNamespaceError:()=>t6,EnsAvatarUriResolutionError:()=>om,EnsInvalidChainIdError:()=>r6,EstimateGasExecutionError:()=>bb,ExecutionRevertedError:()=>ri,FeeCapTooHighError:()=>Ni,FeeCapTooLowError:()=>x0,FeeConflictError:()=>BI,FeePayerNonceMismatchError:()=>Wh,FilterTypeNotSupportedError:()=>Lw,HttpRequestError:()=>Nr,InsufficientFundsError:()=>C0,IntegerOutOfRangeError:()=>Xl,InternalRpcError:()=>Qc,IntrinsicGasTooHighError:()=>S0,IntrinsicGasTooLowError:()=>I0,InvalidAbiDecodingTypeError:()=>Uw,InvalidAbiEncodingTypeError:()=>kw,InvalidAbiItemError:()=>Q1,InvalidAbiParameterError:()=>eg,InvalidAbiParametersError:()=>tg,InvalidAbiTypeParameterError:()=>ig,InvalidAddressError:()=>br,InvalidArrayError:()=>Mh,InvalidBytesBooleanError:()=>Mw,InvalidChainIdError:()=>Kf,InvalidDecimalNumberError:()=>h_,InvalidDefinitionTypeError:()=>Pw,InvalidDomainError:()=>l6,InvalidFunctionModifierError:()=>sg,InvalidHexBooleanError:()=>Hw,InvalidHexValueError:()=>$w,InvalidInputRpcError:()=>_i,InvalidLegacyVError:()=>Kh,InvalidModifierError:()=>og,InvalidParameterError:()=>rg,InvalidParamsRpcError:()=>Qh,InvalidParenthesisError:()=>ug,InvalidPrimaryTypeError:()=>u6,InvalidRequestRpcError:()=>Jh,InvalidSerializableTransactionError:()=>nb,InvalidSerializedTransactionError:()=>ru,InvalidSerializedTransactionTypeError:()=>ob,InvalidSignatureError:()=>ya,InvalidStorageKeySizeError:()=>sb,InvalidStructSignatureError:()=>cg,InvalidStructTypeError:()=>d6,InvalidTypedDataTypeError:()=>Kg,InvalidYParityError:()=>tu,JsonRpcVersionUnsupportedError:()=>t0,LimitExceededRpcError:()=>Df,MaxFeePerGasTooLowError:()=>vb,MethodNotFoundRpcError:()=>Jc,MethodNotSupportedRpcError:()=>Aa,NonceMaxValueError:()=>A0,NonceTooHighError:()=>v0,NonceTooLowError:()=>E0,ParseRpcError:()=>Yh,ProviderDisconnectedError:()=>o0,ProviderRpcError:()=>Ao,RawContractError:()=>sc,ResourceNotFoundRpcError:()=>Xh,ResourceUnavailableRpcError:()=>e0,ResponseBodyTooLargeError:()=>ic,RlpDepthLimitExceededError:()=>Fw,RlpListBoundaryExceededError:()=>zw,RlpTrailingBytesError:()=>Vw,RpcError:()=>Eo,RpcRequestError:()=>Rn,SizeExceedsPaddingSizeError:()=>gg,SizeOverflowError:()=>jw,SliceOffsetOutOfBoundsError:()=>mg,SocketClosedError:()=>su,SolidityProtectedKeywordError:()=>ng,StateAssignmentConflictError:()=>rb,SwitchChainError:()=>i0,TimeoutError:()=>ds,TipAboveFeeCapError:()=>ac,TransactionExecutionError:()=>ib,TransactionNotFoundError:()=>Gc,TransactionReceiptNotFoundError:()=>nu,TransactionRejectedRpcError:()=>iu,TransactionTypeNotSupportedError:()=>T0,TransportNotConfiguredError:()=>S3,UnauthorizedProviderError:()=>r0,UnknownBundleIdError:()=>l0,UnknownNodeError:()=>Ri,UnknownRpcError:()=>ub,UnknownSignatureError:()=>ag,UnknownTypeError:()=>X1,UnsupportedChainIdError:()=>a0,UnsupportedNonOptionalCapabilityError:()=>au,UnsupportedPackedAbiType:()=>Dw,UnsupportedProviderMethodError:()=>n0,UrlRequiredError:()=>pm,UserRejectedRequestError:()=>Xc,WaitForCallsStatusTimeoutError:()=>E3,WaitForTransactionReceiptTimeoutError:()=>Gh,WebSocketRequestError:()=>_g,assertCurrentChain:()=>em,assertRequest:()=>jn,assertTransactionEIP1559:()=>sm,assertTransactionEIP2930:()=>n6,assertTransactionLegacy:()=>o6,blobsToCommitments:()=>D0,blobsToProofs:()=>L0,boolToBytes:()=>KU,boolToHex:()=>wg,bytesToBigInt:()=>B4,bytesToBool:()=>k4,bytesToHex:()=>yt,bytesToNumber:()=>Ea,bytesToRlp:()=>Mne,bytesToString:()=>U4,ccipFetch:()=>Hg,ccipReadTunnel:()=>Hae,ccipRequest:()=>Hg,checksumAddress:()=>Kc,commitmentToVersionedHash:()=>Ib,commitmentsToVersionedHashes:()=>Tb,compactSignatureToHex:()=>mH,compactSignatureToSignature:()=>Ffe,concat:()=>en,concatBytes:()=>eD,concatHex:()=>fr,createClient:()=>wu,createClientResolver:()=>Oie,createNonceManager:()=>WL,createPublicClient:()=>Nue,createTestClient:()=>Mde,createTransport:()=>Au,createWalletClient:()=>gfe,custom:()=>wfe,decodeAbiParameters:()=>Ys,decodeDeployData:()=>Rfe,decodeErrorResult:()=>Vh,decodeEventLog:()=>Yf,decodeFunctionData:()=>T9,decodeFunctionResult:()=>dn,defineBlock:()=>Dse,defineChain:()=>Fae,defineKzg:()=>g_,defineTransaction:()=>Use,defineTransactionReceipt:()=>Sie,defineTransactionRequest:()=>Wne,deploylessCallViaBytecodeBytecode:()=>zb,deploylessCallViaFactoryBytecode:()=>v9,domainSeparator:()=>Ice,encodeAbiParameters:()=>oo,encodeDeployData:()=>tp,encodeErrorResult:()=>m3,encodeEventTopics:()=>nc,encodeFunctionData:()=>Wt,encodeFunctionResult:()=>_9,encodePacked:()=>Sae,erc1155Abi:()=>die,erc20Abi:()=>Hr,erc20Abi_bytes32:()=>uie,erc4626Abi:()=>pie,erc6492SignatureValidatorAbi:()=>Fb,erc6492SignatureValidatorByteCode:()=>f3,erc721Abi:()=>fie,ethAddress:()=>v6,etherUnits:()=>Sfe,extendSchema:()=>zae,extractChain:()=>jae,fallback:()=>G3,formatBlock:()=>qf,formatEther:()=>qh,formatGwei:()=>Pn,formatLog:()=>qn,formatTransaction:()=>jf,formatTransactionReceipt:()=>op,formatTransactionRequest:()=>Bn,formatUnits:()=>pc,fromBlobs:()=>Bfe,fromBytes:()=>zre,fromHex:()=>WU,fromRlp:()=>Wg,getAbiItem:()=>ls,getAddress:()=>Gr,getChainContractAddress:()=>Di,getContract:()=>Aie,getContractAddress:()=>_ae,getContractError:()=>Js,getCreate2Address:()=>jL,getCreateAddress:()=>VL,getEventSelector:()=>Wc,getEventSignature:()=>Pf,getFunctionSelector:()=>va,getFunctionSignature:()=>Pf,getSerializedTransactionType:()=>qT,getTransactionType:()=>Pb,getTypesForEIP712Domain:()=>Zg,gweiUnits:()=>Ife,hashDomain:()=>_3,hashMessage:()=>im,hashStruct:()=>AT,hashTypedData:()=>p6,hexToBigInt:()=>dt,hexToBool:()=>qw,hexToBytes:()=>qt,hexToCompactSignature:()=>pH,hexToNumber:()=>wt,hexToRlp:()=>Hne,hexToSignature:()=>hH,hexToString:()=>bI,http:()=>ry,isAddress:()=>Ft,isAddressEqual:()=>xr,isBytes:()=>I3,isErc6492Signature:()=>IT,isErc8010Signature:()=>zT,isHash:()=>i6,isHex:()=>We,keccak256:()=>Pt,labelhash:()=>J9,maxInt104:()=>ioe,maxInt112:()=>aoe,maxInt120:()=>coe,maxInt128:()=>loe,maxInt136:()=>uoe,maxInt144:()=>doe,maxInt152:()=>foe,maxInt16:()=>Gne,maxInt160:()=>poe,maxInt168:()=>hoe,maxInt176:()=>moe,maxInt184:()=>goe,maxInt192:()=>yoe,maxInt200:()=>woe,maxInt208:()=>boe,maxInt216:()=>xoe,maxInt224:()=>voe,maxInt232:()=>Eoe,maxInt24:()=>Yne,maxInt240:()=>Aoe,maxInt248:()=>Coe,maxInt256:()=>Soe,maxInt32:()=>Jne,maxInt40:()=>Qne,maxInt48:()=>Xne,maxInt56:()=>eoe,maxInt64:()=>toe,maxInt72:()=>roe,maxInt8:()=>Zne,maxInt80:()=>noe,maxInt88:()=>ooe,maxInt96:()=>soe,maxUint104:()=>gse,maxUint112:()=>yse,maxUint120:()=>wse,maxUint128:()=>bse,maxUint136:()=>xse,maxUint144:()=>vse,maxUint152:()=>Ese,maxUint16:()=>sse,maxUint160:()=>Ase,maxUint168:()=>Cse,maxUint176:()=>Sse,maxUint184:()=>Ise,maxUint192:()=>Tse,maxUint200:()=>_se,maxUint208:()=>Pse,maxUint216:()=>Nse,maxUint224:()=>Rse,maxUint232:()=>Ose,maxUint24:()=>ise,maxUint240:()=>Bse,maxUint248:()=>kse,maxUint256:()=>R0,maxUint32:()=>ase,maxUint40:()=>cse,maxUint48:()=>lse,maxUint56:()=>use,maxUint64:()=>dse,maxUint72:()=>fse,maxUint8:()=>ose,maxUint80:()=>pse,maxUint88:()=>hse,maxUint96:()=>mse,minInt104:()=>Moe,minInt112:()=>Hoe,minInt120:()=>$oe,minInt128:()=>Foe,minInt136:()=>zoe,minInt144:()=>Voe,minInt152:()=>joe,minInt16:()=>Toe,minInt160:()=>qoe,minInt168:()=>Woe,minInt176:()=>Koe,minInt184:()=>Zoe,minInt192:()=>Goe,minInt200:()=>Yoe,minInt208:()=>Joe,minInt216:()=>Qoe,minInt224:()=>Xoe,minInt232:()=>ese,minInt24:()=>_oe,minInt240:()=>tse,minInt248:()=>rse,minInt256:()=>nse,minInt32:()=>Poe,minInt40:()=>Noe,minInt48:()=>Roe,minInt56:()=>Ooe,minInt64:()=>Boe,minInt72:()=>koe,minInt8:()=>Ioe,minInt80:()=>Uoe,minInt88:()=>Doe,minInt96:()=>Loe,multicall3Abi:()=>Ui,namehash:()=>Vg,nonceManager:()=>dce,numberToBytes:()=>ZU,numberToHex:()=>oe,offchainLookup:()=>B9,offchainLookupAbiItem:()=>O9,offchainLookupSignature:()=>R9,pad:()=>Zr,padBytes:()=>qU,padHex:()=>cs,parseAbi:()=>Iw,parseAbiItem:()=>Tw,parseAbiParameter:()=>zU,parseAbiParameters:()=>_w,parseCompactSignature:()=>pH,parseErc6492Signature:()=>sle,parseErc8010Signature:()=>ale,parseEther:()=>ble,parseEventLogs:()=>cc,parseGwei:()=>vle,parseSignature:()=>hH,parseTransaction:()=>WT,parseUnits:()=>GT,prepareEncodeFunctionData:()=>TI,presignMessagePrefix:()=>bT,publicActions:()=>l_,recoverAddress:()=>ti,recoverMessageAddress:()=>VT,recoverPublicKey:()=>zI,recoverTransactionAddress:()=>qfe,recoverTypedDataAddress:()=>jT,ripemd160:()=>sce,rpcSchema:()=>Rie,rpcTransactionType:()=>qD,serializeAccessList:()=>qg,serializeCompactSignature:()=>mH,serializeErc6492Signature:()=>lle,serializeErc8010Signature:()=>dle,serializeSignature:()=>W3,serializeTransaction:()=>fT,serializeTypedData:()=>vT,setErrorConfig:()=>cre,setupKzg:()=>Hfe,sha256:()=>KI,shouldThrow:()=>uH,sidecarsToVersionedHashes:()=>Ufe,signatureToCompactSignature:()=>Zfe,signatureToHex:()=>W3,size:()=>gt,slice:()=>vo,sliceBytes:()=>_4,sliceHex:()=>xa,stringToBytes:()=>zo,stringToHex:()=>ec,stringify:()=>bt,testActions:()=>u_,toBlobSidecars:()=>M0,toBlobs:()=>XI,toBytes:()=>un,toCoinType:()=>Lfe,toEventHash:()=>Nf,toEventSelector:()=>Wc,toEventSignature:()=>Pf,toFunctionHash:()=>Nf,toFunctionSelector:()=>va,toFunctionSignature:()=>Pf,toHex:()=>wr,toPrefixedMessage:()=>xT,toRlp:()=>Vo,transactionType:()=>Q4,trim:()=>bn,universalSignatureValidatorAbi:()=>Fb,universalSignatureValidatorByteCode:()=>f3,validateTypedData:()=>f6,verifyHash:()=>ple,verifyMessage:()=>mle,verifyTypedData:()=>yle,walletActions:()=>f_,webSocket:()=>Afe,weiUnits:()=>Tfe,withCache:()=>L9,withRetry:()=>np,withTimeout:()=>sl,zeroAddress:()=>dm,zeroHash:()=>Nce});var R6=b(()=>{l();fg();Cie();q9();nm();Bie();Rue();Hde();yfe();iH();aH();lH();N6();bfe();xfe();Efe();Cfe();So();t_();ST();Vb();jI();YL();_fe();Qr();tc();nt();J4();PL();Ug();ou();C4();yg();rT();jD();Eb();jU();tl();fs();Lf();OI();zn();p_();QL();Pfe();Nfe();zh();Ofe();L4();a3();gL();lc();rc();p3();wL();Cg();us();xL();Tae();Bf();Dg();iD();Zs();Pae();Gs();Bi();t3();r3();GI();ZI();kfe();Dfe();n3();JD();k9();$ae();b3();Vae();qae();K0();Fn();zL();qs();Xa();Fo();Ii();Hh();cD();Xr();mT();Pr();qe();wb();UL();Y9();Mfe();p0();X4();hu();Ab();Qb();rl();gT();Ks();ice();GD();ace();Kw();cce();lce();Ag();uce();fH();$fe();fce();SL();v3();Kb();zfe();T3();P3();XL();NM();Vfe();ile();cle();jfe();w0();RM();VD();Wfe();OM();Kfe();ule();fle();WM();Gfe();JL();hle();gle();wle();so();nl();dT();BM();e9();kM();qL();pT();ET();M4();Ig();z3();xle();Ele();UM()});async function Y3(...e){let t=await fetch(...e);if(!t.ok)throw new Error(`HTTP status code: ${t.status}`,{cause:t});return t}var Li,O6=b(()=>{l();Li=class{constructor({baseUrl:t,clientId:r}){this.baseUrl=t,this.clientId=r}async get({headers:t,signal:r,cache:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"GET",headers:t,signal:r,cache:n})).json()}async getBlob({headers:t,signal:r,...n}){let o=this.createUrl(n);return(await Y3(o,{method:"GET",headers:t,signal:r})).blob()}async post({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"POST",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}async put({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"PUT",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}async delete({body:t,headers:r,signal:n,...o}){let s=this.createUrl(o);return(await Y3(s,{method:"DELETE",headers:r,body:t?JSON.stringify(t):void 0,signal:n})).json()}createUrl({path:t,params:r}){let n=new URL(t,this.baseUrl);return r&&Object.entries(r).forEach(([o,s])=>{s&&n.searchParams.append(o,s)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:t,...r}){let n=this.createUrl(r);return navigator.sendBeacon(n.toString(),t?JSON.stringify(t):void 0)}}});var J3,gH=b(()=>{l();Un();ha();$n();J3={getFeatureValue(e,t){let r=t?.[e];return r===void 0?Ye.DEFAULT_FEATURES[e]:r},filterSocialsByPlatform(e){if(!e||!e.length)return e;let t=e;return se.isTelegram()&&(se.isIos()&&(t=t.filter(r=>r!=="google")),se.isMac()&&(t=t.filter(r=>r!=="x")),se.isAndroid()&&(t=t.filter(r=>!["facebook","x"].includes(r)))),se.isMobile()&&(t=t.filter(r=>r!=="facebook")),t},isSocialsEnabled(){return Array.isArray(Y.state.features?.socials)&&Y.state.features?.socials.length>0||Array.isArray(Y.state.remoteFeatures?.socials)&&Y.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(Y.state.features?.email||Y.state.remoteFeatures?.email)}}});var Ze,Y,Un=b(()=>{l();Lr();Hn();ha();$n();gH();Ze=rt({features:Ye.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ye.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),Y={state:Ze,subscribeKey(e,t){return Tt(Ze,e,t)},setOptions(e){Object.assign(Ze,e)},setRemoteFeatures(e){if(!e)return;let t={...Ze.remoteFeatures,...e};Ze.remoteFeatures=t,Ze.remoteFeatures?.socials&&(Ze.remoteFeatures.socials=J3.filterSocialsByPlatform(Ze.remoteFeatures.socials)),Ze.features?.pay&&(Ze.remoteFeatures.email=!1,Ze.remoteFeatures.socials=!1)},setFeatures(e){if(!e)return;Ze.features||(Ze.features=Ye.DEFAULT_FEATURES);let t={...Ze.features,...e};Ze.features=t,Ze.features?.pay&&Ze.remoteFeatures&&(Ze.remoteFeatures.email=!1,Ze.remoteFeatures.socials=!1)},setProjectId(e){Ze.projectId=e},setCustomRpcUrls(e){Ze.customRpcUrls=e},setAllWallets(e){Ze.allWallets=e},setIncludeWalletIds(e){Ze.includeWalletIds=e},setExcludeWalletIds(e){Ze.excludeWalletIds=e},setFeaturedWalletIds(e){Ze.featuredWalletIds=e},setTokens(e){Ze.tokens=e},setTermsConditionsUrl(e){Ze.termsConditionsUrl=e},setPrivacyPolicyUrl(e){Ze.privacyPolicyUrl=e},setCustomWallets(e){Ze.customWallets=e},setIsSiweEnabled(e){Ze.isSiweEnabled=e},setIsUniversalProvider(e){Ze.isUniversalProvider=e},setSdkVersion(e){Ze.sdkVersion=e},setMetadata(e){Ze.metadata=e},setDisableAppend(e){Ze.disableAppend=e},setEIP6963Enabled(e){Ze.enableEIP6963=e},setDebug(e){Ze.debug=e},setEnableWalletGuide(e){Ze.enableWalletGuide=e},setEnableAuthLogger(e){Ze.enableAuthLogger=e},setEnableWallets(e){Ze.enableWallets=e},setPreferUniversalLinks(e){Ze.experimental_preferUniversalLinks=e},setSIWX(e){if(e)for(let[t,r]of Object.entries(Ye.SIWX_DEFAULTS))e[t]??=r;Ze.siwx=e},setConnectMethodsOrder(e){Ze.features={...Ze.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){Ze.features={...Ze.features,walletFeaturesOrder:e}},setSocialsOrder(e){Ze.remoteFeatures={...Ze.remoteFeatures,socials:e}},setCollapseWallets(e){Ze.features={...Ze.features,collapseWallets:e}},setEnableEmbedded(e){Ze.enableEmbedded=e},setAllowUnsupportedChain(e){Ze.allowUnsupportedChain=e},setManualWCControl(e){Ze.manualWCControl=e},setEnableNetworkSwitch(e){Ze.enableNetworkSwitch=e},setEnableMobileFullScreen(e){Ze.enableMobileFullScreen=se.isMobile()&&e},setEnableReconnect(e){Ze.enableReconnect=e},setCoinbasePreference(e){Ze.coinbasePreference=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([t,r])=>{r&&(Ze.defaultAccountTypes[t]=r)})},setUniversalProviderConfigOverride(e){Ze.universalProviderConfigOverride=e},getUniversalProviderConfigOverride(){return Ze.universalProviderConfigOverride},getSnapshot(){return Kl(Ze)}}});var ny,ao,lHe,Je,hm=b(()=>{l();Lr();Hn();$n();ny=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ao=rt({...ny}),lHe={state:ao,subscribeKey(e,t){return Tt(ao,e,t)},showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){let t=se.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){ao.message=ny.message,ao.variant=ny.variant,ao.svg=ny.svg,ao.open=ny.open,ao.autoClose=ny.autoClose},_showMessage({message:e,svg:t,variant:r="success",autoClose:n=ny.autoClose}){ao.open?(ao.open=!1,setTimeout(()=>{ao.message=e,ao.variant=r,ao.svg=t,ao.open=!0,ao.autoClose=n},150)):(ao.message=e,ao.variant=r,ao.svg=t,ao.open=!0,ao.autoClose=n)}},Je=lHe});var uHe,Jfe,si,ze,lp=b(()=>{l();Lr();ha();$n();O6();ma();$r();Un();hm();uHe={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Jfe=se.getBlockchainApiUrl(),si=rt({clientId:null,api:new Li({baseUrl:Jfe,clientId:null}),supportedChains:{http:[],ws:[]}}),ze={state:si,async get(e){let{st:t,sv:r}=ze.getSdkProperties(),n=Y.state.projectId,o={...e.params||{},st:t,sv:r,projectId:n};return si.api.get({...e,params:o})},getSdkProperties(){let{sdkType:e,sdkVersion:t}=Y.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{si.supportedChains.http.length||await ze.getSupportedNetworks()}catch{return!1}return si.supportedChains.http.includes(e)},async getSupportedNetworks(){try{let e=await ze.get({path:"v1/supported-chains"});return si.supportedChains=e,e}catch{return si.supportedChains}},async fetchIdentity({address:e}){let t=de.getIdentityFromCacheForAddress(e);if(t)return t;let r=await ze.get({path:`/v1/identity/${e}`,params:{sender:$.state.activeCaipAddress?se.getPlainAddress($.state.activeCaipAddress):void 0}});return de.updateIdentityCache({address:e,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:e,cursor:t,signal:r,cache:n,chainId:o}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};let i=de.getTransactionsCacheForAddress({address:e,chainId:o});if(i)return i;let a=await ze.get({path:`/v1/account/${e}/history`,params:{cursor:t,chainId:o},signal:r,cache:n});return de.updateTransactionsCache({address:e,chainId:o,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:e,userAddress:t,from:r,to:n,gasPrice:o}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:r,to:n,gasPrice:o}}):{quotes:[]}},async fetchSwapTokens({chainId:e}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]}},async getAddressBalance({caipNetworkId:e,address:t}){return si.api.post({path:`/v1?chainId=${e}&projectId=${Y.state.projectId}`,body:{id:"1",jsonrpc:"2.0",method:"getAddressBalance",params:{address:t}}}).then(r=>r.result)},async fetchTokenPrice({addresses:e,caipNetworkId:t=$.state.activeCaipNetwork?.caipNetworkId}){if(!await ze.isNetworkSupported(t))return{fungibles:[]};let n=de.getTokenPriceCacheForAddresses(e);if(n)return n;let o=await si.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:Y.state.projectId},headers:{"Content-Type":"application/json"}});return de.updateTokenPriceCache({addresses:e,timestamp:Date.now(),tokenPrice:o}),o},async fetchSwapAllowance({tokenAddress:e,userAddress:t}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:e}){let{st:t,sv:r}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return ze.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:t,sv:r}})},async generateSwapCalldata({amount:e,from:t,to:r,userAddress:n,disableEstimate:o}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return si.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:Ye.CONVERT_SLIPPAGE_TOLERANCE},projectId:Y.state.projectId,from:t,to:r,userAddress:n,disableEstimate:o}})},async generateApproveCalldata({from:e,to:t,userAddress:r}){let{st:n,sv:o}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ze.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:r,from:e,to:t,st:n,sv:o}})},async getBalance(e,t,r){let{st:n,sv:o}=ze.getSdkProperties();if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return Je.showError("Token Balance Unavailable"),{balances:[]};let i=`${t}:${e}`,a=de.getBalanceCacheForCaipAddress(i);if(a)return a;let c=await ze.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:r,st:n,sv:o}});return de.updateBalanceCache({caipAddress:i,balance:c,timestamp:Date.now()}),c},async lookupEnsName(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:e}){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return[];let r=$.getAccountData()?.address;return ze.get({path:`/v1/profile/reverse/${e}`,params:{sender:r,apiVersion:"2"}})},async getEnsNameSuggestions(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:e,address:t,message:r,signature:n}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?si.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:r,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:e,partnerUserId:t,defaultNetwork:r,purchaseAmount:n,paymentAmount:o}){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?(await si.api.post({path:"/v1/generators/onrampurl",params:{projectId:Y.state.projectId},body:{destinationWallets:e,defaultNetwork:r,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:o}})).url:""},async getOnrampOptions(){if(!await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await ze.get({path:"/v1/onramp/options"})}catch{return uHe}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:r,network:n}){try{return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?await si.api.post({path:"/v1/onramp/quote",params:{projectId:Y.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:r,network:n}}):null}catch{return{networkFee:{amount:r,currency:t.id},paymentSubtotal:{amount:r,currency:t.id},paymentTotal:{amount:r,currency:t.id},purchaseAmount:{amount:r,currency:t.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(e){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?ze.get({path:`/v1/sessions/${e}`}):[]},async revokeSmartSession(e,t,r){return await ze.isNetworkSupported($.state.activeCaipNetwork?.caipNetworkId)?si.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:Y.state.projectId},body:{pci:t,signature:r}}):{success:!1}},setClientId(e){si.clientId=e,si.api=new Li({baseUrl:Jfe,clientId:e})}}});var mm=b(()=>{l();g4()});var dHe,fHe,pHe,hHe,gm,Qfe,Xfe=b(()=>{l();Lr();Hn();$n();O6();Un();dHe=Object.freeze({enabled:!0,events:[]}),fHe=new Li({baseUrl:se.getAnalyticsUrl(),clientId:null}),pHe=5,hHe=60*1e3,gm=rt({...dHe}),Qfe={state:gm,subscribeKey(e,t){return Tt(gm,e,t)},async sendError(e,t){if(!gm.enabled)return;let r=Date.now();if(gm.events.filter(s=>{let i=new Date(s.properties.timestamp||"").getTime();return r-i=pHe)return;let o={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:new Date().toISOString()}};gm.events.push(o);try{if(typeof window>"u")return;let{projectId:s,sdkType:i,sdkVersion:a}=Y.state;await fHe.post({path:"/e",params:{projectId:s,st:i,sv:a||"html-wagmi-4.2.2"},body:{eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){gm.enabled=!0},disable(){gm.enabled=!1},clearEvents(){gm.events=[]}}});function epe(e,t){let r="";try{e instanceof Error?r=e.message:typeof e=="string"?r=e:typeof e=="object"&&e!==null?Object.keys(e).length===0?r="Unknown error":r=e?.message||JSON.stringify(e):r=String(e)}catch(o){r="Unknown error",console.error("Error parsing error message",o)}let n=e instanceof hc?e:new hc(r,t,e);throw Qfe.sendError(n,n.category),n}function vr(e,t="INTERNAL_SDK_ERROR"){let r={};return Object.keys(e).forEach(n=>{let o=e[n];if(typeof o=="function"){let s=o;o.constructor.name==="AsyncFunction"?s=async(...i)=>{try{return await o(...i)}catch(a){return epe(a,t)}}:s=(...i)=>{try{return o(...i)}catch(a){return epe(a,t)}},r[n]=s}else r[n]=o}),r}var hc,gs=b(()=>{l();Xfe();hc=class e extends Error{constructor(t,r,n){super(t),this.originalName="AppKitError",this.name="AppKitError",this.category=r,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,e.prototype);let o=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){let s=n.stack,i=s.indexOf(` `);if(i>-1){let a=s.substring(i+1);this.stack=`${this.name}: ${this.message} -${a}`,o=!0}}o||(Error.captureStackTrace?Error.captureStackTrace(this,e):this.stack||(this.stack=`${this.name}: ${this.message}`))}}});var Pa,mHe,Wn,y_=b(()=>{l();Lr();Hn();gs();Pa=rt({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),mHe={state:Pa,subscribeNetworkImages(e){return Dt(Pa.networkImages,()=>e(Pa.networkImages))},subscribeKey(e,t){return Tt(Pa,e,t)},subscribe(e){return Dt(Pa,()=>e(Pa))},setWalletImage(e,t){Pa.walletImages[e]=t},setNetworkImage(e,t){Pa.networkImages[e]=t},setChainImage(e,t){Pa.chainImages[e]=t},setConnectorImage(e,t){Pa.connectorImages={...Pa.connectorImages,[e]:t}},setTokenImage(e,t){Pa.tokenImages[e]=t},setCurrencyImage(e,t){Pa.currencyImages[e]=t}},Wn=vr(mHe)});var tpe,B6,St,yH=b(()=>{l();Lr();ut();Cu();y_();Un();tpe={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:"",ton:"20f673c0-095e-49b2-07cf-eb5049dcf600"},B6=rt({networkImagePromises:{},tokenImagePromises:{}}),St={async fetchWalletImage(e){if(e)return await ge._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;let t=this.getNetworkImageById(e);return t||(B6.networkImagePromises[e]||(B6.networkImagePromises[e]=ge._fetchNetworkImage(e)),await B6.networkImagePromises[e],this.getNetworkImageById(e))},async fetchTokenImage(e){if(e)return B6.tokenImagePromises[e]||(B6.tokenImagePromises[e]=ge._fetchTokenImage(e)),await B6.tokenImagePromises[e],this.getTokenImage(e)},getWalletImageById(e){if(e)return Wn.state.walletImages[e]},getWalletImage(e){if(e?.image_url)return e?.image_url;if(e?.image_id)return Wn.state.walletImages[e.image_id]},getNetworkImage(e){if(e?.assets?.imageUrl)return e?.assets?.imageUrl;if(e?.assets?.imageId)return Wn.state.networkImages[e.assets.imageId]},getNetworkImageById(e){if(e)return Wn.state.networkImages[e]},getConnectorImage(e){if(e?.imageUrl)return e.imageUrl;if(e?.info?.icon)return e.info.icon;if(e?.imageId)return Wn.state.connectorImages[e.imageId]},getChainImage(e){return Wn.state.networkImages[tpe[e]]},getTokenImage(e){if(e)return Wn.state.tokenImages[e]},getWalletImageUrl(e){if(!e)return"";let{projectId:t,sdkType:r,sdkVersion:n}=Y.state,o=new URL(`${Z.W3M_API_URL}/getWalletImage/${e}`);return o.searchParams.set("projectId",t),o.searchParams.set("st",r),o.searchParams.set("sv",n),o.toString()},getAssetImageUrl(e){if(!e)return"";let{projectId:t,sdkType:r,sdkVersion:n}=Y.state,o=new URL(`${Z.W3M_API_URL}/public/getAssetImage/${e}`);return o.searchParams.set("projectId",t),o.searchParams.set("st",r),o.searchParams.set("sv",n),o.toString()},getChainNamespaceImageUrl(e){return this.getAssetImageUrl(tpe[e])},async getImageByToken(e,t){if(e==="native"){let n=Z.NATIVE_IMAGE_IDS_BY_NAMESPACE[t]??null;return n?St.fetchNetworkImage(n):void 0}let[,r]=Object.entries(Z.TOKEN_SYMBOLS_BY_ADDRESS).find(([n])=>n.toLowerCase()===e.toLowerCase())??[];if(r)return St.fetchTokenImage(r)}}});var Na,rpe,wH=b(()=>{l();ut();$r();Na={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},rpe={handleMobileDeeplinkRedirect(e,t){let r=window.location.href,n=encodeURIComponent(r);if(e===Na.PHANTOM.id&&!("phantom"in window)){let o=r.startsWith("https")?"https":"http",s=r.split("/")[2],i=encodeURIComponent(`${o}://${s}`);window.location.href=`${Na.PHANTOM.url}/ul/browse/${n}?ref=${i}`}if(e===Na.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Na.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),t===Z.CHAIN.SOLANA&&e===Na.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Na.COINBASE.url}/dapp?cb_url=${n}`),t===Z.CHAIN.BITCOIN&&e===Na.BINANCE.id&&!("binancew3w"in window)){let o=$.state.activeCaipNetwork,s=window.btoa("/pages/browser/index"),i=window.btoa(`url=${n}&defaultChainId=${o?.id??1}`),a=new URL(Na.BINANCE.deeplink);a.searchParams.set("appId",Na.BINANCE.appId),a.searchParams.set("startPagePath",s),a.searchParams.set("startPageQuery",i);let c=new URL(Na.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}}});var gHe,yHe,wHe,bHe,npe,En,Ae,mc=b(()=>{l();Lr();$n();O6();$r();Un();gHe=se.getAnalyticsUrl(),yHe=new Di({baseUrl:gHe,clientId:null}),wHe=["MODAL_CREATED"],bHe=45,npe=1e3*10,En=rt({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),Ae={state:En,subscribe(e){return Dt(En,()=>e(En))},getSdkProperties(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t,sv:r||"html-wagmi-4.2.2"}},shouldFlushEvents(){let e=JSON.stringify(En.pendingEvents).length/1024>bHe,t=En.lastFlush+npe"u")return;let r=$.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t,properties:{..."properties"in e.data?e.data.properties:{},caipNetworkId:r}}}),En.reportedErrors.FORBIDDEN=!1,Ae.shouldFlushEvents()&&Ae._submitPendingEvents()}catch(t){console.warn("_setPendingEvent",t)}},sendEvent(e){En.timestamp=Date.now(),En.data=e;let t=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];(Y.state.features?.analytics||t.includes(e.event))&&Ae._setPendingEvent(En),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(e){En.walletImpressions.push(e)},_transformPendingEventsForBatch(e){try{return e.filter(t=>t.props.event!=="WALLET_IMPRESSION_V2")}catch{return e}},_submitPendingEvents(){if(En.lastFlush=Date.now(),!(En.pendingEvents.length===0&&En.walletImpressions.length===0))try{let e=Ae._transformPendingEventsForBatch(En.pendingEvents);En.walletImpressions.length&&e.push({eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...En.walletImpressions]}}),yHe.sendBeacon({path:"/batch",params:Ae.getSdkProperties(),body:e}),En.reportedErrors.FORBIDDEN=!1,En.pendingEvents=[],En.walletImpressions=[]}catch{En.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){En.subscribedToVisibilityChange||typeof document>"u"||(En.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",()=>{document.visibilityState==="hidden"&&Ae._submitPendingEvents()}),document?.addEventListener?.("freeze",()=>{Ae._submitPendingEvents()}),window?.addEventListener?.("pagehide",()=>{Ae._submitPendingEvents()}),setInterval(()=>{Ae._submitPendingEvents()},npe))}}});var xHe,ii,vHe,ope,EHe,mt,ge,Cu=b(()=>{l();Lr();Hn();ut();yH();$n();O6();wH();ma();y_();$r();To();mc();Un();xHe=se.getApiUrl(),ii=new Di({baseUrl:xHe,clientId:null}),vHe=40,ope=4,EHe=20,mt=rt({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[],plan:{tier:"none",hasExceededUsageLimit:!1,limits:{isAboveRpcLimit:!1,isAboveMauLimit:!1}}}),ge={state:mt,subscribeKey(e,t){return Tt(mt,e,t)},_getSdkProperties(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t||"appkit",sv:r||"html-wagmi-4.2.2"}},_filterOutExtensions(e){return Y.state.isUniversalProvider?e.filter(t=>!!(t.mobile_link||t.desktop_link||t.webapp_link)):e},async _fetchWalletImage(e){let t=`${ii.baseUrl}/getWalletImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setWalletImage(e,URL.createObjectURL(r))},async _fetchNetworkImage(e){let t=`${ii.baseUrl}/public/getAssetImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setNetworkImage(e,URL.createObjectURL(r))},async _fetchConnectorImage(e){let t=`${ii.baseUrl}/public/getAssetImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setConnectorImage(e,URL.createObjectURL(r))},async _fetchCurrencyImage(e){let t=`${ii.baseUrl}/public/getCurrencyImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setCurrencyImage(e,URL.createObjectURL(r))},async _fetchTokenImage(e){let t=`${ii.baseUrl}/public/getTokenImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setTokenImage(e,URL.createObjectURL(r))},_filterWalletsByPlatform(e){let t=e.length,r=se.isMobile()?e?.filter(o=>o.mobile_link||o.webapp_link?!0:Object.values(Na).map(i=>i.id).includes(o.id)):e,n=t-r.length;return{filteredWallets:r,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await ii.get({path:"/appkit/v1/config",params:ge._getSdkProperties()})).features},async fetchUsage(){try{let e=await ii.get({path:"/appkit/v1/project-limits",params:ge._getSdkProperties()}),{tier:t,isAboveMauLimit:r,isAboveRpcLimit:n}=e.planLimits,o=t==="starter",s=r||n;ge.state.plan={tier:t,hasExceededUsageLimit:o&&s,limits:{isAboveRpcLimit:n,isAboveMauLimit:r}}}catch(e){console.warn("Failed to fetch usage",e)}},async fetchAllowedOrigins(){try{let{allowedOrigins:e}=await ii.get({path:"/projects/v1/origins",params:ge._getSdkProperties()});return e}catch(e){if(e instanceof Error&&e.cause instanceof Response){let t=e.cause.status;if(t===Z.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:e});if(t>=Z.HTTP_STATUS_CODES.SERVER_ERROR&&t<600)throw new Error("SERVER_ERROR",{cause:e});return[]}return[]}},async fetchNetworkImages(){let t=$.getAllRequestedCaipNetworks()?.map(({assets:r})=>r?.imageId).filter(Boolean).filter(r=>!St.getNetworkImageById(r));t&&await Promise.allSettled(t.map(r=>ge._fetchNetworkImage(r)))},async fetchConnectorImages(){let{connectors:e}=re.state,t=e.map(({imageId:r})=>r).filter(Boolean);await Promise.allSettled(t.map(r=>ge._fetchConnectorImage(r)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(t=>ge._fetchCurrencyImage(t)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(t=>ge._fetchTokenImage(t)))},async fetchWallets(e){let t=e.exclude??[];ge._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(Na).map(i=>i.id));let n=await ii.get({path:"/getWallets",params:{...ge._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}}),{filteredWallets:o,mobileFilteredOutWalletsLength:s}=ge._filterWalletsByPlatform(n?.data);return{data:o||[],count:n?.count,mobileFilteredOutWalletsLength:s}},async prefetchWalletRanks(){let e=re.state.connectors;if(!e?.length)return;let t={page:1,entries:20,badge:"certified"};if(t.names=e.map(o=>o.name).join(","),$.state.activeChain===Z.CHAIN.EVM){let o=[...e.flatMap(s=>s.connectors?.map(i=>i.info?.rdns)||[]),...e.map(s=>s.info?.rdns)].filter(s=>typeof s=="string"&&s.length>0);o.length&&(t.rdns=o.join(","))}let{data:r}=await ge.fetchWallets(t);mt.explorerWallets=r,re.extendConnectorsWithExplorerWallets(r);let n=$.getRequestedCaipNetworkIds().join(",");mt.explorerFilteredWallets=r.filter(o=>o.chains?.some(s=>n.includes(s)))},async fetchFeaturedWallets(){let{featuredWalletIds:e}=Y.state;if(e?.length){let t={...ge._getSdkProperties(),page:1,entries:e?.length??ope,include:e},{data:r}=await ge.fetchWallets(t),n=[...r].sort((s,i)=>e.indexOf(s.id)-e.indexOf(i.id)),o=n.map(s=>s.image_id).filter(Boolean);await Promise.allSettled(o.map(s=>ge._fetchWalletImage(s))),mt.featured=n,mt.allFeatured=n}},async fetchRecommendedWallets(){try{mt.isFetchingRecommendedWallets=!0;let{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:r}=Y.state,n=[...t??[],...r??[]].filter(Boolean),o=$.getRequestedCaipNetworkIds().join(","),s={page:1,entries:ope,include:e,exclude:n,chains:o},{data:i,count:a}=await ge.fetchWallets(s),c=de.getRecentWallets(),u=i.map(f=>f.image_id).filter(Boolean),d=c.map(f=>f.image_id).filter(Boolean);await Promise.allSettled([...u,...d].map(f=>ge._fetchWalletImage(f))),mt.recommended=i,mt.allRecommended=i,mt.count=a??0}catch{}finally{mt.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){let{includeWalletIds:t,excludeWalletIds:r,featuredWalletIds:n}=Y.state,o=$.getRequestedCaipNetworkIds().join(","),s=[...mt.recommended.map(({id:f})=>f),...r??[],...n??[]].filter(Boolean),i={page:e,entries:vHe,include:t,exclude:s,chains:o},{data:a,count:c,mobileFilteredOutWalletsLength:u}=await ge.fetchWallets(i);mt.mobileFilteredOutWalletsLength=u+(mt.mobileFilteredOutWalletsLength??0);let d=a.slice(0,EHe).map(f=>f.image_id).filter(Boolean);await Promise.allSettled(d.map(f=>ge._fetchWalletImage(f))),mt.wallets=se.uniqueBy([...mt.wallets,...ge._filterOutExtensions(a)],"id").filter(f=>f.chains?.some(p=>o.includes(p))),mt.count=c>mt.count?c:mt.count,mt.page=e},async initializeExcludedWallets({ids:e}){let t={page:1,entries:e.length,include:e},{data:r}=await ge.fetchWallets(t);r&&r.forEach(n=>{mt.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:e,badge:t}){let{includeWalletIds:r,excludeWalletIds:n}=Y.state,o=$.getRequestedCaipNetworkIds().join(",");mt.search=[];let s={page:1,entries:100,search:e?.trim(),badge_type:t,include:r,exclude:n,chains:o},{data:i}=await ge.fetchWallets(s);Ae.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});let a=i.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>ge._fetchWalletImage(c)),se.wait(300)]),mt.search=ge._filterOutExtensions(i)},initPromise(e,t){let r=mt.promises[e];return r||(mt.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:r=!0,fetchNetworkImages:n=!0,fetchWalletRanks:o=!0}={}){let s=[e&&ge.initPromise("connectorImages",ge.fetchConnectorImages),t&&ge.initPromise("featuredWallets",ge.fetchFeaturedWallets),r&&ge.initPromise("recommendedWallets",ge.fetchRecommendedWallets),n&&ge.initPromise("networkImages",ge.fetchNetworkImages),o&&ge.initPromise("walletRanks",ge.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(s)},prefetchAnalyticsConfig(){Y.state.features?.analytics&&ge.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{let{isAnalyticsEnabled:e}=await ii.get({path:"/getAnalyticsConfig",params:ge._getSdkProperties()});Y.setFeatures({analytics:e})}catch{Y.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length){mt.featured=mt.allFeatured,mt.recommended=mt.allRecommended;return}let t=$.getRequestedCaipNetworkIds().join(",");mt.featured=mt.allFeatured.filter(r=>r.chains?.some(n=>t.includes(n))),mt.recommended=mt.allRecommended.filter(r=>r.chains?.some(n=>t.includes(n))),mt.filteredWallets=mt.wallets.filter(r=>r.chains?.some(n=>t.includes(n)))},clearFilterByNamespaces(){mt.filteredWallets=[]},setFilterByNamespace(e){if(!e){mt.featured=mt.allFeatured,mt.recommended=mt.allRecommended;return}let t=$.getRequestedCaipNetworkIds().join(",");mt.featured=mt.allFeatured.filter(r=>r.chains?.some(n=>t.includes(n))),mt.recommended=mt.allRecommended.filter(r=>r.chains?.some(n=>t.includes(n))),mt.filteredWallets=mt.wallets.filter(r=>r.chains?.some(n=>t.includes(n)))}}});var ys,bH=b(()=>{l();ut();Cu();ai();To();Un();w_();ha();$n();ma();ys={filterOutDuplicatesByRDNS(e){let t=Y.state.enableEIP6963?re.state.connectors:[],r=de.getRecentWallets(),n=t.map(a=>a.info?.rdns).filter(Boolean),o=r.map(a=>a.rdns).filter(Boolean),s=n.concat(o);if(s.includes("io.metamask.mobile")&&se.isMobile()){let a=s.indexOf("io.metamask.mobile");s[a]="io.metamask"}return e.filter(a=>!(a?.rdns&&s.includes(String(a.rdns))||!a?.rdns&&t.some(u=>u.name===a.name)))},filterOutDuplicatesByIds(e){let t=re.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"||a.type==="MULTI_CHAIN"),r=de.getRecentWallets(),n=t.map(a=>a.explorerId||a.explorerWallet?.id||a.id),o=r.map(a=>a.id),s=n.concat(o);return e.filter(a=>!s.includes(a?.id))},filterOutDuplicateWallets(e){let t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){let{connectors:t}=re.state,{featuredWalletIds:r}=Y.state,n=t.filter(i=>i.type==="ANNOUNCED").reduce((i,a)=>(a.info?.rdns&&(i[a.info.rdns]=!0),i),{});return e.map(i=>({...i,installed:!!i.rdns&&!!n[i.rdns??""]})).sort((i,a)=>{let c=Number(a.installed)-Number(i.installed);if(c!==0)return c;if(r?.length){let u=r.indexOf(i.id),d=r.indexOf(a.id);if(u!==-1&&d!==-1)return u-d;if(u!==-1)return-1;if(d!==-1)return 1}return 0})},getConnectOrderMethod(e,t){let r=e?.connectMethodsOrder||Y.state.features?.connectMethodsOrder,n=t||re.state.connectors;if(r)return r;let{injected:o,announced:s}=Dn.getConnectorsByType(n,ge.state.recommended,ge.state.featured),i=o.filter(Dn.showConnector),a=s.filter(Dn.showConnector);return i.length||a.length?["wallet","email","social"]:Ye.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){let t=!!e.rdns&&ge.state.excludedWallets.some(n=>n.rdns===e.rdns),r=!!e.name&&ge.state.excludedWallets.some(n=>l4.isLowerCaseMatch(n.name,e.name));return t||r},markWalletsWithDisplayIndex(e){return e.map((t,r)=>({...t,display_index:r}))},filterWalletsByWcSupport(e){return ee.state.wcBasic?e.filter(t=>t.supports_wc):se.isMobile()?e.filter(t=>t.supports_wc||Ye.MANDATORY_WALLET_IDS_ON_MOBILE.includes(t.id)):e},getWalletConnectWallets(e){let t=[...ge.state.featured,...ge.state.recommended];ge.state.filteredWallets?.length>0?t.push(...ge.state.filteredWallets):t.push(...e);let r=se.uniqueBy(t,"id"),n=ys.markWalletsAsInstalled(r),o=ys.filterWalletsByWcSupport(n);return ys.markWalletsWithDisplayIndex(o)}}});var Dn,w_=b(()=>{l();ut();Cu();$r();ai();To();Un();$n();gH();ma();bH();Dn={getConnectorsByType(e,t,r){let{customWallets:n}=Y.state,o=de.getRecentWallets(),s=ys.filterOutDuplicateWallets(t),i=ys.filterOutDuplicateWallets(r),a=e.filter(f=>f.type==="MULTI_CHAIN"),c=e.filter(f=>f.type==="ANNOUNCED"),u=e.filter(f=>f.type==="INJECTED"),d=e.filter(f=>f.type==="EXTERNAL");return{custom:n,recent:o,external:d,multiChain:a,announced:c,injected:u,recommended:s,featured:i}},showConnector(e){let t=e.info?.rdns,r=!!t&&ge.state.excludedWallets.some(o=>!!o.rdns&&o.rdns===t),n=!!e.name&&ge.state.excludedWallets.some(o=>l4.isLowerCaseMatch(o.name,e.name));return!(e.type==="INJECTED"&&(e.name==="Browser Wallet"&&(!se.isMobile()||se.isMobile()&&!t&&!ee.checkInstalled())||r||n)||(e.type==="ANNOUNCED"||e.type==="EXTERNAL")&&(r||n))},getIsConnectedWithWC(){return Array.from($.state.chains.values()).some(r=>re.getConnectorId(r.namespace)===Z.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:e,featured:t,custom:r,recent:n,announced:o,injected:s,multiChain:i,external:a,overriddenConnectors:c=Y.state.features?.connectorTypeOrder??[]}){let d=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...s,...o,...i].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:r&&r.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter(y=>y.isEnabled),f=new Set(d.map(y=>y.type)),p=c.filter(y=>f.has(y)).map(y=>({type:y,isEnabled:!0})),h=d.filter(({type:y})=>!p.some(({type:x})=>x===y));return Array.from(new Set([...p,...h].map(({type:y})=>y)))},sortConnectorsByExplorerWallet(e){return[...e].sort((t,r)=>t.explorerWallet&&r.explorerWallet?(t.explorerWallet.order??0)-(r.explorerWallet.order??0):t.explorerWallet?-1:r.explorerWallet?1:0)},getPriority(e){return e.id===Z.CONNECTOR_ID.BASE_ACCOUNT?0:e.id===Z.CONNECTOR_ID.COINBASE||e.id===Z.CONNECTOR_ID.COINBASE_SDK?1:2},sortConnectorsByPriority(e){return[...e].sort((t,r)=>Dn.getPriority(t)-Dn.getPriority(r))},getAuthName({email:e,socialUsername:t,socialProvider:r}){return t?r&&r==="discord"&&t.endsWith("0")?t.slice(0,-1):t:e.length>30?`${e.slice(0,-3)}...`:e},async fetchProviderData(e){try{if(e.name==="Browser Wallet"&&!se.isMobile())return{accounts:[],chainId:void 0};if(e.id===Z.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};let[t,r]=await Promise.all([e.provider?.request({method:"eth_accounts"}),e.provider?.request({method:"eth_chainId"}).then(n=>Number(n))]);return{accounts:t,chainId:r}}catch(t){return console.warn(`Failed to fetch provider data for ${e.name}`,t),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(e){let t=de.getRecentWallets(),r=re.state.connectors.map(i=>i.info?.rdns).filter(Boolean),n=t.map(i=>i.rdns).filter(Boolean),o=r.concat(n);if(o.includes("io.metamask.mobile")&&se.isMobile()){let i=o.indexOf("io.metamask.mobile");o[i]="io.metamask"}return e.filter(i=>!o.includes(String(i?.rdns)))},hasWalletConnector(e){return re.state.connectors.some(t=>t.id===e.id||t.name===e.name)},isWalletCompatibleWithCurrentChain(e){let t=$.state.activeChain;return t&&e.chains?e.chains.some(r=>{let n=r.split(":")[0];return t===n}):!0},getFilteredRecentWallets(){return de.getRecentWallets().filter(r=>!ys.isExcluded(r)).filter(r=>!this.hasWalletConnector(r)).filter(r=>this.isWalletCompatibleWithCurrentChain(r))},getCappedRecommendedWallets(e){let{connectors:t}=re.state,{customWallets:r,featuredWalletIds:n}=Y.state,o=t.find(T=>T.id==="walletConnect"),s=t.filter(T=>T.type==="INJECTED"||T.type==="ANNOUNCED"||T.type==="MULTI_CHAIN");if(!o&&!s.length&&!r?.length)return[];let i=J3.isEmailEnabled(),a=J3.isSocialsEnabled(),c=s.filter(T=>T.name!=="Browser Wallet"&&T.name!=="WalletConnect"),u=n?.length||0,d=r?.length||0,f=c.length||0,p=i?1:0,h=a?1:0,y=u+d+f+p+h,x=Math.max(0,4-y);return x<=0?[]:ys.filterOutDuplicateWallets(e).slice(0,x)},processConnectorsByType(e,t=!0){let r=Dn.sortConnectorsByExplorerWallet([...e]);return t?r.filter(Dn.showConnector):r},connectorList(){let e=Dn.getConnectorsByType(re.state.connectors,ge.state.recommended,ge.state.featured),t=this.processConnectorsByType(e.announced.filter(h=>h.id!=="walletConnect")),r=this.processConnectorsByType(e.injected),n=this.processConnectorsByType(e.multiChain.filter(h=>h.name!=="WalletConnect"),!1),o=e.custom,s=e.recent,i=this.processConnectorsByType(e.external.filter(h=>h.id!==Z.CONNECTOR_ID.COINBASE_SDK&&h.id!==Z.CONNECTOR_ID.BASE_ACCOUNT)),a=e.recommended,c=e.featured,u=Dn.getConnectorTypeOrder({custom:o,recent:s,announced:t,injected:r,multiChain:n,recommended:a,featured:c,external:i}),d=re.state.connectors.find(h=>h.id==="walletConnect"),f=se.isMobile(),p=[];for(let h of u)switch(h){case"walletConnect":{!f&&d&&p.push({kind:"connector",subtype:"walletConnect",connector:d});break}case"recent":{Dn.getFilteredRecentWallets().forEach(w=>p.push({kind:"wallet",subtype:"recent",wallet:w}));break}case"injected":{n.forEach(y=>p.push({kind:"connector",subtype:"multiChain",connector:y})),t.forEach(y=>p.push({kind:"connector",subtype:"announced",connector:y})),r.forEach(y=>p.push({kind:"connector",subtype:"injected",connector:y}));break}case"featured":{c.forEach(y=>p.push({kind:"wallet",subtype:"featured",wallet:y}));break}case"custom":{Dn.getFilteredCustomWallets(o??[]).forEach(w=>p.push({kind:"wallet",subtype:"custom",wallet:w}));break}case"external":{i.forEach(y=>p.push({kind:"connector",subtype:"external",connector:y}));break}case"recommended":{Dn.getCappedRecommendedWallets(a).forEach(w=>p.push({kind:"wallet",subtype:"recommended",wallet:w}));break}default:console.warn(`Unknown connector type: ${h}`)}return p},hasInjectedConnectors(){return re.state.connectors.filter(e=>(e.type==="INJECTED"||e.type==="ANNOUNCED"||e.type==="MULTI_CHAIN")&&e.name!=="Browser Wallet"&&e.name!=="WalletConnect").length}}});var AHe,pr,CHe,J,gc=b(()=>{l();Lr();Hn();gs();Cu();$r();To();up();Un();AHe=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],pr=rt({view:"Connect",history:["Connect"],transactionStack:[]}),CHe={state:pr,subscribeKey(e,t){return Tt(pr,e,t)},pushTransactionStack(e){pr.transactionStack.push(e)},popTransactionStack(e){let t=pr.transactionStack.pop();if(!t)return;let{onSuccess:r,onError:n,onCancel:o}=t;switch(e){case"success":r?.();break;case"error":n?.(),J.goBack();break;case"cancel":o?.(),J.goBack();break;default:}},push(e,t){let r=e,n=t;ge.state.plan.hasExceededUsageLimit&&AHe.includes(e)&&(r="UsageExceeded",n=void 0),r!==pr.view&&(pr.view=r,pr.history.push(r),pr.data=n)},reset(e,t){pr.view=e,pr.history=[e],pr.data=t},replace(e,t){pr.history.at(-1)===e||(pr.view=e,pr.history[pr.history.length-1]=e,pr.data=t)},goBack(){let e=$.state.activeCaipAddress,t=J.state.view==="ConnectingFarcaster",r=!e&&t;if(pr.history.length>1){pr.history.pop();let[n]=pr.history.slice(-1);n&&(e&&n==="Connect"?pr.view="Account":pr.view=n)}else De.close();pr.data?.wallet&&(pr.data.wallet=void 0),pr.data?.redirectView&&(pr.data.redirectView=void 0),setTimeout(()=>{if(r){$.setAccountProp("farcasterUrl",void 0,$.state.activeChain);let n=re.getAuthConnector();n?.provider?.reload();let o=Kl(Y.state);n?.provider?.syncDappData?.({metadata:o.metadata,sdkVersion:o.sdkVersion,projectId:o.projectId,sdkType:o.sdkType})}},100)},goBackToIndex(e){if(pr.history.length>1){pr.history=pr.history.slice(0,e+1);let[t]=pr.history.slice(-1);t&&(pr.view=t)}},goBackOrCloseModal(){J.state.history.length>1?J.goBack():De.close()}},J=vr(CHe)});var dp,xH,nn,vH=b(()=>{l();Lr();ut();gs();To();dp=rt({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),xH={state:dp,subscribe(e){return Dt(dp,()=>e(dp))},setThemeMode(e){dp.themeMode=e;try{let t=re.getAuthConnector();if(t){let r=xH.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:r,w3mThemeVariables:Y1(r,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){dp.themeVariables={...dp.themeVariables,...e};try{let t=re.getAuthConnector();if(t){let r=xH.getSnapshot().themeVariables;t.provider.syncTheme({themeVariables:r,w3mThemeVariables:Y1(dp.themeVariables,dp.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Kl(dp)}},nn=vr(xH)});var spe,SHe,Kt,IHe,re,To=b(()=>{l();Lr();Hn();ut();mm();yc();w_();wH();ma();gs();Cu();$r();up();Un();gc();vH();spe=Object.fromEntries(sI.map(e=>[e,void 0])),SHe=Object.fromEntries(sI.map(e=>[e,!0])),Kt=rt({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:spe,filterByNamespaceMap:SHe}),IHe={state:Kt,subscribe(e){return Dt(Kt,()=>{e(Kt)})},subscribeKey(e,t){return Tt(Kt,e,t)},initialize(e){e.forEach(t=>{let r=de.getConnectedConnectorId(t);r&&re.setConnectorId(r,t)})},setActiveConnector(e){e&&(Kt.activeConnector=vf(e))},setConnectors(e){e.filter(o=>!Kt.allConnectors.some(s=>s.id===o.id&&re.getConnectorName(s.name)===re.getConnectorName(o.name)&&s.chain===o.chain)).forEach(o=>{o.type!=="MULTI_CHAIN"&&Kt.allConnectors.push(vf(o))});let r=re.getEnabledNamespaces(),n=re.getEnabledConnectors(r);Kt.connectors=re.mergeMultiChainConnectors(n)},filterByNamespaces(e){Object.keys(Kt.filterByNamespaceMap).forEach(t=>{Kt.filterByNamespaceMap[t]=!1}),e.forEach(t=>{Kt.filterByNamespaceMap[t]=!0}),re.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){Kt.filterByNamespaceMap[e]=t,re.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){let e=re.getEnabledNamespaces(),t=re.getEnabledConnectors(e),r=re.areAllNamespacesEnabled();Kt.connectors=re.mergeMultiChainConnectors(t),r?ge.clearFilterByNamespaces():ge.filterByNamespaces(e)},getEnabledNamespaces(){return Object.entries(Kt.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e)},getEnabledConnectors(e){return Kt.allConnectors.filter(t=>e.includes(t.chain))},areAllNamespacesEnabled(){return Object.values(Kt.filterByNamespaceMap).every(e=>e)},mergeMultiChainConnectors(e){let t=re.generateConnectorMapByName(e),r=[];return t.forEach(n=>{let o=n[0],s=o?.id===Z.CONNECTOR_ID.AUTH;n.length>1&&o?r.push({name:o.name,imageUrl:o.imageUrl,imageId:o.imageId,connectors:[...n],type:s?"AUTH":"MULTI_CHAIN",chain:"eip155",id:o?.id||""}):o&&r.push(o)}),r},generateConnectorMapByName(e){let t=new Map;return e.forEach(r=>{let{name:n}=r,o=re.getConnectorName(n);if(!o)return;let s=t.get(o)||[];s.find(a=>a.chain===r.chain)||s.push(r),t.set(o,s)}),t},getConnectorName(e){return e&&({"Trust Wallet":"Trust"}[e]||e)},getUniqueConnectorsByName(e){let t=[];return e.forEach(r=>{t.find(n=>n.chain===r.chain)||t.push(r)}),t},addConnector(e){if(e.id===Z.CONNECTOR_ID.AUTH){let t=e,r=Kl(Y.state),n=nn.getSnapshot().themeMode,o=nn.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType}),t?.provider?.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Y1(o,n)}),re.setConnectors([e])}else re.setConnectors([e])},getAuthConnector(e){let t=e||$.state.activeChain,r=Kt.connectors.find(n=>n.id===Z.CONNECTOR_ID.AUTH);if(r)return r?.connectors?.length?r.connectors.find(o=>o.chain===t):r},getAnnouncedConnectorRdns(){return Kt.connectors.filter(e=>e.type==="ANNOUNCED").map(e=>e.info?.rdns)},getConnectorById(e){return Dn.sortConnectorsByPriority(Kt.allConnectors).find(r=>r.id===e)},getConnector({id:e,namespace:t}){let r=t||$.state.activeChain,n=Kt.allConnectors.filter(i=>i.chain===r);return Dn.sortConnectorsByPriority(n).find(i=>i.id===e||i.explorerId===e)},syncIfAuthConnector(e){if(e.id!=="AUTH")return;let t=e,r=Kl(Y.state),n=nn.getSnapshot().themeMode,o=nn.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,sdkType:r.sdkType,projectId:r.projectId}),t.provider.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Y1(o,n)})},getConnectorsByNamespace(e){let t=Kt.allConnectors.filter(r=>r.chain===e);return re.mergeMultiChainConnectors(t)},canSwitchToSmartAccount(e){return $.checkIfSmartAccountEnabled()&&Fr(e)===Kr.ACCOUNT_TYPES.EOA},selectWalletConnector(e){let t=J.state.data?.redirectView,r=$.state.activeChain,n=r?re.getConnector({id:e.id,namespace:r}):void 0;rpe.handleMobileDeeplinkRedirect(n?.explorerId||e.id,$.state.activeChain),n?J.push("ConnectingExternal",{connector:n,wallet:e,redirectView:t}):J.push("ConnectingWalletConnect",{wallet:e,redirectView:t})},getConnectors(e){return e?re.getConnectorsByNamespace(e):re.mergeMultiChainConnectors(Kt.allConnectors)},setFilterByNamespace(e){Kt.filterByNamespace=e,Kt.connectors=re.getConnectors(e),ge.setFilterByNamespace(e)},setConnectorId(e,t){e&&(Kt.activeConnectorIds={...Kt.activeConnectorIds,[t]:e},de.setConnectedConnectorId(t,e))},removeConnectorId(e){Kt.activeConnectorIds={...Kt.activeConnectorIds,[e]:void 0},de.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return Kt.activeConnectorIds[e]},isConnected(e){return e?!!Kt.activeConnectorIds[e]:Object.values(Kt.activeConnectorIds).some(t=>!!t)},resetConnectorIds(){Kt.activeConnectorIds={...spe}},extendConnectorsWithExplorerWallets(e){Kt.allConnectors.forEach(n=>{let o=e.find(s=>s.id===n.id||s.rdns&&s.rdns===n.info?.rdns);o&&(n.explorerWallet=o)});let t=re.getEnabledNamespaces(),r=re.getEnabledConnectors(t);Kt.connectors=re.mergeMultiChainConnectors(r)},async connect(e={}){let{namespace:t}=e;return re.setFilterByNamespace(t),J.push("Connect",{addWalletForNamespace:t}),new Promise((r,n)=>{if(t){let o=$.subscribeChainProp("accountState",i=>{i?.caipAddress&&(r({caipAddress:i?.caipAddress}),o())},t),s=De.subscribeKey("open",i=>{i||(n(new Error("Modal closed")),s())})}else{let o=$.subscribeKey("activeCaipAddress",i=>{i&&(r({caipAddress:i}),o())}),s=De.subscribeKey("open",i=>{i||(n(new Error("Modal closed")),s())})}})}},re=vr(IHe)});var THe,k6,ipe=b(()=>{l();ut();ut();mm();$r();ai();To();mc();up();gc();yc();ha();$n();ma();THe=1e3,k6={checkNamespaceConnectorId(e,t){return re.getConnectorId(e)===t},isSocialProvider(e){return Ye.DEFAULT_REMOTE_FEATURES.socials.includes(e)},connectWalletConnect({walletConnect:e,connector:t,closeModalOnConnect:r=!0,redirectViewOnModalClose:n="Connect",onOpen:o,onConnect:s}){return new Promise((i,a)=>{if(e&&re.setActiveConnector(t),o?.(se.isMobile()&&e),n){let u=De.subscribeKey("open",d=>{d||(J.state.view!==n&&J.replace(n),u(),a(new Error("Modal closed")))})}let c=$.subscribeKey("activeCaipAddress",u=>{u&&(s?.(),r&&De.close(),c(),i(lt.parseCaipAddress(u)))})})},connectExternal(e){return new Promise((t,r)=>{let n=$.subscribeKey("activeCaipAddress",o=>{o&&(De.close(),n(),t(lt.parseCaipAddress(o)))});ee.connectExternal(e,e.chain).catch(()=>{n(),r(new Error("Connection rejected"))})})},connectSocial({social:e,namespace:t,closeModalOnConnect:r=!0,onOpenFarcaster:n,onConnect:o}){let s,i=!1,a=null,c=t||$.state.activeChain,u=$.subscribeKey("activeCaipAddress",d=>{d&&(r&&De.close(),u())});return new Promise((d,f)=>{async function p(y){if(y.data?.resultUri)if(y.origin===Z.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",p,!1);try{let w=re.getAuthConnector(c);if(w&&!i){s&&s.close(),i=!0;let x=y.data.resultUri;Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:e}}),de.setConnectedSocialProvider(e),await ee.connectExternal({id:w.id,type:w.type,socialUri:x},w.chain);let v=$.state.activeCaipAddress;if(!v){f(new Error("Failed to connect"));return}d(lt.parseCaipAddress(v)),Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:e}})}}catch(w){Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:se.parseError(w)}}),f(new Error("Failed to connect"))}}else Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:"Untrusted Origin"}})}async function h(){if(Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:e}}),e==="farcaster"){n?.();let y=De.subscribeKey("open",x=>{!x&&e==="farcaster"&&(f(new Error("Popup closed")),o?.(),y())}),w=re.getAuthConnector();if(w&&!$.getAccountData(c)?.farcasterUrl)try{let{url:v}=await w.provider.getFarcasterUri();$.setAccountProp("farcasterUrl",v,c)}catch{f(new Error("Failed to connect to farcaster"))}}else{let y=re.getAuthConnector();a=se.returnOpenHref(`${Z.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(y){let{uri:w}=await y.provider.getSocialRedirectUri({provider:e});if(a&&w){a.location.href=w,s=a;let x=setInterval(()=>{s?.closed&&!i&&(f(new Error("Popup closed")),clearInterval(x))},1e3);window.addEventListener("message",p,!1)}else a?.close(),f(new Error("Failed to initiate social connection"))}}catch{f(new Error("Failed to initiate social connection")),a?.close()}}}h()})},connectEmail({closeModalOnConnect:e=!0,redirectViewOnModalClose:t="Connect",onOpen:r,onConnect:n}){return new Promise((o,s)=>{if(r?.(),t){let a=De.subscribeKey("open",c=>{c||(J.state.view!==t&&J.replace(t),a(),s(new Error("Modal closed")))})}let i=$.subscribeKey("activeCaipAddress",a=>{a&&(n?.(),e&&De.close(),i(),o(lt.parseCaipAddress(a)))})})},async updateEmail(){let e=de.getConnectedConnectorId($.state.activeChain),t=re.getAuthConnector();if(!t)throw new Error("No auth connector found");if(e!==Z.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");let r=t.provider.getEmail()??"";return await De.open({view:"UpdateEmailWallet",data:{email:r,redirectView:void 0}}),new Promise((n,o)=>{let s=setInterval(()=>{let a=t.provider.getEmail()??"";a!==r&&(De.close(),clearInterval(s),i(),n({email:a}))},THe),i=De.subscribeKey("open",a=>{a||(J.state.view!=="Connect"&&J.push("Connect"),clearInterval(s),i(),o(new Error("Modal closed")))})})},canSwitchToSmartAccount(e){return $.checkIfSmartAccountEnabled()&&Fr(e)===Kr.ACCOUNT_TYPES.EOA}}});function U6(){let e=$.state.activeCaipNetwork?.chainNamespace||"eip155",t=$.state.activeCaipNetwork?.id||1,r=Ye.NATIVE_TOKEN_ADDRESS[e];return`${e}:${t}:${r}`}function EH(e){return Ye.NATIVE_TOKEN_ADDRESS[e]}function Fr(e){return $.getAccountData(e)?.preferredAccountType}function oy(e){return e?$.state.chains.get(e)?.networkState?.caipNetwork:$.state.activeCaipNetwork}var yc=b(()=>{l();$r();ha()});var fp,AH=b(()=>{l();ai();To();mc();Un();$n();fp={getConnectionStatus(e,t){let r=re.state.activeConnectorIds[t],n=ee.getConnections(t);return!!r&&e.connectorId===r?"connected":n.some(i=>i.connectorId.toLowerCase()===e.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:e,connectorId:t,addresses:r}){return e.map(n=>{if((t?n.connectorId.toLowerCase()===t.toLowerCase():!1)&&r){let s=n.accounts.filter(i=>!r.some(c=>c.toLowerCase()===i.address.toLowerCase()));return{...n,accounts:s}}return n})},excludeExistingConnections(e,t){let r=new Set(e);return t.filter(n=>!r.has(n.connectorId))},getConnectionsByConnectorId(e,t){return e.filter(r=>r.connectorId.toLowerCase()===t.toLowerCase())},getConnectionsData(e){let t=!!Y.state.remoteFeatures?.multiWallet,r=re.state.activeConnectorIds[e],n=ee.getConnections(e),s=(ee.state.recentConnections.get(e)??[]).filter(a=>re.getConnectorById(a.connectorId)),i=fp.excludeExistingConnections([...n.map(a=>a.connectorId),...r?[r]:[]],s);return t?{connections:n,recentConnections:i}:{connections:n.filter(a=>a.connectorId.toLowerCase()===r?.toLowerCase()),recentConnections:[]}},onConnectMobile(e){let t=ee.state.wcUri;if(e?.mobile_link&&t)try{ee.setWcError(!1);let{mobile_link:r,link_mode:n,name:o}=e,{redirect:s,redirectUniversalLink:i,href:a}=se.formatNativeUrl(r,t,n),c=s,u=i,d=se.isIframe()?"_top":"_self";ee.setWcLinking({name:o,href:a}),ee.setRecentWallet(e),Y.state.experimental_preferUniversalLinks&&u?se.openHref(u,d):se.openHref(c,d)}catch(r){Ae.sendEvent({type:"track",event:"CONNECT_PROXY_ERROR",properties:{message:r instanceof Error?r.message:"Error parsing the deep link",uri:t,mobile_link:e.mobile_link,name:e.name}}),ee.setWcError(!0)}}}});var D6,ws,Q3=b(()=>{l();Lr();Hn();D6=rt({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1,connectingWallet:void 0}),ws={state:D6,subscribe(e){return Dt(D6,()=>e(D6))},subscribeOpen(e){return Tt(D6,"open",e)},set(e){Object.assign(D6,{...D6,...e})}}});var on,_He,X3,ape=b(()=>{l();Lr();mm();yc();gs();lp();$r();mc();Un();hm();on=rt({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),_He={state:on,subscribe(e){return Dt(on,()=>e(on))},setLastNetworkInView(e){on.lastNetworkInView=e},async fetchTransactions(e){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");on.loading=!0;try{let t=await ze.fetchTransactions({account:e,cursor:on.next,chainId:$.state.activeCaipNetwork?.caipNetworkId}),r=X3.filterSpamTransactions(t.data),n=X3.filterByConnectedChain(r),o=[...on.transactions,...n];on.loading=!1,on.transactions=o,on.transactionsByYear=X3.groupTransactionsByYearAndMonth(on.transactionsByYear,n),on.empty=o.length===0,on.next=t.next?t.next:void 0}catch{let r=$.state.activeChain;Ae.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:Y.state.projectId,cursor:on.next,isSmartAccount:Fr(r)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),Je.showError("Failed to fetch transactions"),on.loading=!1,on.empty=!0,on.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){let r=e;return t.forEach(n=>{let o=new Date(n.metadata.minedAt).getFullYear(),s=new Date(n.metadata.minedAt).getMonth(),i=r[o]??{},c=(i[s]??[]).filter(u=>u.id!==n.id);r[o]={...i,[s]:[...c,n].sort((u,d)=>new Date(d.metadata.minedAt).getTime()-new Date(u.metadata.minedAt).getTime())}}),r},filterSpamTransactions(e){return e.filter(t=>!t.transfers?.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(e){let t=$.state.activeCaipNetwork?.caipNetworkId;return e.filter(n=>n.metadata.chain===t)},clearCursor(){on.next=void 0},resetTransactions(){on.transactions=[],on.transactionsByYear={},on.lastNetworkInView=void 0,on.loading=!1,on.empty=!1,on.next=void 0}},X3=vr(_He,"API_ERROR")});var Lt,sy,PHe,ee,ai=b(()=>{l();Lr();Hn();ut();yc();AH();ipe();$n();ma();gs();$r();To();mc();up();Q3();gc();ape();Lt=rt({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,wcFetchingUri:!1,buffering:!1,status:"disconnected"}),PHe={state:Lt,subscribe(e){return Dt(Lt,()=>e(Lt))},subscribeKey(e,t){return Tt(Lt,e,t)},_getClient(){return Lt._client},setClient(e){Lt._client=vf(e)},initialize(e){let t=e.filter(r=>!!r.namespace).map(r=>r.namespace);ee.syncStorageConnections(t)},syncStorageConnections(e){let t=de.getConnections(),r=e??Array.from($.state.chains.keys());for(let n of r){let o=t[n]??[],s=new Map(Lt.recentConnections);s.set(n,o),Lt.recentConnections=s}},getConnections(e){return e?Lt.connections.get(e)??[]:[]},hasAnyConnection(e){let t=ee.state.connections;return Array.from(t.values()).flatMap(r=>r).some(({connectorId:r})=>r===e)},async connectWalletConnect({cache:e="auto"}={}){Lt.wcFetchingUri=!0;let t=se.isTelegram()||se.isSafari()&&se.isIos();if(e==="always"||e==="auto"&&t){if(sy){await sy,sy=void 0;return}if(!se.isPairingExpired(Lt?.wcPairingExpiry)){let r=Lt.wcUri;Lt.wcUri=r;return}sy=ee._getClient()?.connectWalletConnect?.().catch(()=>{}),ee.state.status="connecting",await sy,sy=void 0,Lt.wcPairingExpiry=void 0,ee.state.status="connected"}else await ee._getClient()?.connectWalletConnect?.()},async connectExternal(e,t,r=!0){let n=await ee._getClient()?.connectExternal?.(e);r&&$.setActiveNamespace(t);let o=re.state.allConnectors.find(i=>i.id===e?.id),s=e.type==="AUTH"?"email":"browser";return Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s,name:o?.name||"Unknown",view:J.state.view,walletRank:o?.explorerWallet?.order}}),n},async reconnectExternal(e){await ee._getClient()?.reconnectExternal?.(e);let t=e.chain||$.state.activeChain;t&&re.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){if(!t)return;De.setLoading(!0,$.state.activeChain);let r=re.getAuthConnector();r&&($.setAccountProp("preferredAccountType",e,t),await r.provider.setPreferredAccount(e),de.setPreferredAccountTypes(Object.entries($.state.chains).reduce((n,[o,s])=>{let i=o,a=Fr(i);return a!==void 0&&(n[i]=a),n},{})),await ee.reconnectExternal(r),De.setLoading(!1,$.state.activeChain),Ae.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:$.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(e){return ee._getClient()?.signMessage(e)},parseUnits(e,t){return ee._getClient()?.parseUnits(e,t)},formatUnits(e,t){return ee._getClient()?.formatUnits(e,t)},updateBalance(e){return ee._getClient()?.updateBalance(e)},async sendTransaction(e){return ee._getClient()?.sendTransaction(e)},async getCapabilities(e){return ee._getClient()?.getCapabilities(e)},async grantPermissions(e){return ee._getClient()?.grantPermissions(e)},async walletGetAssets(e){return ee._getClient()?.walletGetAssets(e)??{}},async estimateGas(e){return ee._getClient()?.estimateGas(e)},async writeContract(e){return ee._getClient()?.writeContract(e)},async writeSolanaTransaction(e){return ee._getClient()?.writeSolanaTransaction(e)},async getEnsAddress(e){return ee._getClient()?.getEnsAddress(e)},async getEnsAvatar(e){return ee._getClient()?.getEnsAvatar(e)},checkInstalled(e){return ee._getClient()?.checkInstalled?.(e)||!1},resetWcConnection(){Lt.wcUri=void 0,Lt.wcPairingExpiry=void 0,Lt.wcLinking=void 0,Lt.recentWallet=void 0,Lt.wcFetchingUri=!1,Lt.status="disconnected",X3.resetTransactions(),de.deleteWalletConnectDeepLink(),de.deleteRecentWallet(),ws.set({connectingWallet:void 0})},resetUri(){Lt.wcUri=void 0,Lt.wcPairingExpiry=void 0,sy=void 0,Lt.wcFetchingUri=!1,ws.set({connectingWallet:void 0})},finalizeWcConnection(e){let{wcLinking:t,recentWallet:r}=ee.state;t&&de.setWalletConnectDeepLink(t),r&&de.setAppKitRecent(r),e&&Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:t?"mobile":"qrcode",name:J.state.data?.wallet?.name||"Unknown",view:J.state.view,walletRank:r?.order}})},setWcBasic(e){Lt.wcBasic=e},setUri(e){Lt.wcUri=e,Lt.wcFetchingUri=!1,Lt.wcPairingExpiry=se.getPairingExpiry()},setWcLinking(e){Lt.wcLinking=e},setWcError(e){Lt.wcError=e,Lt.wcFetchingUri=!1,Lt.buffering=!1},setRecentWallet(e){Lt.recentWallet=e},setBuffering(e){Lt.buffering=e},setStatus(e){Lt.status=e},setIsSwitchingConnection(e){Lt.isSwitchingConnection=e},async disconnect({id:e,namespace:t,initialDisconnect:r}={}){try{await ee._getClient()?.disconnect({id:e,chainNamespace:t,initialDisconnect:r})}catch(n){throw new hc("Failed to disconnect","INTERNAL_SDK_ERROR",n)}},async disconnectConnector({id:e,namespace:t}){try{await ee._getClient()?.disconnectConnector({id:e,namespace:t})}catch(r){throw new hc("Failed to disconnect connector","INTERNAL_SDK_ERROR",r)}},setConnections(e,t){let r=new Map(Lt.connections);r.set(t,e),Lt.connections=r},async handleAuthAccountSwitch({address:e,namespace:t}){let n=$.getAccountData(t)?.user?.accounts?.find(s=>s.type==="smartAccount"),o=n&&n.address.toLowerCase()===e.toLowerCase()&&k6.canSwitchToSmartAccount(t)?"smartAccount":"eoa";await ee.setPreferredAccountType(o,t)},async handleActiveConnection({connection:e,namespace:t,address:r}){let n=re.getConnectorById(e.connectorId),o=e.connectorId===Z.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${e.connectorId}`);if(o)r&&await ee.handleAuthAccountSwitch({address:r,namespace:t});else return(await ee.connectExternal({id:n.id,type:n.type,provider:n.provider,address:r,chain:t},t))?.address;return r},async handleDisconnectedConnection({connection:e,namespace:t,address:r,closeModalOnConnect:n}){let o=re.getConnectorById(e.connectorId),s=e.auth?.name?.toLowerCase(),i=e.connectorId===Z.CONNECTOR_ID.AUTH,a=e.connectorId===Z.CONNECTOR_ID.WALLET_CONNECT;if(!o)throw new Error(`No connector found for connection: ${e.connectorId}`);let c;if(i)if(s&&k6.isSocialProvider(s)){let{address:u}=await k6.connectSocial({social:s,closeModalOnConnect:n,onOpenFarcaster(){De.open({view:"ConnectingFarcaster"})},onConnect(){J.replace("ProfileWallets")}});c=u}else{let{address:u}=await k6.connectEmail({closeModalOnConnect:n,onOpen(){De.open({view:"EmailLogin"})},onConnect(){J.replace("ProfileWallets")}});c=u}else if(a){let{address:u}=await k6.connectWalletConnect({walletConnect:!0,connector:o,closeModalOnConnect:n,onOpen(d){let f=d?"AllWallets":"ConnectingWalletConnect";De.state.open?J.push(f):De.open({view:f})},onConnect(){J.replace("ProfileWallets")}});c=u}else{let u=await ee.connectExternal({id:o.id,type:o.type,provider:o.provider,chain:t},t);u&&(c=u.address)}return i&&r&&await ee.handleAuthAccountSwitch({address:r,namespace:t}),c},async switchConnection({connection:e,address:t,namespace:r,closeModalOnConnect:n,onChange:o}){let s,i=$.getAccountData(r)?.caipAddress;if(i){let{address:c}=lt.parseCaipAddress(i);s=c}let a=fp.getConnectionStatus(e,r);switch(a){case"connected":case"active":{let c=await ee.handleActiveConnection({connection:e,namespace:r,address:t});if(s&&c){let u=c.toLowerCase()!==s.toLowerCase();o?.({address:c,namespace:r,hasSwitchedAccount:u,hasSwitchedWallet:a==="active"})}break}case"disconnected":{let c=await ee.handleDisconnectedConnection({connection:e,namespace:r,address:t,closeModalOnConnect:n});c&&o?.({address:c,namespace:r,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},ee=vr(PHe)});var b_,cpe=b(()=>{l();R6();b_={createBalance(e,t){let r={name:e.metadata.name||"",symbol:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:r.name,symbol:r.symbol,chainId:t,address:e.address==="native"?void 0:this.convertAddressToCAIP10Address(e.address,t),value:r.value,price:r.price,quantity:{decimals:r.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:r.decimals})},iconUrl:r.iconUrl}},convertHexToBalance({hex:e,decimals:t}){return pc(BigInt(e),t)},convertAddressToCAIP10Address(e,t){return`${t}:${e}`},createCAIP2ChainId(e,t){return`${t}:${parseInt(e,16)}`},getChainIdHexFromCAIP2ChainId(e){let t=e.split(":");if(t.length<2||!t[1])return"0x0";let r=t[1],n=parseInt(r,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(e){return typeof e!="object"||e===null?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(r=>this.isValidAsset(r)))},isValidAsset(e){return typeof e=="object"&&e!==null&&typeof e.address=="string"&&typeof e.balance=="string"&&(e.type==="ERC20"||e.type==="NATIVE")&&typeof e.metadata=="object"&&e.metadata!==null&&typeof e.metadata.name=="string"&&typeof e.metadata.symbol=="string"&&typeof e.metadata.decimals=="number"&&typeof e.metadata.price=="number"&&typeof e.metadata.iconUrl=="string"}}});async function lpe(){if(!CH){let{createPublicClient:e,http:t,defineChain:r}=await Promise.resolve().then(()=>(R6(),Yfe));CH={createPublicClient:e,http:t,defineChain:r}}return CH}var CH,x_,upe=b(()=>{l();ut();Un();x_={getBlockchainApiRpcUrl(e,t){let r=new URL("https://rpc.walletconnect.org/v1/");return r.searchParams.set("chainId",e),r.searchParams.set("projectId",t),r.toString()},async getViemChain(e){let{defineChain:t}=await lpe(),{chainId:r}=lt.parseCaipNetworkId(e.caipNetworkId);return t({...e,id:Number(r)})},async createViemPublicClient(e){let{createPublicClient:t,http:r}=await lpe(),n=Y.state.projectId,o=await x_.getViemChain(e);if(!o)throw new Error(`Chain ${e.caipNetworkId} not found in viem/chains`);return t({chain:o,transport:r(x_.getBlockchainApiRpcUrl(e.caipNetworkId,n))})}}});var al,L6=b(()=>{l();R6();ut();lp();$r();ai();To();cpe();ma();upe();al={async getMyTokensWithBalance(e={forceUpdate:void 0,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address}){let{forceUpdate:t,caipNetwork:r,address:n}=e,o=re.getConnectorId("eip155")===Z.CONNECTOR_ID.AUTH;if(!n)return[];let s=r?`${r.caipNetworkId}:${n}`:n,i=de.getBalanceCacheForCaipAddress(s);if(i)return i.balances;if(r&&r.chainNamespace===Z.CHAIN.EVM&&o){let c=await this.getEIP155Balances(n,r);if(c)return this.filterLowQualityTokens(c)}let a=await ze.getBalance(n,r?.caipNetworkId,t);return this.filterLowQualityTokens(a.balances)},async getEIP155Balances(e,t){try{let r=b_.getChainIdHexFromCAIP2ChainId(t.caipNetworkId);if(!(await ee.getCapabilities(e))?.[r]?.assetDiscovery?.supported)return null;let o=await ee.walletGetAssets({account:e,chainFilter:[r]});if(!b_.isWalletGetAssetsResponse(o))return null;let i=(o[r]||[]).map(a=>b_.createBalance(a,t.caipNetworkId));return de.updateBalanceCache({caipAddress:`${t.caipNetworkId}:${e}`,balance:{balances:i},timestamp:Date.now()}),i}catch{return null}},filterLowQualityTokens(e){return e.filter(t=>t.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:e,assetAddress:t,caipNetwork:r}){let n=await x_.createViemPublicClient(r),{address:o}=lt.parseCaipAddress(e),[{result:s},{result:i},{result:a},{result:c}]=await n.multicall({contracts:[{address:t,functionName:"name",args:[],abi:Hr},{address:t,functionName:"symbol",args:[],abi:Hr},{address:t,functionName:"balanceOf",args:[o],abi:Hr},{address:t,functionName:"decimals",args:[],abi:Hr}]});return{name:s,symbol:i,decimals:c,balance:a&&c?pc(a,c):"0"}}}});var SH,iy,IH=b(()=>{l();SH={adapters:{}},iy={state:SH,initialize(e){SH.adapters={...e}},get(e){return SH.adapters[e]}}});var v_,Li,ar,E_=b(()=>{l();Lr();Hn();v_={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:void 0},Li=rt({providers:{...v_},providerIds:{...v_}}),ar={state:Li,subscribeKey(e,t){return Tt(Li,e,t)},subscribe(e){return Dt(Li,()=>{e(Li)})},subscribeProviders(e){return Dt(Li.providers,()=>e(Li.providers))},setProvider(e,t){e&&t&&(Li.providers[e]=vf(t))},getProvider(e){if(e)return Li.providers[e]},setProviderId(e,t){t&&(Li.providerIds[e]=t)},getProviderId(e){if(e)return Li.providerIds[e]},reset(){Li.providers={...v_},Li.providerIds={...v_}},resetChain(e){Li.providers[e]=void 0,Li.providerIds[e]=void 0}}});var ym,TH=b(()=>{l();lp();$r();ai();L6();yc();ym={async getTokenList(e){return(await ze.fetchSwapTokens({chainId:e}))?.tokens?.map(n=>({...n,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){let e=$.state.activeCaipNetwork;if(!e)return null;try{if(e.chainNamespace==="solana"){let t=(await ee?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:t,fast:t,instant:t}}else return await ze.fetchGasPrice({chainId:e.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:e,userAddress:t,sourceTokenAmount:r,sourceTokenDecimals:n}){let o=await ze.fetchSwapAllowance({tokenAddress:e,userAddress:t});if(o?.allowance&&r&&n){let s=ee.parseUnits(r,n)||0;return BigInt(o.allowance)>=s}return!1},async getMyTokensWithBalance(e){let t=await al.getMyTokensWithBalance({forceUpdate:e,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address});return $.setAccountProp("tokenBalance",t,$.state.activeChain),this.mapBalancesToSwapTokens(t)},mapBalancesToSwapTokens(e){return e?.map(t=>({...t,address:t?.address?t.address:U6(),decimals:parseInt(t.quantity.decimals,10),logoUri:t.iconUrl,eip2612:!1}))||[]},async handleSwapError(e){try{let t=e?.cause;return t?.json&&(await t.json())?.reasons?.[0]?.description?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}}});var Zt,NHe,xt,_H=b(()=>{l();Lr();Hn();ut();ut();mm();L6();yc();ha();$n();TH();gs();$r();ai();mc();gc();hm();Zt=rt({tokenBalances:[],loading:!1}),NHe={state:Zt,subscribe(e){return Dt(Zt,()=>e(Zt))},subscribeKey(e,t){return Tt(Zt,e,t)},setToken(e){e&&(Zt.token=vf(e))},setTokenAmount(e){Zt.sendTokenAmount=e},setReceiverAddress(e){Zt.receiverAddress=e},setReceiverProfileImageUrl(e){Zt.receiverProfileImageUrl=e},setReceiverProfileName(e){Zt.receiverProfileName=e},setNetworkBalanceInUsd(e){Zt.networkBalanceInUSD=e},setLoading(e){Zt.loading=e},getSdkEventProperties(e){return{message:se.parseError(e),isSmartAccount:Fr($.state.activeChain)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:Zt.token?.symbol||"",amount:Zt.sendTokenAmount??0,network:$.state.activeCaipNetwork?.caipNetworkId||""}},async sendToken(){try{switch(xt.setLoading(!0),$.state.activeCaipNetwork?.chainNamespace){case"eip155":await xt.sendEvmToken();return;case"solana":await xt.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw js.isUserRejectedRequestError(e)?new Z1(e):e}finally{xt.setLoading(!1)}},async sendEvmToken(){let e=$.state.activeChain;if(!e)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");let t=Fr(e);if(!xt.state.sendTokenAmount||!xt.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!xt.state.token)throw new Error("A token is required");if(xt.state.token?.address){Ae.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token.address,amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||""}});let{hash:r}=await xt.sendERC20Token({receiverAddress:xt.state.receiverAddress,tokenAddress:xt.state.token.address,sendTokenAmount:xt.state.sendTokenAmount,decimals:xt.state.token.quantity.decimals});r&&(Zt.hash=r)}else{Ae.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token.symbol||"",amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||""}});let{hash:r}=await xt.sendNativeToken({receiverAddress:xt.state.receiverAddress,sendTokenAmount:xt.state.sendTokenAmount,decimals:xt.state.token.quantity.decimals});r&&(Zt.hash=r)}},async fetchTokenBalance(e){Zt.loading=!0;let t=$.state.activeChain,r=$.state.activeCaipNetwork?.caipNetworkId,n=$.state.activeCaipNetwork?.chainNamespace,o=$.getAccountData(t)?.caipAddress??$.state.activeCaipAddress,s=o?se.getPlainAddress(o):void 0;if(Zt.lastRetry&&!se.isAllowedRetry(Zt.lastRetry,30*Ye.ONE_SEC_MS))return Zt.loading=!1,[];try{if(s&&r&&n){let i=await al.getMyTokensWithBalance();return Zt.tokenBalances=i,Zt.lastRetry=void 0,i}}catch(i){Zt.lastRetry=Date.now(),e?.(i),Je.showError("Token Balance Unavailable")}finally{Zt.loading=!1}return[]},fetchNetworkBalance(){if(Zt.tokenBalances.length===0)return;let e=ym.mapBalancesToSwapTokens(Zt.tokenBalances);if(!e)return;let t=e.find(r=>r.address===U6());t&&(Zt.networkBalanceInUSD=t?ht.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){J.pushTransactionStack({});let t=e.receiverAddress,r=$.getAccountData()?.address,n=ee.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),s=await ee.sendTransaction({chainNamespace:Z.CHAIN.EVM,to:t,address:r,data:"0x",value:n??BigInt(0)});return Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Fr("eip155")===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token?.symbol||"",amount:e.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:s||""}}),ee._getClient()?.updateBalance("eip155"),xt.resetSend(),{hash:s}},async sendERC20Token(e){J.pushTransactionStack({onSuccess(){J.replace("Account")}});let t=ee.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),r=$.getAccountData()?.address;if(r&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){let n=se.getPlainAddress(e.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");let o=await ee.writeContract({fromAddress:r,tokenAddress:n,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:f4.getERC20Abi(n),chainNamespace:Z.CHAIN.EVM});return Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Fr("eip155")===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token?.symbol||"",amount:e.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:o||""}}),xt.resetSend(),{hash:o}}return{hash:void 0}},async sendSolanaToken(){if(!xt.state.sendTokenAmount||!xt.state.receiverAddress)throw new Error("An amount and receiver address are required");J.pushTransactionStack({onSuccess(){J.replace("Account")}});let e;xt.state.token&&xt.state.token.address!==Ye.SOLANA_NATIVE_TOKEN_ADDRESS&&(se.isCaipAddress(xt.state.token.address)?e=se.getPlainAddress(xt.state.token.address):e=xt.state.token.address);let t=await ee.sendTransaction({chainNamespace:"solana",tokenMint:e,to:xt.state.receiverAddress,value:xt.state.sendTokenAmount});t&&(Zt.hash=t),ee._getClient()?.updateBalance("solana"),Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:xt.state.token?.symbol||"",amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:t||""}}),xt.resetSend()},resetSend(){Zt.token=void 0,Zt.sendTokenAmount=void 0,Zt.receiverAddress=void 0,Zt.receiverProfileImageUrl=void 0,Zt.receiverProfileName=void 0,Zt.loading=!1,Zt.tokenBalances=[]}},xt=vr(NHe)});var PH,A_,Oe,dpe,$,$r=b(()=>{l();Lr();Hn();ut();_te();L6();ha();$n();ma();gs();IH();ai();To();mc();up();Un();E_();Q3();_H();hm();PH={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},A_={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},Oe=rt({chains:Cte(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),dpe={state:Oe,subscribe(e){return Dt(Oe,()=>{e(Oe)})},subscribeKey(e,t){return Tt(Oe,e,t)},subscribeAccountStateProp(e,t,r){let n=r||Oe.activeChain;return n?Tt(Oe.chains.get(n)?.accountState||{},e,t):()=>{}},subscribeChainProp(e,t,r){let n;return Dt(Oe.chains,()=>{let o=r||Oe.activeChain;if(o){let s=Oe.chains.get(o)?.[e];n!==s&&(n=s,t(s))}})},initialize(e,t,r){let{chainId:n,namespace:o}=de.getActiveNetworkProps(),s=t?.find(d=>d.id.toString()===n?.toString()),a=e.find(d=>d?.namespace===o)||e?.[0],c=e.map(d=>d.namespace).filter(d=>d!==void 0),u=Y.state.enableEmbedded?new Set([...c]):new Set([...t?.map(d=>d.chainNamespace)??[]]);(e?.length===0||!a)&&(Oe.noAdapters=!0),Oe.noAdapters||(Oe.activeChain=a?.namespace,Oe.activeCaipNetwork=s,$.setChainNetworkData(a?.namespace,{caipNetwork:s}),Oe.activeChain&&ws.set({activeChain:a?.namespace})),u.forEach(d=>{let f=t?.filter(y=>y.chainNamespace===d),p=de.getPreferredAccountTypes()||{},h={...Y.state.defaultAccountTypes,...p};$.state.chains.set(d,{namespace:d,networkState:rt({...A_,caipNetwork:f?.[0]}),accountState:rt({...PH,preferredAccountType:h[d]}),caipNetworks:f??[],...r}),$.setRequestedCaipNetworks(f??[],d)})},removeAdapter(e){if(Oe.activeChain===e){let t=Array.from(Oe.chains.entries()).find(([r])=>r!==e);if(t){let r=t[1]?.caipNetworks?.[0];r&&$.setActiveCaipNetwork(r)}}Oe.chains.delete(e)},addAdapter(e,{connectionControllerClient:t},r){if(!e.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");Oe.chains.set(e.namespace,{namespace:e.namespace,networkState:{...A_,caipNetwork:r[0]},accountState:{...PH},caipNetworks:r,connectionControllerClient:t}),$.setRequestedCaipNetworks(r?.filter(n=>n.chainNamespace===e.namespace)??[],e.namespace)},addNetwork(e){let t=Oe.chains.get(e.chainNamespace);if(t){let r=[...t.caipNetworks||[]];t.caipNetworks?.find(n=>n.id===e.id)||r.push(e),Oe.chains.set(e.chainNamespace,{...t,caipNetworks:r}),$.setRequestedCaipNetworks(r,e.chainNamespace),re.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){let r=Oe.chains.get(e);if(r){let n=Oe.activeCaipNetwork?.id===t,o=[...r.caipNetworks?.filter(s=>s.id!==t)||[]];n&&r?.caipNetworks?.[0]&&$.setActiveCaipNetwork(r.caipNetworks[0]),Oe.chains.set(e,{...r,caipNetworks:o}),$.setRequestedCaipNetworks(o||[],e),o.length===0&&re.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){let r=Oe.chains.get(e);r&&(r.networkState={...r.networkState||A_,...t},Oe.chains.set(e,r))},setChainAccountData(e,t,r=!0){if(!e)throw new Error("Chain is required to update chain account data");let n=Oe.chains.get(e);if(n){let o={...n.accountState||PH,...t};Oe.chains.set(e,{...n,accountState:o}),(Oe.chains.size===1||Oe.activeChain===e)&&t.caipAddress&&(Oe.activeCaipAddress=t.caipAddress)}},setChainNetworkData(e,t){if(!e)return;let r=Oe.chains.get(e);if(r){let n={...r.networkState||A_,...t};Oe.chains.set(e,{...r,networkState:n})}},setAccountProp(e,t,r,n=!0){$.setChainAccountData(r,{[e]:t},n)},setActiveNamespace(e){Oe.activeChain=e;let t=e?Oe.chains.get(e):void 0,r=t?.networkState?.caipNetwork;r?.id&&e&&(Oe.activeCaipAddress=t?.accountState?.caipAddress,Oe.activeCaipNetwork=r,$.setChainNetworkData(e,{caipNetwork:r}),de.setActiveCaipNetworkId(r?.caipNetworkId),ws.set({activeChain:e,selectedNetworkId:r?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;let t=Oe.activeChain===e.chainNamespace;t||$.setIsSwitchingNamespace(!0);let r=Oe.chains.get(e.chainNamespace);Oe.activeChain=e.chainNamespace,Oe.activeCaipNetwork=e,$.setChainNetworkData(e.chainNamespace,{caipNetwork:e});let n=r?.accountState?.address;if(n)Oe.activeCaipAddress=`${e.chainNamespace}:${e.id}:${n}`;else if(t&&Oe.activeCaipAddress){let{address:s}=lt.parseCaipAddress(Oe.activeCaipAddress);n=s,Oe.activeCaipAddress=`${e.caipNetworkId}:${n}`}else Oe.activeCaipAddress=void 0;$.setChainAccountData(e.chainNamespace,{address:n,caipAddress:Oe.activeCaipAddress}),xt.resetSend(),ws.set({activeChain:Oe.activeChain,selectedNetworkId:Oe.activeCaipNetwork?.caipNetworkId}),de.setActiveCaipNetworkId(e.caipNetworkId),!$.checkIfSupportedNetwork(e.chainNamespace)&&Y.state.enableNetworkSwitch&&!Y.state.allowUnsupportedChain&&!ee.state.wcBasic&&$.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;let t=Oe.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;let t=e!==$.state.activeChain,r=$.getNetworkData(e)?.caipNetwork,n=$.getCaipNetworkByNamespace(e,r?.id);t&&n&&await $.switchActiveNetwork(n)},async switchActiveNetwork(e,{throwOnFailure:t=!1}={}){let r=$.state.activeChain;if(!r)throw new Error("ChainController:switchActiveNetwork - namespace is required");let n=ar.getProviderId(Oe.activeChain)==="AUTH",o=$.getAccountData(r)?.address,s=Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e.chainNamespace);try{if(o&&e.chainNamespace===r||n&&s){let i=iy.get(e.chainNamespace);if(!i)throw new Error("Adapter not found");await i.switchNetwork({caipNetwork:e})}$.setActiveCaipNetwork(e)}catch(i){if(t)throw i}Ae.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})},getConnectionControllerClient(e){let t=e||Oe.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");let r=Oe.chains.get(t);if(!r?.connectionControllerClient)throw new Error("ConnectionController client not set");return r.connectionControllerClient},getNetworkProp(e,t){let r=Oe.chains.get(t)?.networkState;if(r)return r[e]},getRequestedCaipNetworks(e){let t=Oe.chains.get(e),{approvedCaipNetworkIds:r=[],requestedCaipNetworks:n=[]}=t?.networkState||{};return se.sortRequestedNetworks(r,n).filter(i=>i?.id)},getAllRequestedCaipNetworks(){let e=[];return Oe.chains.forEach(t=>{if(!t.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");let r=$.getRequestedCaipNetworks(t.namespace);e.push(...r)}),e},setRequestedCaipNetworks(e,t){$.setAdapterNetworkState(t,{requestedCaipNetworks:e});let n=$.getAllRequestedCaipNetworks().map(s=>s.chainNamespace),o=Array.from(new Set(n));re.filterByNamespaces(o)},getAllApprovedCaipNetworkIds(){let e=[];return Oe.chains.forEach(t=>{if(!t.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");let r=$.getApprovedCaipNetworkIds(t.namespace);e.push(...r)}),e},getActiveCaipNetwork(e){return e?Oe.chains.get(e)?.networkState?.caipNetwork:Oe.activeCaipNetwork},getActiveCaipAddress(){return Oe.activeCaipAddress},getApprovedCaipNetworkIds(e){return Oe.chains.get(e)?.networkState?.approvedCaipNetworkIds||[]},setApprovedCaipNetworksData(e,t){$.setAdapterNetworkState(e,t)},checkIfSupportedNetwork(e,t){let r=t||Oe.activeCaipNetwork?.caipNetworkId,n=$.getRequestedCaipNetworks(e);return n.length?n?.some(o=>o.caipNetworkId===r):!0},checkIfSupportedChainId(e){return Oe.activeChain?$.getRequestedCaipNetworks(Oe.activeChain)?.some(r=>r.id===e):!0},checkIfSmartAccountEnabled(){let e=V1.caipNetworkIdToNumber(Oe.activeCaipNetwork?.caipNetworkId);return!Oe.activeChain||!e?!1:!!(Ew.get(Qa.SMART_ACCOUNT_ENABLED_NETWORKS)?.split(",")||[])?.includes(e.toString())},showUnsupportedChainUI(){De.open({view:"UnsupportedChain"})},checkIfNamesSupported(){let e=Oe.activeCaipNetwork;return!!(e?.chainNamespace&&Ye.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){$.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(e){let t=e;if(!t)throw new Error("Chain is required to set account prop");let r=$.state.chains.get(t)?.accountState?.preferredAccountType,n=Y.state.defaultAccountTypes[t];Oe.activeCaipAddress=void 0,$.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:n||r,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),re.removeConnectorId(t)},setIsSwitchingNamespace(e){Oe.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){let e=[],t;if(Oe.chains.forEach(r=>{Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&e.push(r.namespace)}),e.length>0){let r=e[0];return t=r?Oe.chains.get(r)?.caipNetworks?.[0]:void 0,t}},getAccountData(e){let t=e||Oe.activeChain;if(t)return $.state.chains.get(t)?.accountState},getNetworkData(e){let t=e||Oe.activeChain;if(t)return $.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;let r=$.state.chains.get(e),n=r?.caipNetworks?.find(o=>o.id.toString()===t?.toString());return n||r?.networkState?.caipNetwork||r?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){let e=re.state.filterByNamespace;return(e?[Oe.chains.get(e)]:Array.from(Oe.chains.values())).flatMap(r=>r?.caipNetworks||[]).map(r=>r.caipNetworkId)},getCaipNetworks(e){return e?$.getRequestedCaipNetworks(e):$.getAllRequestedCaipNetworks()},getCaipNetworkById(e,t){return dpe.getCaipNetworks(t).find(r=>r.id.toString()===e.toString()||r.caipNetworkId.toString()===e.toString())},setLastConnectedSIWECaipNetwork(e){Oe.lastConnectedSIWECaipNetwork=e},getLastConnectedSIWECaipNetwork(){return Oe.lastConnectedSIWECaipNetwork},async fetchTokenBalance(e){let t=$.getAccountData();if(!t)return[];let r=$.state.activeCaipNetwork?.caipNetworkId,n=$.state.activeCaipNetwork?.chainNamespace,o=$.state.activeCaipAddress,s=o?se.getPlainAddress(o):void 0;if($.setAccountProp("balanceLoading",!0,n),t.lastRetry&&!se.isAllowedRetry(t.lastRetry,30*Ye.ONE_SEC_MS))return $.setAccountProp("balanceLoading",!1,n),[];try{if(s&&r&&n){let i=await al.getMyTokensWithBalance();return $.setAccountProp("tokenBalance",i,n),$.setAccountProp("lastRetry",void 0,n),$.setAccountProp("balanceLoading",!1,n),i}}catch(i){$.setAccountProp("lastRetry",Date.now(),n),e?.(i),Je.showError("Token Balance Unavailable")}finally{$.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(e){let t=e.chainNamespace,r=!!$.getAccountData(t)?.caipAddress,n=$.getAllApprovedCaipNetworkIds(),o=$.getNetworkProp("supportsAllNetworks",t)!==!1,s=re.getConnectorId(t),i=re.getAuthConnector(),a=s===Z.CONNECTOR_ID.AUTH&&i;return!r||o||a?!1:!n?.includes(e.caipNetworkId)}},$=vr(dpe)});var fpe,ppe=b(()=>{l();ut();$r();To();gc();fpe={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){let r=$.state.activeCaipNetwork,n=$.state.activeChain,o=J.state.data;if(e.id===r?.id)return;let i=!!$.getAccountData(n)?.address,a=!!$.getAccountData(e.chainNamespace)?.address,c=e.chainNamespace!==n,d=re.getConnectorId(n)===Z.CONNECTOR_ID.AUTH,f=Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(p=>p===e.chainNamespace);t||d&&f?J.push("SwitchNetwork",{...o,network:e}):i&&c&&!a?J.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):J.push("SwitchNetwork",{...o,network:e})}}});var Mi,RHe,De,up=b(()=>{l();Lr();Hn();$n();ppe();gs();Cu();$r();ai();To();mc();Un();Q3();gc();Mi=rt({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),RHe={state:Mi,subscribe(e){return Dt(Mi,()=>e(Mi))},subscribeKey(e,t){return Tt(Mi,e,t)},async open(e){let t=e?.namespace,r=$.state.activeChain,n=t&&t!==r,o=$.getAccountData(e?.namespace)?.caipAddress,s=$.state.noAdapters;if(ee.state.wcBasic?ge.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await ge.prefetch(),re.setFilterByNamespace(e?.namespace),De.setLoading(!0,t),t&&n){let i=$.getNetworkData(t)?.caipNetwork||$.getRequestedCaipNetworks(t)[0];i&&(s?(await $.switchActiveNetwork(i),J.push("ConnectingWalletConnectBasic")):fpe.onSwitchNetwork({network:i,ignoreSwitchConfirmation:!0}))}else Y.state.manualWCControl||s&&!o?se.isMobile()?J.reset("AllWallets"):J.reset("ConnectingWalletConnectBasic"):e?.view?J.reset(e.view,e.data):o?J.reset("Account"):J.reset("Connect");Mi.open=!0,ws.set({open:!0}),Ae.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!o}})},close(){let e=Y.state.enableEmbedded,t=!!$.state.activeCaipAddress;Mi.open&&Ae.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),Mi.open=!1,J.reset("Connect"),De.clearLoading(),e?t?J.replace("Account"):J.push("Connect"):ws.set({open:!1}),ee.resetUri()},setLoading(e,t){t&&Mi.loadingNamespaceMap.set(t,e),Mi.loading=e,ws.set({loading:e})},clearLoading(){Mi.loadingNamespaceMap.clear(),Mi.loading=!1,ws.set({loading:!1})},shake(){Mi.shake||(Mi.shake=!0,setTimeout(()=>{Mi.shake=!1},500))}},De=vr(RHe)});var e5,NH,OHe,Jt,BHe,t5,hpe=b(()=>{l();Lr();Hn();ut();ha();gs();Cu();lp();$r();Un();e5={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},NH={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},OHe={providers:BU,selectedProvider:null,error:null,purchaseCurrency:e5,paymentCurrency:NH,purchaseCurrencies:[e5],paymentCurrencies:[],quotesLoading:!1},Jt=rt(OHe),BHe={state:Jt,subscribe(e){return Dt(Jt,()=>e(Jt))},subscribeKey(e,t){return Tt(Jt,e,t)},setSelectedProvider(e){if(e&&e.name==="meld"){let t=$.state.activeChain,r=t===Z.CHAIN.SOLANA?"SOL":"USDC",n=t?$.state.chains.get(t)?.accountState?.address??"":"",o=new URL(e.url);o.searchParams.append("publicKey",Ste),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",n),o.searchParams.append("externalCustomerId",Y.state.projectId),Jt.selectedProvider={...e,url:o.toString()}}else Jt.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(t=>typeof t=="string")){let t=e,r=BU.filter(n=>t.includes(n.name));Jt.providers=r}else Jt.providers=[]},setPurchaseCurrency(e){Jt.purchaseCurrency=e},setPaymentCurrency(e){Jt.paymentCurrency=e},setPurchaseAmount(e){t5.state.purchaseAmount=e},setPaymentAmount(e){t5.state.paymentAmount=e},async getAvailableCurrencies(){let e=await ze.getOnrampOptions();Jt.purchaseCurrencies=e.purchaseCurrencies,Jt.paymentCurrencies=e.paymentCurrencies,Jt.paymentCurrency=e.paymentCurrencies[0]||NH,Jt.purchaseCurrency=e.purchaseCurrencies[0]||e5,await ge.fetchCurrencyImages(e.paymentCurrencies.map(t=>t.id)),await ge.fetchTokenImages(e.purchaseCurrencies.map(t=>t.symbol))},async getQuote(){Jt.quotesLoading=!0;try{let e=await ze.getOnrampQuote({purchaseCurrency:Jt.purchaseCurrency,paymentCurrency:Jt.paymentCurrency,amount:Jt.paymentAmount?.toString()||"0",network:Jt.purchaseCurrency?.symbol});return Jt.quotesLoading=!1,Jt.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return Jt.error=e.message,Jt.quotesLoading=!1,null}finally{Jt.quotesLoading=!1}},resetState(){Jt.selectedProvider=null,Jt.error=null,Jt.purchaseCurrency=e5,Jt.paymentCurrency=NH,Jt.purchaseCurrencies=[e5],Jt.paymentCurrencies=[],Jt.paymentAmount=void 0,Jt.purchaseAmount=void 0,Jt.quotesLoading=!1}},t5=vr(BHe)});function kHe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let u=0;u>>0,w=new Uint8Array(y);for(;p!==h;){let T=u[p],E=0;for(let S=y-1;(T!==0||E>>0,w[S]=T%r>>>0,T=T/r>>>0;if(T!==0)throw new Error("Non-zero carry");f=E,p++}let x=y-f;for(;x!==y&&w[x]===0;)x++;let v=n.repeat(d);for(;x>>0,y=new Uint8Array(h);for(;d255)return;let E=t[T];if(E===255)return;let S=0;for(let _=h-1;(E!==0||S>>0,y[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=S,d++}let w=h-p;for(;w!==h&&y[w]===0;)w++;let x=new Uint8Array(f+(h-w)),v=f;for(;w!==h;)x[v++]=y[w++];return x}function c(u){let d=a(u);if(d)return d;throw new Error("Non-base"+r+" character")}return{encode:i,decodeUnsafe:a,decode:c}}var mpe,gpe=b(()=>{l();mpe=kHe});var UHe,wm,RH=b(()=>{l();gpe();UHe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",wm=mpe(UHe)});var DHe,LHe,MHe,Yrr,HHe,Jrr,C_=b(()=>{l();$c();cw();rI();DHe=Ht(ks(),1),LHe="wc",MHe="universal_provider",Yrr=`${LHe}@2:${MHe}:`,HHe="https://rpc.walletconnect.org/v1/",Jrr=`${HHe}bundler`});var ype,wpe=b(()=>{l();ype={convertEVMChainIdToCoinType(e){if(e>=2147483648)throw new Error("Invalid chainId");return(2147483648|e)>>>0}}});var wc,$He,bm,OH=b(()=>{l();Lr();Hn();wpe();ma();gs();lp();$r();ai();To();gc();wc=rt({suggestions:[],loading:!1}),$He={state:wc,subscribe(e){return Dt(wc,()=>e(wc))},subscribeKey(e,t){return Tt(wc,e,t)},async resolveName(e){try{return await ze.lookupEnsName(e)}catch(t){let r=t;throw new Error(r?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await ze.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{wc.loading=!0,wc.suggestions=[];let t=await ze.getEnsNameSuggestions(e);return wc.suggestions=t.suggestions||[],wc.suggestions}catch(t){let r=bm.parseEnsApiError(t,"Error fetching name suggestions");throw new Error(r)}finally{wc.loading=!1}},async getNamesForAddress(e){try{if(!$.state.activeCaipNetwork)return[];let r=de.getEnsFromCacheForAddress(e);if(r)return r;let n=await ze.reverseLookupEnsName({address:e});return de.updateEnsCache({address:e,ens:n,timestamp:Date.now()}),n}catch(t){let r=bm.parseEnsApiError(t,"Error fetching names for address");throw new Error(r)}},async registerName(e){let t=$.state.activeCaipNetwork,r=$.getAccountData(t?.chainNamespace)?.address,n=re.getAuthConnector();if(!t)throw new Error("Network not found");if(!r||!n)throw new Error("Address or auth connector not found");wc.loading=!0;try{let o=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});J.pushTransactionStack({onCancel(){J.replace("RegisterAccountName")}});let s=await ee.signMessage(o);wc.loading=!1;let i=t.id;if(!i)throw new Error("Network not found");let a=ype.convertEVMChainIdToCoinType(Number(i));await ze.registerEnsName({coinType:a,address:r,signature:s,message:o}),$.setAccountProp("profileName",e,t.chainNamespace),de.updateEnsCache({address:r,ens:[{name:e,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),J.replace("RegisterAccountNameSuccess")}catch(o){let s=bm.parseEnsApiError(o,`Error registering name ${e}`);throw J.replace("RegisterAccountName"),new Error(s)}finally{wc.loading=!1}},validateName(e){return/^[a-zA-Z0-9-]{4,}$/u.test(e)},parseEnsApiError(e,t){return e?.reasons?.[0]?.description||t}},bm=vr($He)});function S_(e){try{return new URL(e)}catch{return null}}function FHe(e){let t=e.split("/"),r=t.length>0&&t[0]!==void 0?t[0]:"",n=r.lastIndexOf(":");return n===-1?{host:r}:{host:r.slice(0,n),port:r.slice(n+1)}}function zHe(e){let t=e.indexOf("://");if(t===-1)return null;let r=e.slice(0,t),n=t+3,o=e.indexOf("/",n);o===-1&&(o=e.length);let s=e.slice(n,o),i=s.lastIndexOf(":");return i===-1?{scheme:r,host:s}:{scheme:r,host:s.slice(0,i),port:s.slice(i+1)}}function bpe(e,t){if(t.includes("://")){let i=S_(t);return i?i.origin===e:!1}let{host:r,port:n}=FHe(t),o=e.indexOf("://");if(o!==-1){let i=o+3,a=e.indexOf("/",i);a===-1&&(a=e.length);let c=e.slice(i,a);if(n!==void 0)return`${r}:${n}`===c;let u=c.split(":")[0];return r===u}let s=S_(e);return s?n!==void 0?r===s.hostname&&n===(s.port||void 0):r===s.hostname:!1}function xpe(e,t,r){let n=r,o,s=n.indexOf("://");s!==-1&&(o=n.slice(0,s),n=n.slice(s+3));let i=n.indexOf("/");i!==-1&&(n=n.slice(0,i));let a=n,c,u=a.lastIndexOf(":");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let d=a.split(".");for(let w of d)if(w.includes("*")&&w!=="*")return!1;let f=e.protocol.replace(/:$/u,"");if(o&&o!==f||c!==void 0&&c!=="*"&&c!==e.port)return!1;let p=zHe(t),y=(p?p.host:e.hostname).split(".");if(d.length!==y.length)return!1;for(let w=d.length-1;w>=0;w-=1){let x=d[w],v=y[w];if(x!=="*"&&x!==v)return!1}return!0}var vpe=b(()=>{l()});var VHe,cl,I_=b(()=>{l();ut();OH();vpe();VHe={ton:["ton_sendMessage","ton_signData"],solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},cl={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(e){return VHe[e]||[]},createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};let r={...e},n=new Set;if(t.methods&&Object.keys(t.methods).forEach(o=>n.add(o)),t.chains&&Object.keys(t.chains).forEach(o=>n.add(o)),t.events&&Object.keys(t.events).forEach(o=>n.add(o)),t.rpcMap&&Object.keys(t.rpcMap).forEach(o=>{let[s]=o.split(":");s&&n.add(s)}),n.forEach(o=>{r[o]||(r[o]=this.createDefaultNamespace(o))}),t.methods&&Object.entries(t.methods).forEach(([o,s])=>{r[o]&&(r[o].methods=s)}),t.chains&&Object.entries(t.chains).forEach(([o,s])=>{r[o]&&(r[o].chains=s)}),t.events&&Object.entries(t.events).forEach(([o,s])=>{r[o]&&(r[o].events=s)}),t.rpcMap){let o=new Set;Object.entries(t.rpcMap).forEach(([s,i])=>{let[a,c]=s.split(":");!a||!c||!r[a]||(r[a].rpcMap||(r[a].rpcMap={}),o.has(a)||(r[a].rpcMap={},o.add(a)),r[a].rpcMap[c]=i)})}return r},createNamespaces(e,t){let r=e.reduce((n,o)=>{let{id:s,chainNamespace:i,rpcUrls:a}=o,c=a.default.http[0];n[i]||(n[i]=this.createDefaultNamespace(i));let u=`${i}:${s}`,d=n[i];switch(d.chains.push(u),u){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":d.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":d.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break;default:}return d?.rpcMap&&c&&(d.rpcMap[s]=c),n},{});return this.applyNamespaceOverrides(r,t)},resolveReownName:async e=>{let t=await bm.resolveName(e);return(t?.addresses?Object.values(t.addresses):[])[0]?.address||!1},getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{let r=t.chains||[],n=t.accounts.map(o=>{let[s,i]=o.split(":");return`${s}:${i}`});return Array.from(new Set([...r,...n]))})},isSessionEventData(e){return typeof e=="object"&&e!==null&&"id"in e&&"topic"in e&&"params"in e&&typeof e.params=="object"&&e.params!==null&&"chainId"in e.params&&"event"in e.params&&typeof e.params.event=="object"&&e.params.event!==null},isUserRejectedRequestError(e){try{if(typeof e=="object"&&e!==null){let t=e,r=typeof t.code=="number",n=r&&t.code===cl.RPC_ERROR_CODE.USER_REJECTED_METHODS,o=r&&t.code===cl.RPC_ERROR_CODE.USER_REJECTED;return n||o}return!1}catch{return!1}},isOriginAllowed(e,t,r){let n=[...t,...r];if(t.length===0)return!0;let o=S_(e);if(!o)return n.some(s=>!s.includes("*")&&s===e);if(o.hostname==="localhost"||o.hostname==="127.0.0.1")return!0;for(let s of n)if(s.includes("*")){if(xpe(o,e,s))return!0}else if(bpe(e,s))return!0;return!1},listenWcProvider({universalProvider:e,namespace:t,onConnect:r,onDisconnect:n,onAccountsChanged:o,onChainChanged:s,onDisplayUri:i}){r&&e.on("connect",()=>{let a=cl.getWalletConnectAccounts(e,t);r(a)}),n&&e.on("disconnect",()=>{n()}),o&&e.on("accountsChanged",a=>{try{let c=e.session?.namespaces?.[t]?.accounts||[],u=e.rpcProviders?.[t]?.getDefaultChain(),d=a.map(f=>{let p=c.find(w=>w.includes(`${t}:${u}:${f}`));if(!p)return;let{chainId:h,chainNamespace:y}=lt.parseCaipAddress(p);return{address:f,chainId:h,chainNamespace:y}}).filter(f=>f!==void 0);d.length>0&&o(d)}catch(c){console.warn("Failed to parse accounts for namespace on accountsChanged event",t,a,c)}}),s&&e.on("chainChanged",a=>{s(a)}),i&&e.on("display_uri",a=>{i(a)})},getWalletConnectAccounts(e,t){let r=new Set,n=e?.session?.namespaces?.[t]?.accounts?.map(o=>lt.parseCaipAddress(o)).filter(({address:o})=>r.has(o.toLowerCase())?!1:(r.add(o.toLowerCase()),!0));return n&&n.length>0?n:[]}}});var jHe,r5,Epe=b(()=>{l();C_();ut();yc();$n();I_();$r();To();E_();jHe=[Z.CONNECTOR_ID.AUTH,Z.CONNECTOR_ID.WALLET_CONNECT],r5=class{constructor(t){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=r=>$.getCaipNetworks(r),this.getConnectorId=r=>re.getConnectorId(r),t&&this.construct(t)}construct(t){this.projectId=t.projectId,this.namespace=t.namespace,this.adapterType=t.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:t,chainId:r}){let n=this.getCaipNetworks().filter(o=>o.chainNamespace===this.namespace).find(o=>o.id.toString()===r?.toString());t&&n&&this.addConnection({connectorId:Z.CONNECTOR_ID.AUTH,accounts:t,caipNetwork:n})}setAuthProvider(t){t.onConnect(this.onAuthConnected.bind(this)),t.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:Z.CONNECTOR_ID.AUTH,type:"AUTH",name:Z.CONNECTOR_NAMES.AUTH,provider:t,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...t){let r=new Set;this.availableConnectors=[...t,...this.availableConnectors].filter(n=>r.has(n.id)?!1:(r.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...t){let r=new Set;this.availableConnections=[...t,...this.availableConnections].filter(n=>r.has(n.connectorId.toLowerCase())?!1:(r.add(n.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(t){this.availableConnections=this.availableConnections.filter(r=>r.connectorId.toLowerCase()!==t.toLowerCase()),this.emit("connections",this.availableConnections)}clearConnections(t=!1){this.availableConnections=[],t&&this.emit("connections",this.availableConnections)}setStatus(t,r){$.setAccountProp("status",t,r)}on(t,r){this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t)?.add(r)}off(t,r){let n=this.eventListeners.get(t);n&&n.delete(r)}removeAllEventListeners(){this.eventListeners.forEach(t=>{t.clear()})}emit(t,r){let n=this.eventListeners.get(t);n&&n.forEach(o=>o(r))}async connectWalletConnect(t){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(r){throw cl.isUserRejectedRequestError(r)?new Z1(r):r}}async switchNetwork(t){let{caipNetwork:r}=t,n=ar.getProviderId(r.chainNamespace),o=ar.getProvider(r.chainNamespace);if(!o)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){o.setDefaultChain(r.caipNetworkId);return}if(n==="AUTH"){let s=re.getAuthConnector()?.provider;if(!s)throw new Error("Auth provider not found");let i=Fr(r.chainNamespace);await s.switchNetwork({chainId:r.caipNetworkId});let a=await s.getUser({chainId:r.caipNetworkId,preferredAccountType:i});this.emit("switchNetwork",a)}}getWalletConnectConnector(){let t=this.connectors.find(r=>r.id==="walletConnect");if(!t)throw new Error("WalletConnectConnector not found");return t}onConnect(t,r){if(t.length>0){let{address:n,chainId:o}=se.getAccount(t[0]),s=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===o?.toString()),i=this.connectors.find(a=>a.id===r);n&&(this.emit("accountChanged",{address:n,chainId:o,connector:i}),this.addConnection({connectorId:r,accounts:t.map(a=>{let{address:c}=se.getAccount(a);return{address:c}}),caipNetwork:s}))}}onAccountsChanged(t,r,n=!0){if(t.length>0){let{address:o}=se.getAccount(t[0]),s=this.getConnection({connectorId:r,connections:this.connections,connectors:this.connectors});o&&this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===r.toLowerCase()&&this.emit("accountChanged",{address:o,chainId:s?.caipNetwork?.id,connector:s?.connector}),this.addConnection({connectorId:r,accounts:t.map(i=>{let{address:a}=se.getAccount(i);return{address:a}}),caipNetwork:s?.caipNetwork})}else n&&this.onDisconnect(r)}onDisconnect(t){this.removeProviderListeners(t),this.deleteConnection(t),this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===t.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(t,r){let n=typeof t=="string"&&t.startsWith("0x")?parseInt(t,16).toString():t.toString(),o=this.getConnection({connectorId:r,connections:this.connections,connectors:this.connectors}),s=this.getCaipNetworks().filter(i=>i.chainNamespace===this.namespace).find(i=>i.id.toString()===n);o&&this.addConnection({connectorId:r,accounts:o.accounts,caipNetwork:s}),this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===r.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(t,r){if(jHe.includes(t))return;let n=i=>this.onAccountsChanged(i,t),o=i=>this.onChainChanged(i,t),s=()=>this.onDisconnect(t);this.providerHandlers[t]||(r.on("disconnect",s),r.on("accountsChanged",n),r.on("chainChanged",o),this.providerHandlers[t]={provider:r,disconnect:s,accountsChanged:n,chainChanged:o})}removeProviderListeners(t){if(this.providerHandlers[t]){let{provider:r,disconnect:n,accountsChanged:o,chainChanged:s}=this.providerHandlers[t];r.removeListener("disconnect",n),r.removeListener("accountsChanged",o),r.removeListener("chainChanged",s),this.providerHandlers[t]=null}}emitFirstAvailableConnection(){let t=this.getConnection({connections:this.connections,connectors:this.connectors});if(t){let[r]=t.accounts;this.emit("accountChanged",{address:r?.address,chainId:t.caipNetwork?.id,connector:t.connector})}}getConnection({address:t,connectorId:r,connections:n,connectors:o}){if(r){let i=n.find(u=>u.connectorId.toLowerCase()===r.toLowerCase());if(!i)return null;let a=o.find(u=>u.id.toLowerCase()===i.connectorId.toLowerCase()),c=t?i.accounts.find(u=>u.address.toLowerCase()===t.toLowerCase()):i.accounts[0];return{...i,account:c,connector:a}}let s=n.find(i=>i.accounts.length>0&&o.some(a=>a.id.toLowerCase()===i.connectorId.toLowerCase()));if(s){let[i]=s.accounts,a=o.find(c=>c.id.toLowerCase()===s.connectorId.toLowerCase());return{...s,account:i,connector:a}}return null}}});var ay,_o,T_=b(()=>{l();C_();ut();mm();$r();ai();To();mc();up();Un();gc();hm();yc();$n();ay=null,_o={getSIWX(){return Y.state.siwx},async initializeIfEnabled(e=$.getActiveCaipAddress()){let t=Y.state.siwx;if(!(t&&e))return;let[r,n,o]=e.split(":");if($.checkIfSupportedNetwork(r,`${r}:${n}`))try{if(Y.state.remoteFeatures?.emailCapture){let i=$.getAccountData(r)?.user;await De.open({view:"DataCapture",data:{email:i?.email??void 0}});return}if(ay&&await ay,(await t.getSessions(`${r}:${n}`,o)).length)return;await De.open({view:"SIWXSignMessage"})}catch(s){console.error("SIWXUtil:initializeIfEnabled",s),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(s)}),await ee._getClient()?.disconnect().catch(console.error),J.reset("Connect"),Je.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(e=$.getActiveCaipAddress()){if(!Y.state.siwx||!e)return!0;let{chainNamespace:r,chainId:n,address:o}=lt.parseCaipAddress(e),s=`${r}:${n}`;return(await _o.getSessions({address:o,caipNetworkId:s})).length>0},async requestSignMessage(){let e=Y.state.siwx,t=se.getPlainAddress($.getActiveCaipAddress()),r=oy();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!r)throw new Error("No ActiveCaipNetwork or client found");try{let n=await e.createMessage({chainId:r.caipNetworkId,accountAddress:t}),o=n.toString(),s="";e.signMessage?s=await e.signMessage({message:o,chainId:r.caipNetworkId,accountAddress:t}):(re.getConnectorId(r.chainNamespace)===Z.CONNECTOR_ID.AUTH&&J.pushTransactionStack({}),s=await ee.signMessage(o)||""),await e.addSession({data:n,message:o,signature:s}),$.setLastConnectedSIWECaipNetwork(r),De.close(),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(n){(!De.state.open||J.state.view==="ApproveTransaction")&&await De.open({view:"SIWXSignMessage"}),Je.showError("Error signing message"),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(n)}),console.error("SWIXUtil:requestSignMessage",n)}},async cancelSignMessage(){try{let e=this.getSIWX();if(e?.getRequired?.()){let r=$.getLastConnectedSIWECaipNetwork();if(r){let n=await e?.getSessions(r?.caipNetworkId,se.getPlainAddress($.getActiveCaipAddress())||"");n&&n.length>0?await $.switchActiveNetwork(r):await ee.disconnect()}else await ee.disconnect()}else De.close();De.close(),Ae.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){let e=this.getSIWX(),t=$.getAllRequestedCaipNetworks(),r=[];return await Promise.all(t.map(async n=>{let o=await e?.getSessions(n.caipNetworkId,se.getPlainAddress($.getActiveCaipAddress())||"");o&&r.push(...o)})),r},async getSessions(e){let t=Y.state.siwx,r=e?.address;if(!r){let o=$.getActiveCaipAddress();r=se.getPlainAddress(o)}let n=e?.caipNetworkId;return n||(n=$.getActiveCaipNetwork()?.caipNetworkId),t&&r&&n?t.getSessions(n,r):[]},async isSIWXCloseDisabled(){let e=this.getSIWX();if(e){let t=J.state.view==="ApproveTransaction",r=J.state.view==="SIWXSignMessage";if(t||r)return e.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:e,chainId:t,socialUri:r,preferredAccountType:n,chainNamespace:o}){let s=_o.getSIWX(),i=oy();if(!s||!o.includes(Z.CHAIN.EVM)||Y.state.remoteFeatures?.emailCapture){let f=await e.connect({chainId:t,socialUri:r,preferredAccountType:n});return{address:f.address,chainId:f.chainId,accounts:f.accounts}}let a=`${o}:${t}`,c=await s.createMessage({chainId:a,accountAddress:"<>"}),u={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await e.connect({chainId:t,socialUri:r,siwxMessage:u,preferredAccountType:n});return u.accountAddress=d.address,u.serializedMessage=d.message||"",d.signature&&d.message&&await _o.addEmbeddedWalletSession(u,d.message,d.signature),$.setLastConnectedSIWECaipNetwork(i),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(e,t,r){if(ay)return ay;let n=_o.getSIWX();return n?(ay=n.addSession({data:e,message:t,signature:r}).finally(()=>{ay=null}),ay):Promise.resolve()},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:r}){let n=_o.getSIWX(),o=oy(),s=new Set(t.map(u=>u.split(":")[0]));if(!n||s.size!==1||!s.has("eip155"))return!1;let i=await n.createMessage({chainId:oy()?.caipNetworkId||"",accountAddress:""}),a=await e.authenticate({nonce:i.nonce,domain:i.domain,uri:i.uri,exp:i.expirationTime,iat:i.issuedAt,nbf:i.notBefore,requestId:i.requestId,version:i.version,resources:i.resources,statement:i.statement,chainId:i.chainId,methods:r,chains:[i.chainId,...t.filter(u=>u!==i.chainId)]});Je.showLoading("Authenticating...",{autoClose:!1});let c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if($.setAccountProp("connectedWalletInfo",c,Array.from(s)[0]),a?.auths?.length){let u=a.auths.map(d=>{let f=e.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud??"",version:d.p.version||i.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:f,signature:d.s.s,cacao:d}});try{await n.setSessions(u),o&&$.setLastConnectedSIWECaipNetwork(o),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:_o.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:_o.getSIWXEventProperties(d)}),await e.disconnect().catch(console.error),d}finally{Je.hide()}}return!0},getSIWXEventProperties(e){let t=$.state.activeChain;if(!t)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:$.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Fr(t)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,message:e?se.parseError(e):void 0}},async clearSessions(){let e=this.getSIWX();e&&await e.setSessions([])}}});var n5,qHe,Ape=b(()=>{l();C_();ut();T_();I_();$r();Un();n5=class{constructor({provider:t,namespace:r}){this.id=Z.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=$.getCaipNetworks.bind($),this.caipNetworks=this.getCaipNetworks(),this.provider=t,this.chain=r}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){let r=this.getCaipNetworks(),n=Y.state.universalProviderConfigOverride,o=cl.createNamespaces(r,n);await this.provider.connect({optionalNamespaces:o})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){let t=this.chains.map(r=>r.caipNetworkId);return _o.universalProviderAuthenticate({universalProvider:this.provider,chains:t,methods:qHe})}},qHe=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"]});var pp,Cpe=b(()=>{l();ut();pp={getGasPriceInEther(e,t){let r=t*e;return Number(r)/1e18},getGasPriceInUSD(e,t,r){let n=pp.getGasPriceInEther(t,r);return ht.bigNumber(e).times(n).toNumber()},getPriceImpact({sourceTokenAmount:e,sourceTokenPriceInUSD:t,toTokenPriceInUSD:r,toTokenAmount:n}){let o=ht.bigNumber(e).times(t),s=ht.bigNumber(n).times(r);return o.minus(s).div(o).times(100).toNumber()},getMaxSlippage(e,t){let r=ht.bigNumber(e).div(100);return ht.multiply(t,r).toNumber()},getProviderFee(e,t=.0085){return ht.bigNumber(e).times(t).toString()},isInsufficientNetworkTokenForGas(e,t){let r=t||"0";return ht.bigNumber(e).eq(0)?!0:ht.bigNumber(ht.bigNumber(r)).gt(e)},isInsufficientSourceTokenForSwap(e,t,r){let n=r?.find(s=>s.address===t)?.quantity?.numeric;return ht.bigNumber(n||"0").lt(e)}}});var ll,WHe,sn,BH=b(()=>{l();Lr();Hn();ut();gs();Un();ll=rt({message:"",variant:"info",open:!1}),WHe={state:ll,subscribeKey(e,t){return Tt(ll,e,t)},open(e,t){let{debug:r}=Y.state,{code:n,displayMessage:o,debugMessage:s}=e;if(o&&r&&(ll.message=o,ll.variant=t,ll.open=!0),s){if(!Z.IS_DEVELOPMENT)return;let i=typeof s=="function"?s():s,a=n?{code:n}:void 0;t==="error"?console.error(i,a):t==="warning"?console.warn(i,a):console.info(i,a)}},warn(e,t,r){ll.open=!0,ll.message=e,ll.variant="warning",t&&console.warn(t,r)},close(){ll.open=!1,ll.message="",ll.variant="info"}},sn=vr(WHe)});var Spe,KHe,bs,Q,__,ot,Ipe=b(()=>{l();Lr();Hn();ut();ut();mm();L6();yc();ha();$n();TH();Cpe();gs();BH();lp();$r();ai();To();mc();gc();hm();Spe=15e4,KHe=6,bs={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,switchingTokens:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:Ye.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},Q=rt({...bs}),__={state:Q,subscribe(e){return Dt(Q,()=>e(Q))},subscribeKey(e,t){return Tt(Q,e,t)},getParams(){let e=$.state.activeChain,t=$.getAccountData(e)?.caipAddress??$.state.activeCaipAddress,r=se.getPlainAddress(t),n=U6(),o=re.getConnectorId($.state.activeChain);if(!r)throw new Error("No address found to swap the tokens from.");let s=!Q.toToken?.address||!Q.toToken?.decimals,i=!Q.sourceToken?.address||!Q.sourceToken?.decimals||!ht.bigNumber(Q.sourceTokenAmount).gt(0),a=!Q.sourceTokenAmount;return{networkAddress:n,fromAddress:r,fromCaipAddress:t,sourceTokenAddress:Q.sourceToken?.address,toTokenAddress:Q.toToken?.address,toTokenAmount:Q.toTokenAmount,toTokenDecimals:Q.toToken?.decimals,sourceTokenAmount:Q.sourceTokenAmount,sourceTokenDecimals:Q.sourceToken?.decimals,invalidToToken:s,invalidSourceToken:i,invalidSourceTokenAmount:a,availableToSwap:t&&!s&&!i&&!a,isAuthConnector:o===Z.CONNECTOR_ID.AUTH}},async setSourceToken(e){if(!e){Q.sourceToken=e,Q.sourceTokenAmount="",Q.sourceTokenPriceInUSD=0;return}Q.sourceToken=e,await ot.setTokenPrice(e.address,"sourceToken")},setSourceTokenAmount(e){Q.sourceTokenAmount=e},async setToToken(e){if(!e){Q.toToken=e,Q.toTokenAmount="",Q.toTokenPriceInUSD=0;return}Q.toToken=e,await ot.setTokenPrice(e.address,"toToken")},setToTokenAmount(e){Q.toTokenAmount=e?ht.toFixed(e,KHe):""},async setTokenPrice(e,t){let r=Q.tokensPriceMap[e]||0;r||(Q.loadingPrices=!0,r=await ot.getAddressPrice(e)),t==="sourceToken"?Q.sourceTokenPriceInUSD=r:t==="toToken"&&(Q.toTokenPriceInUSD=r),Q.loadingPrices&&(Q.loadingPrices=!1),ot.getParams().availableToSwap&&!Q.switchingTokens&&ot.swapTokens()},async switchTokens(){if(!(Q.initializing||!Q.initialized||Q.switchingTokens)){Q.switchingTokens=!0;try{let e=Q.toToken?{...Q.toToken}:void 0,t=Q.sourceToken?{...Q.sourceToken}:void 0,r=e&&Q.toTokenAmount===""?"1":Q.toTokenAmount;ot.setSourceTokenAmount(r),ot.setToTokenAmount(""),await ot.setSourceToken(e),await ot.setToToken(t),Q.switchingTokens=!1,ot.swapTokens()}catch(e){throw Q.switchingTokens=!1,e}}},resetState(){Q.myTokensWithBalance=bs.myTokensWithBalance,Q.tokensPriceMap=bs.tokensPriceMap,Q.initialized=bs.initialized,Q.initializing=bs.initializing,Q.switchingTokens=bs.switchingTokens,Q.sourceToken=bs.sourceToken,Q.sourceTokenAmount=bs.sourceTokenAmount,Q.sourceTokenPriceInUSD=bs.sourceTokenPriceInUSD,Q.toToken=bs.toToken,Q.toTokenAmount=bs.toTokenAmount,Q.toTokenPriceInUSD=bs.toTokenPriceInUSD,Q.networkPrice=bs.networkPrice,Q.networkTokenSymbol=bs.networkTokenSymbol,Q.networkBalanceInUSD=bs.networkBalanceInUSD,Q.inputError=bs.inputError},resetValues(){let{networkAddress:e}=ot.getParams(),t=Q.tokens?.find(r=>r.address===e);ot.setSourceToken(t),ot.setToToken(void 0)},getApprovalLoadingState(){return Q.loadingApprovalTransaction},clearError(){Q.transactionError=void 0},async initializeState(){if(!Q.initializing){if(Q.initializing=!0,!Q.initialized)try{await ot.fetchTokens(),Q.initialized=!0}catch{Q.initialized=!1,Je.showError("Failed to initialize swap"),J.goBack()}Q.initializing=!1}},async fetchTokens(){let{networkAddress:e}=ot.getParams();await ot.getNetworkTokenPrice(),await ot.getMyTokensWithBalance();let t=Q.myTokensWithBalance?.find(r=>r.address===e);t&&(Q.networkTokenSymbol=t.symbol,ot.setSourceToken(t),ot.setSourceTokenAmount("0"))},async getTokenList(){let e=$.state.activeCaipNetwork?.caipNetworkId;if(!(Q.caipNetworkId===e&&Q.tokens))try{Q.tokensLoading=!0;let t=await ym.getTokenList(e);Q.tokens=t,Q.caipNetworkId=e,Q.popularTokens=t.sort((i,a)=>i.symbola.symbol?1:0);let n=(e&&Ye.SUGGESTED_TOKENS_BY_CHAIN?.[e]||[]).map(i=>t.find(a=>a.symbol===i)).filter(i=>!!i),s=(Ye.SWAP_SUGGESTED_TOKENS||[]).map(i=>t.find(a=>a.symbol===i)).filter(i=>!!i).filter(i=>!n.some(a=>a.address===i.address));Q.suggestedTokens=[...n,...s]}catch{Q.tokens=[],Q.popularTokens=[],Q.suggestedTokens=[]}finally{Q.tokensLoading=!1}},async getAddressPrice(e){let t=Q.tokensPriceMap[e];if(t)return t;let n=(await ze.fetchTokenPrice({addresses:[e]}))?.fungibles||[],s=[...Q.tokens||[],...Q.myTokensWithBalance||[]]?.find(c=>c.address===e)?.symbol,i=n.find(c=>c.symbol.toLowerCase()===s?.toLowerCase())?.price||0,a=parseFloat(i.toString());return Q.tokensPriceMap[e]=a,a},async getNetworkTokenPrice(){let{networkAddress:e}=ot.getParams(),r=(await ze.fetchTokenPrice({addresses:[e]}).catch(()=>(Je.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],n=r?.price.toString()||"0";Q.tokensPriceMap[e]=parseFloat(n),Q.networkTokenSymbol=r?.symbol||"",Q.networkPrice=n},async getMyTokensWithBalance(e){let t=await al.getMyTokensWithBalance({forceUpdate:e,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address}),r=ym.mapBalancesToSwapTokens(t);r&&(await ot.getInitialGasPrice(),ot.setBalances(r))},setBalances(e){let{networkAddress:t}=ot.getParams(),r=$.state.activeCaipNetwork;if(!r)return;let n=e.find(o=>o.address===t);e.forEach(o=>{Q.tokensPriceMap[o.address]=o.price||0}),Q.myTokensWithBalance=e.filter(o=>o.address.startsWith(r.caipNetworkId)),Q.networkBalanceInUSD=n?ht.multiply(n.quantity.numeric,n.price).toString():"0"},async getInitialGasPrice(){let e=await ym.fetchGasPrice();if(!e)return{gasPrice:null,gasPriceInUSD:null};switch($.state?.activeCaipNetwork?.chainNamespace){case Z.CHAIN.SOLANA:return Q.gasFee=e.standard??"0",Q.gasPriceInUSD=ht.multiply(e.standard,Q.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(Q.gasFee),gasPriceInUSD:Number(Q.gasPriceInUSD)};case Z.CHAIN.EVM:default:let t=e.standard??"0",r=BigInt(t),n=BigInt(Spe),o=pp.getGasPriceInUSD(Q.networkPrice,n,r);return Q.gasFee=t,Q.gasPriceInUSD=o,{gasPrice:r,gasPriceInUSD:o}}},async swapTokens(){let e=$.getAccountData()?.address,t=Q.sourceToken,r=Q.toToken,n=ht.bigNumber(Q.sourceTokenAmount).gt(0);if(n||ot.setToTokenAmount(""),!r||!t||Q.loadingPrices||!n||!e)return;Q.loadingQuote=!0;let o=ht.bigNumber(Q.sourceTokenAmount).times(10**t.decimals).round(0).toFixed(0);try{let s=await ze.fetchSwapQuote({userAddress:e,from:t.address,to:r.address,gasPrice:Q.gasFee,amount:o.toString()});Q.loadingQuote=!1;let i=s?.quotes?.[0]?.toAmount;if(!i){sn.open({displayMessage:"Incorrect amount",debugMessage:"Please enter a valid amount"},"error");return}let a=ht.bigNumber(i).div(10**r.decimals).toString();ot.setToTokenAmount(a),ot.hasInsufficientToken(Q.sourceTokenAmount,t.address)?Q.inputError="Insufficient balance":(Q.inputError=void 0,ot.setTransactionDetails())}catch(s){let i=await ym.handleSwapError(s);Q.loadingQuote=!1,Q.inputError=i||"Insufficient balance"}},async getTransaction(){let{fromCaipAddress:e,availableToSwap:t}=ot.getParams(),r=Q.sourceToken,n=Q.toToken;if(!(!e||!t||!r||!n||Q.loadingQuote))try{Q.loadingBuildTransaction=!0;let o=await ym.fetchSwapAllowance({userAddress:e,tokenAddress:r.address,sourceTokenAmount:Q.sourceTokenAmount,sourceTokenDecimals:r.decimals}),s;return o?s=await ot.createSwapTransaction():s=await ot.createAllowanceTransaction(),Q.loadingBuildTransaction=!1,Q.fetchError=!1,s}catch{J.goBack(),Je.showError("Failed to check allowance"),Q.loadingBuildTransaction=!1,Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}},async createAllowanceTransaction(){let{fromCaipAddress:e,sourceTokenAddress:t,toTokenAddress:r}=ot.getParams();if(!(!e||!r)){if(!t)throw new Error("createAllowanceTransaction - No source token address found.");try{let n=await ze.generateApproveCalldata({from:t,to:r,userAddress:e}),o=se.getPlainAddress(n.tx.from);if(!o)throw new Error("SwapController:createAllowanceTransaction - address is required");let s={data:n.tx.data,to:o,gasPrice:BigInt(n.tx.eip155.gasPrice),value:BigInt(n.tx.value),toAmount:Q.toTokenAmount};return Q.swapTransaction=void 0,Q.approvalTransaction={data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount},{data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount}}catch{J.goBack(),Je.showError("Failed to create approval transaction"),Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}}},async createSwapTransaction(){let{networkAddress:e,fromCaipAddress:t,sourceTokenAmount:r}=ot.getParams(),n=Q.sourceToken,o=Q.toToken;if(!t||!r||!n||!o)return;let s=ee.parseUnits(r,n.decimals)?.toString();try{let i=await ze.generateSwapCalldata({userAddress:t,from:n.address,to:o.address,amount:s,disableEstimate:!0}),a=n.address===e,c=BigInt(i.tx.eip155.gas),u=BigInt(i.tx.eip155.gasPrice),d=se.getPlainAddress(i.tx.to);if(!d)throw new Error("SwapController:createSwapTransaction - address is required");let f={data:i.tx.data,to:d,gas:c,gasPrice:u,value:BigInt(a?s??"0":"0"),toAmount:Q.toTokenAmount};return Q.gasPriceInUSD=pp.getGasPriceInUSD(Q.networkPrice,c,u),Q.approvalTransaction=void 0,Q.swapTransaction=f,f}catch{J.goBack(),Je.showError("Failed to create transaction"),Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}},onEmbeddedWalletApprovalSuccess(){Je.showLoading("Approve limit increase in your wallet"),J.replace("SwapPreview")},async sendTransactionForApproval(e){let{fromAddress:t,isAuthConnector:r}=ot.getParams();Q.loadingApprovalTransaction=!0,r?J.pushTransactionStack({onSuccess:ot.onEmbeddedWalletApprovalSuccess}):Je.showLoading("Approve limit increase in your wallet");try{await ee.sendTransaction({address:t,to:e.to,data:e.data,value:e.value,chainNamespace:Z.CHAIN.EVM}),await ot.swapTokens(),await ot.getTransaction(),Q.approvalTransaction=void 0,Q.loadingApprovalTransaction=!1}catch(o){let s=o;Q.transactionError=s?.displayMessage,Q.loadingApprovalTransaction=!1,Je.showError(s?.displayMessage||"Transaction error"),Ae.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.displayMessage||s?.message||"Unknown",network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(e){if(!e)return;let{fromAddress:t,toTokenAmount:r,isAuthConnector:n}=ot.getParams();Q.loadingTransaction=!0;let o=`Swapping ${Q.sourceToken?.symbol} to ${ht.formatNumberToLocalString(r,3)} ${Q.toToken?.symbol}`,s=`Swapped ${Q.sourceToken?.symbol} to ${ht.formatNumberToLocalString(r,3)} ${Q.toToken?.symbol}`;n?J.pushTransactionStack({onSuccess(){J.replace("Account"),Je.showLoading(o),__.resetState()}}):Je.showLoading("Confirm transaction in your wallet");try{let i=[Q.sourceToken?.address,Q.toToken?.address].join(","),a=await ee.sendTransaction({address:t,to:e.to,data:e.data,value:e.value,chainNamespace:Z.CHAIN.EVM});return Q.loadingTransaction=!1,Je.showSuccess(s),Ae.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),__.resetState(),n||J.replace("Account"),__.getMyTokensWithBalance(i),a}catch(i){let a=i;Q.transactionError=a?.displayMessage,Q.loadingTransaction=!1,Je.showError(a?.displayMessage||"Transaction error"),Ae.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:a?.displayMessage||a?.message||"Unknown",network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(e,t){return pp.isInsufficientSourceTokenForSwap(e,t,Q.myTokensWithBalance)},setTransactionDetails(){let{toTokenAddress:e,toTokenDecimals:t}=ot.getParams();!e||!t||(Q.gasPriceInUSD=pp.getGasPriceInUSD(Q.networkPrice,BigInt(Q.gasFee),BigInt(Spe)),Q.priceImpact=pp.getPriceImpact({sourceTokenAmount:Q.sourceTokenAmount,sourceTokenPriceInUSD:Q.sourceTokenPriceInUSD,toTokenPriceInUSD:Q.toTokenPriceInUSD,toTokenAmount:Q.toTokenAmount}),Q.maxSlippage=pp.getMaxSlippage(Q.slippage,Q.toTokenAmount),Q.providerFee=pp.getProviderFee(Q.sourceTokenAmount))}},ot=vr(__)});var ul,ZHe,ci,Tpe=b(()=>{l();Lr();Hn();gs();ul=rt({message:"",open:!1,triggerRect:{width:0,height:0,top:0,left:0},variant:"shade"}),ZHe={state:ul,subscribe(e){return Dt(ul,()=>e(ul))},subscribeKey(e,t){return Tt(ul,e,t)},showTooltip({message:e,triggerRect:t,variant:r}){ul.open=!0,ul.message=e,ul.triggerRect=t,ul.variant=r},hide(){ul.open=!1,ul.message="",ul.triggerRect={width:0,height:0,top:0,left:0}}},ci=vr(ZHe)});var kH,UH,_pe=b(()=>{l();kH={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},UH={network:"eip155:84532",asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}}});var o5,Ppe=b(()=>{l();ai();up();gc();T_();o5={isUnsupportedChainView(){return J.state.view==="UnsupportedChain"||J.state.view==="SwitchNetwork"&&J.state.history.includes("UnsupportedChain")},async safeClose(){if(this.isUnsupportedChainView()){De.shake();return}if(await _o.isSIWXCloseDisabled()){De.shake();return}(J.state.view==="DataCapture"||J.state.view==="DataCaptureOtpConfirm")&&ee.disconnect(),De.close()}}});var ct=b(()=>{l();up();gc();$r();E_();hpe();IH();Epe();Ape();ai();AH();To();hm();Cu();y_();vH();Un();lp();Q3();mc();Ipe();_H();Tpe();OH();BH();yH();ha();bH();$n();w_();ma();T_();Ppe();gs();_pe();O6();yc();I_()});var Ope,GHe,YHe,Npe,P_,JHe,QHe,XHe,N_,R_,O_,B_,k_,U_,D_,L_,M_,H_,e$e,t$e,Rpe,$_,F_,DH=b(()=>{l();tS();Ope=Ht(ks()),GHe=Object.defineProperty,YHe=(e,t,r)=>t in e?GHe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Npe=(e,t,r)=>YHe(e,typeof t!="symbol"?t+"":t,r),P_=class extends yo{constructor(t){super(),this.opts=t,Npe(this,"protocol","wc"),Npe(this,"version",2)}},JHe=Object.defineProperty,QHe=(e,t,r)=>t in e?JHe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,XHe=(e,t,r)=>QHe(e,typeof t!="symbol"?t+"":t,r),N_=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r,XHe(this,"records",new Map)}},R_=class{constructor(t,r){this.logger=t,this.core=r}},O_=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},B_=class extends yo{constructor(t){super()}},k_=class{constructor(t,r,n,o){this.core=t,this.logger=r,this.name=n}},U_=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},D_=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r}},L_=class{constructor(t,r,n){this.core=t,this.logger=r,this.store=n}},M_=class{constructor(t,r){this.projectId=t,this.logger=r}},H_=class{constructor(t,r,n){this.core=t,this.logger=r,this.telemetryEnabled=n}},e$e=Object.defineProperty,t$e=(e,t,r)=>t in e?e$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Rpe=(e,t,r)=>t$e(e,typeof t!="symbol"?t+"":t,r),$_=class{constructor(t){this.opts=t,Rpe(this,"protocol","wc"),Rpe(this,"version",2)}},F_=class{constructor(t){this.client=t}}});var Bpe=b(()=>{l()});var kpe,Upe=b(()=>{l();kpe="0.1.1"});function Dpe(){return kpe}var Lpe=b(()=>{l();Upe()});function Mpe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?Mpe(e.cause,t):t?null:e}var zt,xm=b(()=>{l();Lpe();zt=class e extends Error{constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=`https://oxlib.sh${o??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0]:[]].filter(c=>typeof c=="string").join(` -`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Dpe()}`}),this.cause=r.cause,this.details=n,this.docs=i,this.docsPath=o,this.shortMessage=t}walk(t){return Mpe(this,t)}}});var ly,Hpe=b(()=>{l();ly=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function n$e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function uy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Su(e,...t){if(!n$e(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function $pe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");uy(e.outputLen),uy(e.blockLen)}function hp(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function z_(e,t){Su(e);let r=t.outputLen;if(e.length>>t}function s$e(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function i$e(e){for(let t=0;te().update(dy(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Vpe(e=32){if(ly&&typeof ly.getRandomValues=="function")return ly.getRandomValues(new Uint8Array(e));if(ly&&typeof ly.randomBytes=="function")return Uint8Array.from(ly.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var o$e,LH,vm,fy=b(()=>{l();Hpe();o$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;LH=o$e?e=>e:i$e;vm=class{}});function c$e(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function jpe(e,t,r){return e&t^~e&r}function qpe(e,t,r){return e&t^e&r^t&r}var q_,mp,Wpe=b(()=>{l();fy();q_=class extends vm{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=V_(this.buffer)}update(t){hp(this),t=dy(t),Su(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>Kpe&W_)}:{h:Number(e>>Kpe&W_)|0,l:Number(e&W_)|0}}function Zpe(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s{l();W_=BigInt(4294967295),Kpe=BigInt(32);Gpe=(e,t,r)=>e<>>32-r,Ype=(e,t,r)=>t<>>32-r,Jpe=(e,t,r)=>t<>>64-r,Qpe=(e,t,r)=>e<>>64-r});function y$e(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=ehe(u,d,1)^r[a],p=the(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=nhe[i],c=ehe(o,s,a),u=the(o,s,a),d=rhe[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=m$e[n],e[1]^=g$e[n]}Iu(r)}var u$e,s5,d$e,f$e,p$e,h$e,rhe,nhe,ohe,she,m$e,g$e,ehe,the,MH,w$e,ihe,ahe=b(()=>{l();Xpe();fy();u$e=BigInt(0),s5=BigInt(1),d$e=BigInt(2),f$e=BigInt(7),p$e=BigInt(256),h$e=BigInt(113),rhe=[],nhe=[],ohe=[];for(let e=0,t=s5,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],rhe.push(2*(5*n+r)),nhe.push((e+1)*(e+2)/2%64);let o=u$e;for(let s=0;s<7;s++)t=(t<>f$e)*h$e)%p$e,t&d$e&&(o^=s5<<(s5<r>32?Jpe(e,t,r):Gpe(e,t,r),the=(e,t,r)=>r>32?Qpe(e,t,r):Ype(e,t,r);MH=class e extends vm{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,uy(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return uy(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(z_(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Iu(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},w$e=(e,t,r)=>j_(()=>new MH(t,e,r)),ihe=w$e(1,136,256/8)});var b$e,Em,HH,che,lhe=b(()=>{l();Wpe();fy();b$e=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Em=new Uint32Array(64),HH=class extends q_{constructor(t=32){super(64,t,8,!1),this.A=mp[0]|0,this.B=mp[1]|0,this.C=mp[2]|0,this.D=mp[3]|0,this.E=mp[4]|0,this.F=mp[5]|0,this.G=mp[6]|0,this.H=mp[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)Em[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=Em[f-15],h=Em[f-2],y=dl(p,7)^dl(p,18)^p>>>3,w=dl(h,17)^dl(h,19)^h>>>10;Em[f]=w+Em[f-7]+y+Em[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=dl(a,6)^dl(a,11)^dl(a,25),h=d+p+jpe(a,c,u)+b$e[f]+Em[f]|0,w=(dl(n,2)^dl(n,13)^dl(n,22))+qpe(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){Iu(Em)}destroy(){this.set(0,0,0,0,0,0,0,0),Iu(this.buffer)}},che=j_(()=>new HH)});function M6(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function jH(e){if(!M6(e))throw new Error("Uint8Array expected")}function H6(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function i5(e){let t=e.toString(16);return t.length&1?"0"+t:t}function fhe(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?VH:BigInt("0x"+e)}function $6(e){if(jH(e),phe)return e.toHex();let t="";for(let r=0;r=gp._0&&e<=gp._9)return e-gp._0;if(e>=gp.A&&e<=gp.F)return e-(gp.A-10);if(e>=gp.a&&e<=gp.f)return e-(gp.a-10)}function a5(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(phe)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oVH;e>>=zH,t+=1);return t}function mhe(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=FH(e),o=FH(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=FH(0))=>{o=a(dhe([0]),f),n=a(),f.length!==0&&(o=a(dhe([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}function gy(e,t,r={}){let n=(o,s,i)=>{let a=v$e[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function KH(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var VH,zH,phe,x$e,gp,$H,my,FH,dhe,v$e,Z_=b(()=>{l();VH=BigInt(0),zH=BigInt(1);phe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",x$e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));gp={_0:48,_9:57,A:65,F:70,a:97,f:102};$H=e=>typeof e=="bigint"&&VH<=e;my=e=>(zH<new Uint8Array(e),dhe=e=>Uint8Array.from(e);v$e={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||M6(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function ghe(e,t){if(ZH(e)>t)throw new G_({givenSize:ZH(e),maxSize:t})}function GH(e){if(e>=wp.zero&&e<=wp.nine)return e-wp.zero;if(e>=wp.A&&e<=wp.F)return e-(wp.A-10);if(e>=wp.a&&e<=wp.f)return e-(wp.a-10)}function yhe(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new Y_({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;s{l();Am();wp={zero:48,nine:57,A:65,F:70,a:97,f:102}});function l5(e,t){if($i(e)>t)throw new J_({givenSize:$i(e),maxSize:t})}function bhe(e,t){if(typeof t=="number"&&t>0&&t>$i(e)-1)throw new u5({offset:t,position:"start",size:$i(e)})}function xhe(e,t,r){if(typeof t=="number"&&typeof r=="number"&&$i(e)!==r-t)throw new u5({offset:r,position:"end",size:$i(e)})}function YH(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new Q_({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function vhe(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;s{l();bp()});function Sm(e,t,r){return JSON.stringify(e,(n,o)=>typeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+A$e:o,r)}var A$e,F6=b(()=>{l();A$e="#__bigint"});function I$e(e,t={}){let{strict:r=!1}=t;if(!e)throw new X_(e);if(typeof e!="string")throw new X_(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new e7(e);if(!e.startsWith("0x"))throw new e7(e)}function wy(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Tu(e){return e instanceof Uint8Array?li(e):Array.isArray(e)?li(new Uint8Array(e)):e}function Ahe(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(l5(r,t.size),f5(r,t.size)):r}function li(e,t={}){let r="";for(let o=0;os||o{l();xm();JH();F6();C$e=new TextEncoder,S$e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));QH=class extends zt{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},X_=class extends zt{constructor(t){super(`Value \`${typeof t=="object"?Sm(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},e7=class extends zt{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},J_=class extends zt{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},u5=class extends zt{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},Q_=class extends zt{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function _$e(e){if(!(e instanceof Uint8Array)){if(!e)throw new z6(e);if(typeof e!="object")throw new z6(e);if(!("BYTES_PER_ELEMENT"in e))throw new z6(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new z6(e)}}function V6(e){return e instanceof Uint8Array?e:typeof e=="string"?h5(e):P$e(e)}function P$e(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function h5(e,t={}){let{size:r}=t,n=e;r&&(l5(e,r),n=p5(e,r));let o=n.slice(2);o.length%2&&(o=`0${o}`);let s=o.length/2,i=new Uint8Array(s);for(let a=0,c=0;a{l();xm();bp();whe();JH();F6();T$e=new TextEncoder;z6=class extends zt{constructor(t){super(`Value \`${typeof t=="object"?Sm(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},G_=class extends zt{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},Y_=class extends zt{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function t$(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=ihe(V6(e));return r==="Bytes"?n:li(n)}var r$=b(()=>{l();ahe();Am();bp()});var t7,_he=b(()=>{l();t7=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});var R$e,r7,n$=b(()=>{l();_he();R$e={checksum:new t7(8192)},r7=R$e.checksum});function Nhe(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new n7({prefix:n,cause:new i$});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new n7({prefix:n,cause:new s$});return}throw new o$({publicKey:e})}function c$(e){let t=(()=>{if(e$(e))return Rhe(e);if(Ihe(e))return O$e(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return Nhe(t),t}function O$e(e){return Rhe(li(e))}function Rhe(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new a$({publicKey:e});if(e.length===130){let n=BigInt(fl(e,0,32)),o=BigInt(fl(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(fl(e,0,1)),o=BigInt(fl(e,1,33)),s=BigInt(fl(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(fl(e,0,1)),r=BigInt(fl(e,1,33));return{prefix:t,x:r}}function Ohe(e,t={}){return h5(m5(e,t))}function m5(e,t={}){Nhe(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return wy(s?ui(r,{size:1}):"0x",ui(n,{size:32}),typeof o=="bigint"?ui(o,{size:32}):"0x")}var o$,n7,s$,i$,a$,o7=b(()=>{l();Am();xm();bp();F6();o$=class extends zt{constructor({publicKey:t}){super(`Value \`${Sm(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},n7=class extends zt{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},s$=class extends zt{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},i$=class extends zt{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},a$=class extends zt{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${$i(Tu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});function j6(e,t={}){let{strict:r=!0}=t;if(!B$e.test(e))throw new s7({address:e,cause:new u$});if(r){if(e.toLowerCase()===e)return;if(Bhe(e)!==e)throw new s7({address:e,cause:new d$})}}function Bhe(e){if(r7.has(e))return r7.get(e);j6(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=t$(She(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return r7.set(e,o),o}function k$e(e,t={}){let{checksum:r=!1}=t;return j6(e),r?Bhe(e):e}function khe(e,t={}){let r=t$(`0x${m5(e).slice(4)}`).substring(26);return k$e(`0x${r}`,t)}function Uhe(e,t){return j6(e,{strict:!1}),j6(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}var B$e,s7,u$,d$,i7=b(()=>{l();Am();n$();xm();r$();o7();B$e=/^0x[a-fA-F0-9]{40}$/;s7=class extends zt{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},u$=class extends zt{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},d$=class extends zt{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});var Dhe=b(()=>{l()});var Lhe,Mhe,Hhe,Hir,$ir,Fir,zir,Vir,jir,qir,Wir,Kir,Zir,Gir,Yir,Jir,Qir,Xir,ear,tar,rar,nar,oar,sar,iar,aar,car,lar,uar,dar,far,par,har,mar,gar,yar,war,bar,xar,Ear,Aar,Car,Sar,Iar,Tar,_ar,Par,Nar,Rar,Oar,Bar,kar,Uar,Dar,Lar,Mar,Har,$ar,Far,zar,Var,jar,qar,War,Kar,Zar,Gar,Yar,Jar,Qar,Xar,ecr,tcr,rcr,ncr,ocr,scr,icr,acr,ccr,lcr,ucr,dcr,fcr,pcr,hcr,mcr,gcr,ycr,wcr,bcr,xcr,vcr,Ecr,Acr,Ccr,Scr,Icr,p$,a7=b(()=>{l();Lhe=/^(.*)\[([0-9]*)\]$/,Mhe=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Hhe=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Hir=2n**(8n-1n)-1n,$ir=2n**(16n-1n)-1n,Fir=2n**(24n-1n)-1n,zir=2n**(32n-1n)-1n,Vir=2n**(40n-1n)-1n,jir=2n**(48n-1n)-1n,qir=2n**(56n-1n)-1n,Wir=2n**(64n-1n)-1n,Kir=2n**(72n-1n)-1n,Zir=2n**(80n-1n)-1n,Gir=2n**(88n-1n)-1n,Yir=2n**(96n-1n)-1n,Jir=2n**(104n-1n)-1n,Qir=2n**(112n-1n)-1n,Xir=2n**(120n-1n)-1n,ear=2n**(128n-1n)-1n,tar=2n**(136n-1n)-1n,rar=2n**(144n-1n)-1n,nar=2n**(152n-1n)-1n,oar=2n**(160n-1n)-1n,sar=2n**(168n-1n)-1n,iar=2n**(176n-1n)-1n,aar=2n**(184n-1n)-1n,car=2n**(192n-1n)-1n,lar=2n**(200n-1n)-1n,uar=2n**(208n-1n)-1n,dar=2n**(216n-1n)-1n,far=2n**(224n-1n)-1n,par=2n**(232n-1n)-1n,har=2n**(240n-1n)-1n,mar=2n**(248n-1n)-1n,gar=2n**(256n-1n)-1n,yar=-(2n**(8n-1n)),war=-(2n**(16n-1n)),bar=-(2n**(24n-1n)),xar=-(2n**(32n-1n)),Ear=-(2n**(40n-1n)),Aar=-(2n**(48n-1n)),Car=-(2n**(56n-1n)),Sar=-(2n**(64n-1n)),Iar=-(2n**(72n-1n)),Tar=-(2n**(80n-1n)),_ar=-(2n**(88n-1n)),Par=-(2n**(96n-1n)),Nar=-(2n**(104n-1n)),Rar=-(2n**(112n-1n)),Oar=-(2n**(120n-1n)),Bar=-(2n**(128n-1n)),kar=-(2n**(136n-1n)),Uar=-(2n**(144n-1n)),Dar=-(2n**(152n-1n)),Lar=-(2n**(160n-1n)),Mar=-(2n**(168n-1n)),Har=-(2n**(176n-1n)),$ar=-(2n**(184n-1n)),Far=-(2n**(192n-1n)),zar=-(2n**(200n-1n)),Var=-(2n**(208n-1n)),jar=-(2n**(216n-1n)),qar=-(2n**(224n-1n)),War=-(2n**(232n-1n)),Kar=-(2n**(240n-1n)),Zar=-(2n**(248n-1n)),Gar=-(2n**(256n-1n)),Yar=2n**8n-1n,Jar=2n**16n-1n,Qar=2n**24n-1n,Xar=2n**32n-1n,ecr=2n**40n-1n,tcr=2n**48n-1n,rcr=2n**56n-1n,ncr=2n**64n-1n,ocr=2n**72n-1n,scr=2n**80n-1n,icr=2n**88n-1n,acr=2n**96n-1n,ccr=2n**104n-1n,lcr=2n**112n-1n,ucr=2n**120n-1n,dcr=2n**128n-1n,fcr=2n**136n-1n,pcr=2n**144n-1n,hcr=2n**152n-1n,mcr=2n**160n-1n,gcr=2n**168n-1n,ycr=2n**176n-1n,wcr=2n**184n-1n,bcr=2n**192n-1n,xcr=2n**200n-1n,vcr=2n**208n-1n,Ecr=2n**216n-1n,Acr=2n**224n-1n,Ccr=2n**232n-1n,Scr=2n**240n-1n,Icr=2n**248n-1n,p$=2n**256n-1n});function m$(e,t){if(e.length!==t.length)throw new y$({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n{l();i7();xm();bp();a7();(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return j6(c),f5(c.toLowerCase(),o?32:0)}if(r==="string")return Che(n);if(r==="bytes")return n;if(r==="bool")return f5(Ahe(n),o?32:1);let s=r.match(Hhe);if(s){let[c,u,d="256"]=s,f=Number.parseInt(d,10)/8;return ui(n,{size:o?32:f,signed:u==="int"})}let i=r.match(Mhe);if(i){let[c,u]=i;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new g$({expectedSize:Number.parseInt(u,10),value:n});return p5(n,o?32:0)}let a=r.match(Lhe);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let f=0;f{l()});var zhe=b(()=>{l()});var Vhe=b(()=>{l()});var jhe=b(()=>{l()});var qhe=b(()=>{l()});var Whe=b(()=>{l()});var Khe=b(()=>{l()});var Zhe=b(()=>{l()});var c7,b$,Ghe=b(()=>{l();fy();c7=class extends vm{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,$pe(t);let n=dy(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew c7(e,t).update(r).digest();b$.create=(e,t)=>new c7(e,t)});function xs(e,t){let r=e%t;return r>=di?r:t+r}function Ra(e,t,r){let n=e;for(;t-- >di;)n*=n,n%=r;return n}function l7(e,t){if(e===di)throw new Error("invert: expected non-zero number");if(t<=di)throw new Error("invert: expected positive modulus, got "+t);let r=xs(e,t),n=t,o=di,s=vs,i=vs,a=di;for(;r!==di;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==vs)throw new Error("invert: does not exist");return xs(o,t)}function e0e(e,t){let r=(e.ORDER+vs)/Jhe,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function q$e(e,t){let r=(e.ORDER-Qhe)/Xhe,n=e.mul(t,by),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,by),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function W$e(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return e0e;let s=o.pow(n,t),i=(t+vs)/by;return function(c,u){if(c.is0(u))return u;if(Yhe(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=vs<(n[o]="function",n),t);return gy(e,r)}function G$e(e,t,r){if(rdi;)r&vs&&(n=e.mul(n,o)),o=e.sqr(o),r>>=vs;return n}function v$(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function Yhe(e,t){let r=(e.ORDER-vs)/by,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function E$(e,t){t!==void 0&&uy(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function g5(e,t,r=!1,n={}){if(e<=di)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=E$(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:my(o),ZERO:di,ONE:vs,create:c=>xs(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return di<=c&&cc===di,isOdd:c=>(c&vs)===vs,neg:c=>xs(-c,e),eql:(c,u)=>c===u,sqr:c=>xs(c*c,e),add:(c,u)=>xs(c+u,e),sub:(c,u)=>xs(c-u,e),mul:(c,u)=>xs(c*u,e),pow:(c,u)=>G$e(a,c,u),div:(c,u)=>xs(c*l7(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>l7(c,e),sqrt:n.sqrt||(c=>(i||(i=K$e(e)),i(a,c))),toBytes:c=>r?WH(c,s):py(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?qH(c):yp(c)},invertBatch:c=>v$(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function t0e(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function A$(e){let t=t0e(e);return t+Math.ceil(t/2)}function r0e(e,t,r=!1){let n=e.length,o=t0e(t),s=A$(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?qH(e):yp(e),a=xs(i,t-vs)+vs;return r?WH(a,o):py(a,o)}var di,vs,by,j$e,Jhe,Qhe,Xhe,Z$e,u7=b(()=>{l();fy();Z_();di=BigInt(0),vs=BigInt(1),by=BigInt(2),j$e=BigInt(3),Jhe=BigInt(4),Qhe=BigInt(5),Xhe=BigInt(8);Z$e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function C$(e,t){let r=t.negate();return e?r:t}function s0e(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function S$(e,t){s0e(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=my(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function o0e(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=_$);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function Y$e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function J$e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function T$(e){return i0e.get(e)||1}function a0e(e,t){return{constTimeNegate:C$,hasPrecomputes(r){return T$(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>n0e;)n&_$&&(o=o.add(s)),s=s.double(),n>>=_$;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=S$(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=my(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{l();u7();Z_();n0e=BigInt(0),_$=BigInt(1);I$=new WeakMap,i0e=new WeakMap});function u0e(e){e.lowS!==void 0&&H6("lowS",e.lowS),e.prehash!==void 0&&H6("prehash",e.prehash)}function Q$e(e){let t=P$(e);gy(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function N$(e,t){return $6(py(e,t))}function eFe(e){let t=Q$e(e),{Fp:r}=t,n=g5(t.n,t.nBitLength),o=t.toBytes||((E,S,_)=>{let O=S.toAffine();return c5(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,R$),X$e),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return K_(E,Po,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(M6(E)&&(E=$6(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:yp(Hi("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=xs(M,D)),hy("private key",M,Po,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=KH((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=KH(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=v$(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(Hi("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return c0e(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,R$),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,R$),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;hy("scalar",S,vp,O);let D=w.ZERO;if(S===vp)return D;if(this.is0()||S===Po)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>vp||P>vp;)N&Po&&(R=R.add(B)),P&Po&&(I=I.add(B)),B=B.double(),N>>=Po,P>>=Po;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;hy("scalar",S,Po,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===vp||P===Po||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===Po)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===Po?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return H6("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return H6("isCompressed",S),$6(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=a0e(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function tFe(e){let t=P$(e);return gy(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function d0e(e){let t=tFe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return xs(C,n)}function u(C){return l7(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=eFe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=c5;return H6("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=yp(H);if(!K_(k,Po,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&Po)===Po;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>Po;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>yp(C.slice(A,U));class v{constructor(A,U,H){hy("r",A,Po,n),hy("s",U,Po,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=Hi("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=xp.toSig(Hi("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(Hi("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+N$(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return a5(this.toDERHex())}toDERHex(){return xp.hexFromSig(this)}toCompactRawBytes(){return a5(this.toCompactHex())}toCompactHex(){let A=o;return N$(this.r,A)+N$(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=A$(t.n);return r0e(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=Hi("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=yp(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=my(s);function N(C){return hy("num < 2^"+s,C,vp,M),py(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=Hi("msgHash",C),u0e(U),j&&(C=Hi("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(Hi("extraEntropy",ye))}let pe=c5(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===vp)return;let ur=c(Et*c(me+At*te));if(ur===vp)return;let _r=(kt.x===At?0:2)|Number(kt.y&Po),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return mhe(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=Hi("msgHash",A),U=Hi("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(u0e(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||M6(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof xp.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}var O$,xp,vp,Po,Jcr,R$,X$e,f0e=b(()=>{l();l0e();u7();Z_();O$=class extends Error{constructor(t=""){super(t)}},xp={Err:O$,_tlv:{encode:(e,t)=>{let{Err:r}=xp;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=i5(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?i5(o.length/2|128):"";return i5(e)+s+o+t},decode(e,t){let{Err:r}=xp,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=xp;if(eb$(e,t,zpe(...r)),randomBytes:Vpe}}function p0e(e,t){let r=n=>d0e({...e,...rFe(n)});return{...r(t),create:r}}var h0e=b(()=>{l();Ghe();fy();f0e();});function sFe(e){let t=y0e,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=Ra(d,r,t)*d%t,p=Ra(f,r,t)*d%t,h=Ra(p,B$,t)*u%t,y=Ra(h,o,t)*h%t,w=Ra(y,s,t)*y%t,x=Ra(w,a,t)*w%t,v=Ra(x,c,t)*x%t,T=Ra(v,a,t)*w%t,E=Ra(T,r,t)*d%t,S=Ra(E,i,t)*y%t,_=Ra(S,n,t)*u%t,O=Ra(_,B$,t);if(!k$.eql(k$.sqr(O),e))throw new Error("Cannot find square root");return O}var y0e,m0e,nFe,oFe,B$,g0e,k$,Oa,U$=b(()=>{l();lhe();h0e();u7();y0e=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),m0e=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),nFe=BigInt(0),oFe=BigInt(1),B$=BigInt(2),g0e=(e,t)=>(e+t/B$)/t;k$=g5(y0e,void 0,void 0,{sqrt:sFe}),Oa=p0e({a:nFe,b:BigInt(7),Fp:k$,n:m0e,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=m0e,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-oFe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=g0e(s*e,t),c=g0e(-n*e,t),u=xs(e-a*r-c*o,t),d=xs(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},che)});var y7={};Te(y7,{InvalidRError:()=>f7,InvalidSError:()=>p7,InvalidSerializedSizeError:()=>d7,InvalidVError:()=>h7,InvalidYParityError:()=>xy,MissingPropertiesError:()=>q6,assert:()=>m7,extract:()=>iFe,from:()=>L$,fromBytes:()=>w0e,fromDerBytes:()=>aFe,fromDerHex:()=>b0e,fromHex:()=>D$,fromLegacy:()=>x0e,fromRpc:()=>v0e,fromTuple:()=>cFe,toBytes:()=>lFe,toDerBytes:()=>uFe,toDerHex:()=>dFe,toHex:()=>E0e,toLegacy:()=>fFe,toRpc:()=>pFe,toTuple:()=>hFe,vToYParity:()=>g7,validate:()=>mFe,yParityToV:()=>M$});function m7(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new q6({signature:e});if(typeof e.s>"u")throw new q6({signature:e});if(r&&typeof e.yParity>"u")throw new q6({signature:e});if(e.r<0n||e.r>p$)throw new f7({value:e.r});if(e.s<0n||e.s>p$)throw new p7({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new xy({value:e.yParity})}function w0e(e){return D$(li(e))}function D$(e){if(e.length!==130&&e.length!==132)throw new d7({signature:e});let t=BigInt(fl(e,0,32)),r=BigInt(fl(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return g7(o)}catch{throw new xy({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function iFe(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return L$(e)}function L$(e){let t=typeof e=="string"?D$(e):e instanceof Uint8Array?w0e(e):typeof e.r=="string"?v0e(e):e.v?x0e(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return m7(t),t}function aFe(e){return b0e(li(e))}function b0e(e){let{r:t,s:r}=Oa.Signature.fromDER(Tu(e).slice(2));return{r:t,s:r}}function x0e(e){return{r:e.r,s:e.s,yParity:g7(e.v)}}function v0e(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=g7(r)),typeof n!="number")throw new xy({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function cFe(e){let[t,r,n]=e;return L$({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function lFe(e){return h5(E0e(e))}function E0e(e){m7(e);let t=e.r,r=e.s;return wy(ui(t,{size:32}),ui(r,{size:32}),typeof e.yParity=="number"?ui(M$(e.yParity),{size:1}):"0x")}function uFe(e){return new Oa.Signature(e.r,e.s).toDERRawBytes()}function dFe(e){return`0x${new Oa.Signature(e.r,e.s).toDERHex()}`}function fFe(e){return{r:e.r,s:e.s,v:M$(e.yParity)}}function pFe(e){let{r:t,s:r,yParity:n}=e;return{r:ui(t,{size:32}),s:ui(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function hFe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":XH(ui(t)),r===0n?"0x":XH(ui(r))]}function mFe(e,t={}){try{return m7(e,t),!0}catch{return!1}}function g7(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new h7({value:e})}function M$(e){if(e===0)return 27;if(e===1)return 28;throw new xy({value:e})}var d7,q6,f7,p7,xy,h7,A0e=b(()=>{l();U$();Am();xm();bp();F6();a7();d7=class extends zt{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${$i(Tu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},q6=class extends zt{constructor({signature:t}){super(`Signature \`${Sm(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},f7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},p7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},xy=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},h7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}});var C0e=b(()=>{l()});var S0e=b(()=>{l()});var hlr,mlr,I0e=b(()=>{l();hlr=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),mlr={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var T0e=b(()=>{l()});var _0e=b(()=>{l()});var P0e,vFe,N0e,EFe,blr,R0e=b(()=>{l();P0e=6,vFe=32,N0e=4096,EFe=vFe*N0e,blr=EFe*P0e-1-1*N0e*P0e});var O0e=b(()=>{l()});var B0e=b(()=>{l()});var k0e=b(()=>{l()});var U0e=b(()=>{l()});var D0e=b(()=>{l()});var L0e=b(()=>{l()});var M0e=b(()=>{l()});var H0e=b(()=>{l()});var $0e=b(()=>{l()});var F0e=b(()=>{l();pZ()});var z0e=b(()=>{l()});var V0e=b(()=>{l()});var j0e,q0e=b(()=>{l();j0e=!1});var w7={};Te(w7,{createKeyPair:()=>LFe,getPublicKey:()=>W0e,getSharedSecret:()=>MFe,noble:()=>DFe,randomPrivateKey:()=>K0e,recoverAddress:()=>Z0e,recoverPublicKey:()=>G0e,sign:()=>HFe,verify:()=>$Fe});function LFe(e={}){let{as:t="Hex"}=e,r=K0e({as:t}),n=W0e({privateKey:r});return{privateKey:r,publicKey:n}}function W0e(e){let{privateKey:t}=e,r=Oa.ProjectivePoint.fromPrivateKey(Tu(t).slice(2));return c$(r)}function MFe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,i=Oa.ProjectivePoint.fromHex(m5(n).slice(2)).multiply(Oa.utils.normPrivateKeyToScalar(Tu(r).slice(2))).toRawBytes(!0);return t==="Hex"?li(i):i}function K0e(e={}){let{as:t="Hex"}=e,r=Oa.utils.randomPrivateKey();return t==="Hex"?li(r):r}function Z0e(e){return khe(G0e(e))}function G0e(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new Oa.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Tu(t).substring(2));return c$(a)}function HFe(e){let{extraEntropy:t=j0e,hash:r,payload:n,privateKey:o}=e,{r:s,s:i,recovery:a}=Oa.sign(V6(n),V6(o),{extraEntropy:typeof t=="boolean"?t:Tu(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function $Fe(e){let{address:t,hash:r,payload:n,publicKey:o,signature:s}=e;return t?Uhe(t,Z0e({payload:n,signature:s})):Oa.verify(s,V6(n),Ohe(o),...r?[{prehash:!0,lowS:!0}]:[])}var DFe,Y0e=b(()=>{l();U$();i7();Am();bp();q0e();o7();DFe=Oa});var J0e=b(()=>{l()});var Q0e=b(()=>{l()});var X0e=b(()=>{l()});var eme=b(()=>{l();kZ()});var tme=b(()=>{l()});var rme=b(()=>{l()});var Fi,H$,$$,F$,z$,V$,j$,q$,W$,K$,Z$,G$,Y$,nme=b(()=>{l();Fi=class extends Error{constructor(t){let{cause:r,code:n,message:o,data:s,stack:i}=t;super(o,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.BaseError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=r,this.code=n,this.data=s,this.stack=i??""}},H$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Missing or invalid parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidInputError"})}};Object.defineProperty(H$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});$$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not found."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceNotFoundError"})}};Object.defineProperty($$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});F$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not available."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceUnavailableError"})}};Object.defineProperty(F$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});z$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Transaction creation failed."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.TransactionRejectedError"})}};Object.defineProperty(z$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});V$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method is not implemented."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotSupportedError"})}};Object.defineProperty(V$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});j$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Rate limit exceeded."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.LimitExceededError"})}};Object.defineProperty(j$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});q$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"JSON-RPC version not supported."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.VersionNotSupportedError"})}};Object.defineProperty(q$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});W$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Input is not a valid JSON-RPC request."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidRequestError"})}};Object.defineProperty(W$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});K$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method does not exist."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotFoundError"})}};Object.defineProperty(K$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Z$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Invalid method parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidParamsError"})}};Object.defineProperty(Z$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});G$=class e extends Fi{constructor(t={}){super({cause:t.cause,code:e.code,data:t.data,message:t.message??"Internal JSON-RPC error.",stack:t.stack}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InternalError"})}};Object.defineProperty(G$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Y$=class e extends Fi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Failed to parse JSON-RPC response."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ParseError"})}};Object.defineProperty(Y$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700})});var fi,J$,Q$,X$,eF,tF,rF,nF,oF,sF,iF,aF,cF,lF,ome=b(()=>{l();MZ();fi=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderRpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}},J$=class extends fi{constructor({message:t="The user rejected the request."}={}){super(4001,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UserRejectedRequestError"})}};Object.defineProperty(J$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});Q$=class extends fi{constructor({message:t="The requested method and/or account has not been authorized by the user."}={}){super(4100,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnauthorizedError"})}};Object.defineProperty(Q$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});X$=class extends fi{constructor({message:t="The provider does not support the requested method."}={}){super(4200,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedMethodError"})}};Object.defineProperty(X$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});eF=class extends fi{constructor({message:t="The provider is disconnected from all chains."}={}){super(4900,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DisconnectedError"})}};Object.defineProperty(eF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});tF=class extends fi{constructor({message:t="The provider is not connected to the requested chain."}={}){super(4901,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.ChainDisconnectedError"})}};Object.defineProperty(tF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});rF=class extends fi{constructor({message:t="An error occurred when attempting to switch chain."}={}){super(4902,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.SwitchChainError"})}};Object.defineProperty(rF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});nF=class extends fi{constructor({message:t="This Wallet does not support a capability that was not marked as optional."}={}){super(5700,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedNonOptionalCapabilityError"})}};Object.defineProperty(nF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});oF=class extends fi{constructor({message:t="This Wallet does not support the requested chain ID."}={}){super(5710,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedChainIdError"})}};Object.defineProperty(oF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});sF=class extends fi{constructor({message:t="There is already a bundle submitted with this ID."}={}){super(5720,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DuplicateIdError"})}};Object.defineProperty(sF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});iF=class extends fi{constructor({message:t="This bundle id is unknown / has not been submitted."}={}){super(5730,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnknownBundleIdError"})}};Object.defineProperty(iF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});aF=class extends fi{constructor({message:t="The call bundle is too large for the Wallet to process."}={}){super(5740,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.BundleTooLargeError"})}};Object.defineProperty(aF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});cF=class extends fi{constructor({message:t="The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."}={}){super(5750,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicReadyWalletRejectedUpgradeError"})}};Object.defineProperty(cF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});lF=class extends fi{constructor({message:t="The wallet does not support atomic execution but the request requires it."}={}){super(5760,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicityNotSupportedError"})}};Object.defineProperty(lF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760})});var sme=b(()=>{l()});var ime=b(()=>{l()});var ame=b(()=>{l()});var cme=b(()=>{l()});var lme=b(()=>{l()});var ume=b(()=>{l()});var dme=b(()=>{l()});var fme=b(()=>{l()});var pme=b(()=>{l()});var hme=b(()=>{l()});var mme=b(()=>{l()});var gme=b(()=>{l()});var yme=b(()=>{l()});var wme=b(()=>{l()});var bme=b(()=>{l()});var xme=b(()=>{l()});var pur,vme=b(()=>{l();pur=Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233])});var Eme=b(()=>{l()});var Ame=b(()=>{l()});var Cme=b(()=>{l();Bpe();Fhe();zhe();Vhe();jhe();Dhe();$he();qhe();Whe();i7();Khe();C0e();S0e();I0e();T0e();R0e();k0e();U0e();D0e();L0e();M0e();Am();n$();H0e();$0e();F0e();xm();z0e();V0e();r$();J0e();bp();F6();Q0e();_0e();X0e();eme();tme();rme();ome();o7();Zhe();sme();nme();ime();ame();Y0e();A0e();cme();a7();lme();O0e();dme();fme();pme();hme();mme();gme();yme();wme();bme();xme();ume();vme();Eme();B0e();Ame()});function Sme(e){let t=e.length,r=0,n=0;for(;n=55296&&o<=56319&&n>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}function yze(e,t,r){mze.encodeInto(e,t.subarray(r))}function Ime(e,t,r){e.length>gze?yze(e,t,r):hze(e,t,r)}function uF(e,t,r){let n=t,o=n+r,s=[],i="";for(;n65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=wze&&(i+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(i+=String.fromCharCode(...s)),i}function vze(e,t,r){let n=e.subarray(t,t+r);return bze.decode(n)}function Tme(e,t,r){return r>xze?vze(e,t,r):uF(e,t,r)}var mze,gze,wze,bze,xze,b7=b(()=>{l();mze=new TextEncoder,gze=50;wze=4096;bze=new TextDecoder,xze=200});var vy,_me=b(()=>{l();vy=class{constructor(t,r){this.type=t,this.data=r}}});var zi,dF=b(()=>{l();zi=class e extends Error{constructor(t){super(t);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}});function Pme(e,t,r){let n=r/4294967296,o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function x7(e,t,r){let n=Math.floor(r/4294967296),o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function v7(e,t){let r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function Nme(e,t){let r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}var E7=b(()=>{l()});function Sze({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=Cze)if(t===0&&e<=Aze){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|r&3),s.setUint32(4,n),o}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),x7(n,4,e),r}}function Ize(e){let t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,o=Math.floor(n/1e9);return{sec:r+o,nsec:n-o*1e9}}function Tze(e){if(e instanceof Date){let t=Ize(e);return Sze(t)}else return null}function _ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let r=t.getUint32(0),n=t.getUint32(4),o=(r&3)*4294967296+n,s=r>>>2;return{sec:o,nsec:s}}case 12:{let r=v7(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new zi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Pze(e){let t=_ze(e);return new Date(t.sec*1e3+t.nsec/1e6)}var Eze,Aze,Cze,Rme,Ome=b(()=>{l();dF();E7();Eze=-1,Aze=4294967296-1,Cze=17179869184-1;Rme={type:Eze,encode:Tze,decode:Pze}});var Im,fF=b(()=>{l();_me();Ome();Im=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Rme)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{let o=-1-t;this.builtInEncoders[o]=r,this.builtInDecoders[o]=n}}tryToEncode(t,r){for(let n=0;n{l()});var Rze,Oze,A7,Bme=b(()=>{l();b7();fF();E7();pF();Rze=100,Oze=2048,A7=class e{constructor(t){this.entered=!1,this.extensionCodec=t?.extensionCodec??Im.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??Rze,this.initialBufferSize=t?.initialBufferSize??Oze,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){let r=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let n=Sme(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Ime(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){let n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let n=y5(t);this.writeU8a(n)}encodeArray(t,r){let n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let o of t)this.doEncode(o,r+1)}countWithoutUndefined(t,r){let n=0;for(let o of r)t[o]!==void 0&&n++;return n}encodeMap(t,r){let n=Object.keys(t);this.sortKeys&&n.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of n){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){let n=t.data(this.pos+6),o=n.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(n);return}let r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),Pme(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),x7(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}});function hF(e,t){return new A7(t).encodeSharedRef(e)}var kme=b(()=>{l();Bme()});function C7(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}var Ume=b(()=>{l()});var Bze,kze,S7,Dme=b(()=>{l();b7();Bze=16,kze=16,S7=class{constructor(t=Bze,r=kze){this.hit=0,this.miss=0,this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n0&&t<=this.maxKeyLength}find(t,r,n){let o=this.caches[n-1];e:for(let s of o){let i=s.bytes;for(let a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)}decode(t,r,n){let o=this.find(t,r,n);if(o!=null)return this.hit++,o;this.miss++;let s=uF(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,s),s}}});var mF,x5,Mme,Uze,gF,b5,yF,Dze,Lme,Lze,I7,Hme=b(()=>{l();Ume();fF();E7();b7();pF();Dme();dF();mF="array",x5="map_key",Mme="map_value",Uze=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new zi("The type of key must be string or number but "+typeof e)},gF=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let r=this.getUninitializedStateFromPool();r.type=mF,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){let r=this.getUninitializedStateFromPool();r.type=x5,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===mF){let n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===x5||t.type===Mme){let n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},b5=-1,yF=new DataView(new ArrayBuffer(0)),Dze=new Uint8Array(yF.buffer);try{yF.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}Lme=new RangeError("Insufficient data"),Lze=new S7,I7=class e{constructor(t){this.totalPos=0,this.pos=0,this.view=yF,this.bytes=Dze,this.headByte=b5,this.stack=new gF,this.entered=!1,this.extensionCodec=t?.extensionCodec??Im.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??4294967295,this.maxBinLength=t?.maxBinLength??4294967295,this.maxArrayLength=t?.maxArrayLength??4294967295,this.maxMapLength=t?.maxMapLength??4294967295,this.maxExtLength=t?.maxExtLength??4294967295,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:Lze,this.mapKeyConverter=t?.mapKeyConverter??Uze}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=b5,this.stack.reset()}setBuffer(t){let r=y5(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===b5&&!this.hasRemaining(1))this.setBuffer(t);else{let r=this.bytes.subarray(this.pos),n=y5(t),o=new Uint8Array(r.length+n.length);o.set(r),o.set(n,r.length),this.setBuffer(o)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(let a of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:o,pos:s,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${C7(o)} at ${i} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,o=-1;for await(let s of t){if(r&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){let o=t-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t<160){let o=t-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else{let o=t-160;r=this.decodeString(o,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){let o=this.lookU8();r=this.decodeString(o,1)}else if(t===218){let o=this.lookU16();r=this.decodeString(o,2)}else if(t===219){let o=this.lookU32();r=this.decodeString(o,4)}else if(t===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===196){let o=this.lookU8();r=this.decodeBinary(o,1)}else if(t===197){let o=this.lookU16();r=this.decodeBinary(o,2)}else if(t===198){let o=this.lookU32();r=this.decodeBinary(o,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){let o=this.lookU8();r=this.decodeExtension(o,1)}else if(t===200){let o=this.lookU16();r=this.decodeExtension(o,2)}else if(t===201){let o=this.lookU32();r=this.decodeExtension(o,4)}else throw new zi(`Unrecognized type byte: ${C7(t)}`);this.complete();let n=this.stack;for(;n.length>0;){let o=n.top();if(o.type===mF)if(o.array[o.position]=r,o.position++,o.position===o.size)r=o.array,n.release(o);else continue e;else if(o.type===x5){if(r==="__proto__")throw new zi("The key __proto__ is not allowed");o.key=this.mapKeyConverter(r),o.type=Mme;continue e}else if(o.map[o.key]=r,o.readCount++,o.readCount===o.size)r=o.map,n.release(o);else{o.key=null,o.type=x5;continue e}}return r}}readHeadByte(){return this.headByte===b5&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=b5}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new zi(`Unrecognized array type byte: ${C7(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new zi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new zi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new zi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===x5:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new zi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw Lme;let n=this.pos+r,o=this.bytes.subarray(n,n+t);return this.pos+=r+t,o}decodeExtension(t,r){if(t>this.maxExtLength)throw new zi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+r),o=this.decodeBinary(t,r+1);return this.extensionCodec.decode(o,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){let t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){let t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){let t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){let t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){let t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){let t=Nme(this.view,this.pos);return this.pos+=8,t}readI64(){let t=v7(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){let t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){let t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){let t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){let t=this.view.getFloat64(this.pos);return this.pos+=8,t}}});function wF(e,t){return new I7(t).decode(e)}var $me=b(()=>{l();Hme()});var Fme=b(()=>{l();kme();$me()});function bl(e){let[t,r]=e.split(Mze);return{namespace:t,reference:r}}function C1e(e,t){return e.includes(":")?[e]:t.chains||[]}function P5(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function _p(){return!(0,yl.getDocument)()&&!!(0,yl.getNavigator)()&&navigator.product===qze}function S1e(){return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function I1e(){return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Ty(){return!P5()&&!!(0,yl.getNavigator)()&&!!(0,yl.getDocument)()}function N5(){return _p()?ji.reactNative:P5()?ji.node:Ty()?ji.browser:ji.unknown}function JF(){var e;try{return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(e=global.Application)==null?void 0:e.applicationId:void 0}catch{return}}function Kze(e,t){let r=new URLSearchParams(e);return Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!=null&&r.set(n,String(o))}),r.toString()}function T1e(e){var t,r;let n=QF();try{return e!=null&&e.url&&n.url&&new URL(e.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),e.url=n.url),(t=e?.icons)!=null&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(o=>o!=="")),jze(Vme(Vme({},n),e),{url:e?.url||n.url,name:e?.name||n.name,description:e?.description||n.description,icons:(r=e?.icons)!=null&&r.length&&e.icons.length>0?e.icons:n.icons})}catch(o){return console.warn("Error populating app metadata",o),e||n}}function QF(){return(0,E1e.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function Zze(){if(N5()===ji.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let e=iA();if(e===null)return"unknown";let t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function Gze(){var e;let t=N5();return t===ji.browser?[t,((e=(0,yl.getLocation)())==null?void 0:e.host)||"unknown"].join(":"):t}function XF(e,t,r){let n=Zze(),o=Gze();return[[e,t].join("-"),[Wze,r].join("-"),n,o].join("/")}function _1e({protocol:e,version:t,relayUrl:r,sdkVersion:n,auth:o,projectId:s,useOnCloseEvent:i,bundleId:a,packageName:c}){let u=r.split("?"),d=XF(e,t,n),f={auth:o,ua:d,projectId:s,useOnCloseEvent:i||void 0,packageName:c||void 0,bundleId:a||void 0},p=Kze(u[1]||"",f);return u[0]+"?"+p}function Ey(e,t){return e.filter(r=>t.includes(r)).length===e.length}function $7(e){return Object.fromEntries(e.entries())}function F7(e){return new Map(Object.entries(e))}function Pp(e=Ip.FIVE_MINUTES,t){let r=(0,Ip.toMiliseconds)(e||Ip.FIVE_MINUTES),n,o,s,i;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),i=Promise.resolve(a))},reject:a=>{s&&o&&(clearTimeout(s),o(a))},done:()=>new Promise((a,c)=>{if(i)return a(i);s=setTimeout(()=>{let u=new Error(t);i=Promise.reject(u),c(u)},r),n=a,o=c})}}function xl(e,t,r){return new Promise(async(n,o)=>{let s=setTimeout(()=>o(new Error(r)),t);try{let i=await e;n(i)}catch(i){o(i)}clearTimeout(s)})}function P1e(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function N1e(e){return P1e("topic",e)}function R1e(e){return P1e("id",e)}function z7(e){let[t,r]=e.split(":"),n={id:void 0,topic:void 0};if(t==="topic"&&typeof r=="string")n.topic=r;else if(t==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);return n}function pn(e,t){return(0,Ip.fromMiliseconds)((t||Date.now())+(0,Ip.toMiliseconds)(e))}function ka(e){return Date.now()>=(0,Ip.toMiliseconds)(e)}function cr(e,t){return`${e}${t?`:${t}`:""}`}function ml(e=[],t=[]){return[...new Set([...e,...t])]}async function O1e({id:e,topic:t,wcDeepLink:r}){var n;try{if(!r)return;let o=typeof r=="string"?JSON.parse(r):r,s=o?.href;if(typeof s!="string")return;let i=Yze(s,e,t),a=N5();if(a===ji.browser){if(!((n=(0,yl.getDocument)())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Jze(i)}else a===ji.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(i)}catch(o){console.error(o)}}function Yze(e,t,r){let n=`requestId=${t}&sessionTopic=${r}`;e.endsWith("/")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith("https://t.me")){let s=e.includes("?")?"&startapp=":"?startapp=";o=`${o}${s}${eVe(n,!0)}`}else o=`${o}/wc?${n}`;return o}function Jze(e){let t="_self";Xze()?t="_top":(Qze()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function B1e(e,t){let r="";try{if(Ty()&&(r=localStorage.getItem(t),r))return r;r=await e.getItem(t)}catch(n){console.error(n)}return r}function ez(e,t){if(!e.includes(t))return null;let r=e.split(/([&,?,=])/),n=r.indexOf(t);return r[n+2]}function tz(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function R5(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function Qze(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Xze(){try{return window.self!==window.top}catch{return!1}}function eVe(e,t=!1){let r=Buffer.from(e).toString("base64");return t?r.replace(/[=]/g,""):r}function k1e(e){return Buffer.from(e,"base64").toString("utf-8")}function U1e(e){return new Promise(t=>setTimeout(t,e))}function D1e(e,t=!1){return t?{h:Number(e&T7),l:Number(e>>qme&T7)}:{h:Number(e>>qme&T7)|0,l:Number(e&T7)|0}}function L1e(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}function V7(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Tp(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wl(e,...t){if(!V7(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function j7(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Tp(e.outputLen),Tp(e.blockLen)}function Mm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oz(e,t){wl(e);let r=t.outputLen;if(e.length>>t}function H1e(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function dVe(e){for(let t=0;t=Ep._0&&e<=Ep._9)return e-Ep._0;if(e>=Ep.A&&e<=Ep.F)return e-(Ep.A-10);if(e>=Ep.a&&e<=Ep.f)return e-(Ep.a-10)}function B7(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if($1e)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oe().update(gl(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function pVe(e){let t=(n,o)=>e(o).update(gl(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function _y(e=32){if(W6&&typeof W6.getRandomValues=="function")return W6.getRandomValues(new Uint8Array(e));if(W6&&typeof W6.randomBytes=="function")return Uint8Array.from(W6.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function vVe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=Gme(u,d,1)^r[a],p=Yme(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=V1e[i],c=Gme(o,s,a),u=Yme(o,s,a),d=z1e[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=bVe[n],e[1]^=xVe[n]}bc(r)}function CVe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function SVe(e,t,r){return e&t^~e&r}function IVe(e,t,r){return e&t^e&r^t&r}function Rm(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=ke[2*e],u=ke[2*e+1],d=ke[2*t],f=ke[2*t+1],p=ke[2*r],h=ke[2*r+1],y=ke[2*n],w=ke[2*n+1],x=rz(c,d,i);u=nz(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:tVe(w,y),Dl:rVe(w)},{h,l:p}=hl(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:Bm(f,d,24),Bl:km(f,d,24)},ke[2*e]=c,ke[2*e+1]=u,ke[2*t]=d,ke[2*t+1]=f,ke[2*r]=p,ke[2*r+1]=h,ke[2*n]=y,ke[2*n+1]=w}function Om(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=ke[2*e],u=ke[2*e+1],d=ke[2*t],f=ke[2*t+1],p=ke[2*r],h=ke[2*r+1],y=ke[2*n],w=ke[2*n+1],x=rz(c,d,i);u=nz(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:Bm(w,y,16),Dl:km(w,y,16)},{h,l:p}=hl(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:A5(f,d,63),Bl:C5(f,d,63)},ke[2*e]=c,ke[2*e+1]=u,ke[2*t]=d,ke[2*t+1]=f,ke[2*r]=p,ke[2*r+1]=h,ke[2*n]=y,ke[2*n+1]=w}function kVe(e,t={},r,n,o){if(Tp(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");let{key:s,salt:i,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(i!==void 0&&i.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==o)throw new Error("personalization must be undefined or "+o)}function K1e(e){let t=`Ethereum Signed Message: -${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toString("hex")}async function LVe(e,t,r,n,o,s){switch(r.t){case"eip191":return await MVe(e,t,r.s);case"eip1271":return await HVe(e,t,r.s,n,o,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function MVe(e,t,r){let n=y7.fromHex(r);return w7.recoverAddress({payload:K1e(t),signature:n}).toLowerCase()===e.toLowerCase()}async function HVe(e,t,r,n,o,s){let i=bl(n);if(!i.namespace||!i.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{let a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),d=(u.length/2).toString(16).padStart(64,"0"),f=(t.startsWith("0x")?t:K1e(t)).substring(2),p=a+f+c+d+u,h=await fetch(`${s||DVe}/?chainId=${n}&projectId=${o}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:$Ve(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:p},"latest"]})}),{result:y}=await h.json();return y?y.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function $Ve(){return Date.now()+Math.floor(Math.random()*1e3)}function Z1e(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;is.charCodeAt(0)),n=new Uint8Array(r.length+t.length);n.set(r),n.set(t,r.length);let o=UVe(n,{dkLen:32});return wm.encode(o)}function sz(e){let t=new Uint8Array(q7(FVe(e)));return wm.encode(t)}function FVe(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(typeof e=="object"&&e!=null&&e.data)return new Uint8Array(Object.values(e.data));if(typeof e=="object"&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function iz(e){let t=Buffer.from(e,"base64"),r=wF(t).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");let n=hF(r),o=Buffer.from("TX"),s=Buffer.concat([o,Buffer.from(n)]),i=OVe(s);return KA.encode(i).replace(/=+$/,"")}function xF(e){let t=[],r=BigInt(e);for(;r>=BigInt(128);)t.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return t.push(Number(r)),Buffer.from(t)}function Y1e(e){let t=Buffer.from(e.signed.bodyBytes,"base64"),r=Buffer.from(e.signed.authInfoBytes,"base64"),n=Buffer.from(e.signature.signature,"base64"),o=[];o.push(Buffer.from([10])),o.push(xF(t.length)),o.push(t),o.push(Buffer.from([18])),o.push(xF(r.length)),o.push(r),o.push(Buffer.from([26])),o.push(xF(n.length)),o.push(n);let s=Buffer.concat(o),i=q7(s);return Buffer.from(i).toString("hex").toUpperCase()}function J1e(e){var t,r;let n=[];try{if(typeof e=="string")return n.push(e),n;if(typeof e!="object")return n;e!=null&&e.id&&n.push(e.id);let o=(r=(t=e?.capabilities)==null?void 0:t.caip345)==null?void 0:r.transactionHashes;o&&n.push(...o)}catch(o){console.warn("getWalletSendCallsHashes failed: ",o)}return n}async function az(e){let{cacao:t,projectId:r}=e,{s:n,p:o}=t,s=cz(o,o.iss),i=B5(o.iss);return await LVe(i,s,n,K7(o.iss),r)}function XVe(e){return Buffer.from(JSON.stringify(e)).toString("base64")}function eje(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}function Iy(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");let t=Object.keys(e.att);if(!(t!=null&&t.length))throw new Error("No resources found in `att` property");t.forEach(r=>{let n=e.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(o=>{let s=n[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!="object")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function tje(e,t,r,n={}){return r?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:rje(t,r,n)}}}function rje(e,t,r={}){t=t?.sort((o,s)=>o.localeCompare(s));let n=t.map(o=>({[`${e}/${o}`]:[r]}));return Object.assign({},...n)}function X1e(e){return Iy(e),`urn:recap:${XVe(e).replace(/=/g,"")}`}function _5(e){let t=eje(e.replace("urn:recap:",""));return Iy(t),t}function ege(e,t,r){let n=tje(e,t,r);return X1e(n)}function nje(e){return e&&e.includes("urn:recap:")}function tge(e,t){let r=_5(e),n=_5(t),o=oje(r,n);return X1e(o)}function oje(e,t){Iy(e),Iy(t);let r=Object.keys(e.att).concat(Object.keys(t.att)).sort((o,s)=>o.localeCompare(s)),n={att:{}};return r.forEach(o=>{var s,i;Object.keys(((s=e.att)==null?void 0:s[o])||{}).concat(Object.keys(((i=t.att)==null?void 0:i[o])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;n.att[o]=ZVe(KVe({},n.att[o]),{[a]:((c=e.att[o])==null?void 0:c[a])||((u=t.att[o])==null?void 0:u[a])})})}),n}function sje(e="",t){Iy(t);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(r))return e;let n=[],o=0;Object.keys(t.att).forEach(a=>{let c=Object.keys(t.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,p)=>f.action.localeCompare(p.action));let u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});let d=Object.keys(u).map(f=>(o++,`(${o}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});let s=n.join(" "),i=`${r}${s}`;return`${e?e+" ":""}${i}`}function lz(e){var t;let r=_5(e);Iy(r);let n=(t=r.att)==null?void 0:t.eip155;return n?Object.keys(n).map(o=>o.split("/")[1]):[]}function uz(e){let t=_5(e);Iy(t);let r=[];return Object.values(t.att).forEach(n=>{Object.values(n).forEach(o=>{var s;(s=o?.[0])!=null&&s.chains&&r.push(o[0].chains)})}),[...new Set(r.flat())]}function k5(e){if(!e)return;let t=e?.[e.length-1];return nje(t)?t:void 0}function rge(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function MF(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function vF(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Vi(e,...t){if(!rge(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Xme(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ije(e,t){Vi(e);let r=t.outputLen;if(e.length>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function pje(e,t,r){MF(r);let n=new Uint8Array(16),o=aje(n);return t1e(o,0,BigInt(t),r),t1e(o,8,BigInt(e),r),n}function hje(e){return e.byteOffset%4===0}function $F(e){return Uint8Array.from(e)}function tr(e,t){return e<>>32-t}function FF(e){return e.byteOffset%4===0}function xje(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(_7),d=Lm(u),f=FF(o)&&FF(s),p=f?Lm(o):r1e,h=f?Lm(s):r1e;for(let y=0;y=oge)throw new Error("arx: counter overflow");let w=Math.min(_7,c-y);if(f&&w===_7){let x=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,T;v{Vi(a),Vi(c),Vi(u);let p=u.length;if(d===void 0&&(d=new Uint8Array(p)),Vi(d),vF(f),f<0||f>=oge)throw new Error("arx: counter overflow");if(d.lengthe(o).update(HF(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Cje(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],p=t[2],h=t[3],y=t[4],w=t[5],x=t[6],v=t[7],T=o,E=r[0],S=r[1],_=r[2],O=i,D=a,M=c,N=u,L=d,P=f,R=p,I=h,B=y,C=w,A=x,U=v,H=T,k=E,F=S,j=_;for(let ae=0;ae255*o)throw new Error("Length should be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0&&(r=s1e);let i=new Uint8Array(s*o),a=Z7.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;ddz;e>>=VF,t+=1);return t}function Bje(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),o=p=>Uint8Array.of(p),s=n(e),i=n(e),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...p)=>r(i,s,...p),d=(p=n(0))=>{i=u(o(0),p),s=u(),p.length!==0&&(i=u(o(1),p),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,h=[];for(;p{c(),d(p);let y;for(;!(y=h(f()));)d();return c(),y}}function J7(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function i1e(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}function Ba(e,t){let r=e%t;return r>=qi?r:t+r}function pl(e,t,r){let n=e;for(;t-- >qi;)n*=n,n%=r;return n}function a1e(e,t){if(e===qi)throw new Error("invert: expected non-zero number");if(t<=qi)throw new Error("invert: expected positive modulus, got "+t);let r=Ba(e,t),n=t,o=qi,s=pi;for(;r!==qi;){let i=n/r,a=n%r,c=o-s*i;n=r,r=a,o=s,s=c}if(n!==pi)throw new Error("invert: does not exist");return Ba(o,t)}function hz(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function pge(e,t){let r=(e.ORDER+pi)/lge,n=e.pow(t,r);return hz(e,n,t),n}function Dje(e,t){let r=(e.ORDER-uge)/dge,n=e.mul(t,Cy),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Cy),o),a=e.mul(s,e.sub(i,e.ONE));return hz(e,a,t),a}function Lje(e){let t=Fm(e),r=hge(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+kje)/fge;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),h=a.eql(a.sqr(d),c),y=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(p,f,y);let w=a.eql(a.sqr(d),c),x=a.cmov(u,d,w);return hz(a,x,c),x}}function hge(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return pge;let s=o.pow(n,t),i=(t+pi)/Cy;return function(a,c){if(a.is0(c))return c;if(c1e(a,c)!==1)throw new Error("Cannot find square root");let u=r,d=a.mul(a.ONE,s),f=a.pow(c,t),p=a.pow(c,i);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let h=1,y=a.sqr(f);for(;!a.eql(y,a.ONE);)if(h++,y=a.sqr(y),h===u)throw new Error("Cannot find square root");let w=pi<(n[o]="function",n),t);return J7(e,r),e}function Fje(e,t,r){if(rqi;)r&pi&&(n=e.mul(n,o)),o=e.sqr(o),r>>=pi;return n}function mge(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function c1e(e,t){let r=(e.ORDER-pi)/Cy,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function gge(e,t){t!==void 0&&Tp(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Fm(e,t,r=!1,n={}){if(e<=qi)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(r=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=gge(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:U5(c),ZERO:qi,ONE:pi,allowedLengths:a,create:p=>Ba(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return qi<=p&&pp===qi,isValidNot0:p=>!f.is0(p)&&f.isValid(p),isOdd:p=>(p&pi)===pi,neg:p=>Ba(-p,e),eql:(p,h)=>p===h,sqr:p=>Ba(p*p,e),add:(p,h)=>Ba(p+h,e),sub:(p,h)=>Ba(p-h,e),mul:(p,h)=>Ba(p*h,e),pow:(p,h)=>Fje(f,p,h),div:(p,h)=>Ba(p*a1e(h,e),e),sqrN:p=>p*p,addN:(p,h)=>p+h,subN:(p,h)=>p-h,mulN:(p,h)=>p*h,inv:p=>a1e(p,e),sqrt:s||(p=>(d||(d=Mje(e)),d(f,p))),toBytes:p=>r?pz(p,u):fz(p,u),fromBytes:(p,h=!0)=>{if(a){if(!a.includes(p.length)||p.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let w=new Uint8Array(u);w.set(p,r?0:w.length-p.length),p=w}if(p.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+p.length);let y=r?L7(p):Y7(p);if(i&&(y=Ba(y,e)),!h&&!f.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:p=>mge(f,p),cmov:(p,h,y)=>y?h:p});return Object.freeze(f)}function yge(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function wge(e){let t=yge(e);return t+Math.ceil(t/2)}function zje(e,t,r=!1){let n=e.length,o=yge(t),s=wge(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?L7(e):Y7(e),a=Ba(i,t-pi)+pi;return r?pz(a,o):fz(a,o)}function M7(e,t){let r=t.negate();return e?r:t}function CF(e,t){let r=mge(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function bge(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function SF(e,t){bge(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=U5(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function l1e(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=Sy);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function Vje(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function jje(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function TF(e){return xge.get(e)||1}function u1e(e){if(e!==X6)throw new Error("invalid wNAF")}function qje(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>X6||n>X6;)r&Sy&&(s=s.add(o)),n&Sy&&(i=i.add(o)),o=o.double(),r>>=Sy,n>>=Sy;return{p1:s,p2:i}}function Wje(e,t,r,n){Vje(r,e),jje(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=age(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=U5(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;wX6))throw new Error(`CURVE.${a} must be positive bigint`)}let o=d1e(t.p,r.Fp,n),s=d1e(t.n,r.Fn,n),i=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let a of i)if(!o.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Zje(e){return J7(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Gje(e){let t=Zje(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||_y,u=a?255:448,d=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),h=a?N7**BigInt(254):N7**BigInt(447),y=a?BigInt(8)*N7**BigInt(251)-K6:BigInt(4)*N7**BigInt(445)-K6,w=h+y+K6,x=R=>Ba(R,r),v=T(f);function T(R){return pz(x(R),d)}function E(R){let I=Ss("u coordinate",R,d);return a&&(I[31]&=127),x(L7(I))}function S(R){return L7(o(Ss("scalar",R,d)))}function _(R,I){let B=M(E(I),S(R));if(B===E5)throw new Error("invalid private or public key received");return T(B)}function O(R){return _(R,v)}function D(R,I,B){let C=x(R*(I-B));return I=x(I-C),B=x(B+C),{x_2:I,x_3:B}}function M(R,I){jF("u",R,E5,r),jF("scalar",I,h,w);let B=I,C=R,A=K6,U=E5,H=R,k=K6,F=E5;for(let W=BigInt(u-1);W>=E5;W--){let ae=B>>W&K6;F^=ae,{x_2:A,x_3:H}=D(F,A,H),{x_2:U,x_3:k}=D(F,U,k),F=ae;let te=A+U,X=x(te*te),pe=A-U,me=x(pe*pe),Ne=X-me,ye=H+k,Re=H-k,Et=x(Re*te),kt=x(ye*pe),At=Et+kt,ur=Et-kt;H=x(At*At),k=x(C*x(ur*ur)),A=x(X*me),U=x(Ne*(X+x(p*Ne)))}({x_2:A,x_3:H}=D(F,A,H)),{x_2:U,x_3:k}=D(F,U,k);let j=s(U);return x(A*j)}let N={secretKey:d,publicKey:d,seed:d},L=(R=c(d))=>(wl(R,N.seed),R);function P(R){let I=L(R);return{secretKey:I,publicKey:O(I)}}return{keygen:P,getSharedSecret:(R,I)=>_(R,I),getPublicKey:R=>O(R),scalarMult:_,scalarMultBase:O,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:v.slice(),lengths:N}}function tqe(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=vge,i=e*e%s*e%s,a=pl(i,f1e,s)*i%s,c=pl(a,Yje,s)*e%s,u=pl(c,Qje,s)*c%s,d=pl(u,t,s)*u%s,f=pl(d,r,s)*d%s,p=pl(f,n,s)*f%s,h=pl(p,o,s)*p%s,y=pl(h,o,s)*p%s,w=pl(y,t,s)*u%s;return{pow_p_5_8:pl(w,f1e,s)*e%s,b2:i}}function rqe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function oqe(e,t,r){let[[n,o],[s,i]]=t,a=p1e(i*e,r),c=p1e(-o*e,r),u=e-a*n-c*s,d=-a*o-c*i,f=u=h||d=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function KF(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function _F(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return D7(r.lowS,"lowS"),D7(r.prehash,"prehash"),r.format!==void 0&&KF(r.format),r}function Z6(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=Ss("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function iqe(e,t={}){let r=Kje("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;J7(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Cge(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(R,I,B){let{x:C,y:A}=I.toAffine(),U=n.toBytes(C);if(D7(B,"isCompressed"),B){d();let H=!n.isOdd(A);return Dm(Age(H),U)}else return Dm(Uint8Array.of(4),U,n.toBytes(A))}function p(R){Ay(R,void 0,"Point");let{publicKey:I,publicKeyUncompressed:B}=u,C=R.length,A=R[0],U=R.subarray(1);if(C===I&&(A===2||A===3)){let H=n.fromBytes(U);if(!n.isValid(H))throw new Error("bad point: is not on curve, wrong x");let k=w(H),F;try{F=n.sqrt(k)}catch(W){let ae=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}d();let j=n.isOdd(F);return(A&1)===1!==j&&(F=n.neg(F)),{x:H,y:F}}else if(C===B&&A===4){let H=n.BYTES,k=n.fromBytes(U.subarray(0,H)),F=n.fromBytes(U.subarray(H,H*2));if(!x(k,F))throw new Error("bad point: is not on curve");return{x:k,y:F}}else throw new Error(`bad point: got length ${C}, expected compressed=${I} or uncompressed=${B}`)}let h=t.toBytes||f,y=t.fromBytes||p;function w(R){let I=n.sqr(R),B=n.mul(I,R);return n.add(n.add(B,n.mul(R,s.a)),s.b)}function x(R,I){let B=n.sqr(I),C=w(R);return n.eql(B,C)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,R7),sqe),T=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,T)))throw new Error("bad curve params: a or b");function E(R,I,B=!1){if(!n.isValid(I)||B&&n.is0(I))throw new Error(`bad point coordinate ${R}`);return I}function S(R){if(!(R instanceof N))throw new Error("ProjectivePoint expected")}function _(R){if(!c||!c.basises)throw new Error("no endo");return oqe(R,c.basises,o.ORDER)}let O=i1e((R,I)=>{let{X:B,Y:C,Z:A}=R;if(n.eql(A,n.ONE))return{x:B,y:C};let U=R.is0();I==null&&(I=U?n.ONE:n.inv(A));let H=n.mul(B,I),k=n.mul(C,I),F=n.mul(A,I);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:k}}),D=i1e(R=>{if(R.is0()){if(t.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:B}=R.toAffine();if(!n.isValid(I)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!x(I,B))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,I,B,C,A){return B=new N(n.mul(B.X,R),B.Y,B.Z),I=M7(C,I),B=M7(A,B),I.add(B)}class N{constructor(I,B,C){this.X=E("x",I),this.Y=E("y",B,!0),this.Z=E("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){let{x:B,y:C}=I||{};if(!I||!n.isValid(B)||!n.isValid(C))throw new Error("invalid affine point");if(I instanceof N)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(C)?N.ZERO:new N(B,C,n.ONE)}static fromBytes(I){let B=N.fromAffine(y(Ay(I,void 0,"point")));return B.assertValidity(),B}static fromHex(I){return N.fromBytes(Ss("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,B=!0){return P.createCache(this,I),B||this.multiply(R7),this}assertValidity(){D(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.eql(n.mul(B,k),n.mul(U,A)),j=n.eql(n.mul(C,k),n.mul(H,A));return F&&j}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:B}=s,C=n.mul(B,R7),{X:A,Y:U,Z:H}=this,k=n.ZERO,F=n.ZERO,j=n.ZERO,W=n.mul(A,A),ae=n.mul(U,U),te=n.mul(H,H),X=n.mul(A,U);return X=n.add(X,X),j=n.mul(A,H),j=n.add(j,j),k=n.mul(I,j),F=n.mul(C,te),F=n.add(k,F),k=n.sub(ae,F),F=n.add(ae,F),F=n.mul(k,F),k=n.mul(X,k),j=n.mul(C,j),te=n.mul(I,te),X=n.sub(W,te),X=n.mul(I,X),X=n.add(X,j),j=n.add(W,W),W=n.add(j,W),W=n.add(W,te),W=n.mul(W,X),F=n.add(F,W),te=n.mul(U,H),te=n.add(te,te),W=n.mul(te,X),k=n.sub(k,W),j=n.mul(te,ae),j=n.add(j,j),j=n.add(j,j),new N(k,F,j)}add(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.ZERO,j=n.ZERO,W=n.ZERO,ae=s.a,te=n.mul(s.b,R7),X=n.mul(B,U),pe=n.mul(C,H),me=n.mul(A,k),Ne=n.add(B,C),ye=n.add(U,H);Ne=n.mul(Ne,ye),ye=n.add(X,pe),Ne=n.sub(Ne,ye),ye=n.add(B,A);let Re=n.add(U,k);return ye=n.mul(ye,Re),Re=n.add(X,me),ye=n.sub(ye,Re),Re=n.add(C,A),F=n.add(H,k),Re=n.mul(Re,F),F=n.add(pe,me),Re=n.sub(Re,F),W=n.mul(ae,ye),F=n.mul(te,me),W=n.add(F,W),F=n.sub(pe,W),W=n.add(pe,W),j=n.mul(F,W),pe=n.add(X,X),pe=n.add(pe,X),me=n.mul(ae,me),ye=n.mul(te,ye),pe=n.add(pe,me),me=n.sub(X,me),me=n.mul(ae,me),ye=n.add(ye,me),X=n.mul(pe,ye),j=n.add(j,X),X=n.mul(Re,ye),F=n.mul(Ne,F),F=n.sub(F,X),X=n.mul(Ne,pe),W=n.mul(Re,W),W=n.add(W,X),new N(F,j,W)}subtract(I){return this.add(I.negate())}is0(){return this.equals(N.ZERO)}multiply(I){let{endo:B}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let C,A,U=H=>P.cached(this,H,k=>CF(N,k));if(B){let{k1neg:H,k1:k,k2neg:F,k2:j}=_(I),{p:W,f:ae}=U(k),{p:te,f:X}=U(j);A=ae.add(X),C=M(B.beta,W,te,H,F)}else{let{p:H,f:k}=U(I);C=H,A=k}return CF(N,[C,A])[0]}multiplyUnsafe(I){let{endo:B}=t,C=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===Sp||C.is0())return N.ZERO;if(I===Y6)return C;if(P.hasCache(this))return this.multiply(I);if(B){let{k1neg:A,k1:U,k2neg:H,k2:k}=_(I),{p1:F,p2:j}=qje(N,C,U,k);return M(B.beta,F,j,A,H)}else return P.unsafe(C,I)}multiplyAndAddUnsafe(I,B,C){let A=this.multiplyUnsafe(B).add(I.multiplyUnsafe(C));return A.is0()?void 0:A}toAffine(I){return O(this,I)}isTorsionFree(){let{isTorsionFree:I}=t;return i===Y6?!0:I?I(N,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=t;return i===Y6?this:I?I(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return D7(I,"isCompressed"),this.assertValidity(),h(N,this,I)}toHex(I=!0){return G6(this.toBytes(I))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return CF(N,I)}static msm(I,B){return Wje(N,o,I,B)}static fromPrivateKey(I){return N.BASE.multiply(Z6(o,I))}}N.BASE=new N(s.Gx,s.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=o;let L=o.BITS,P=new qF(N,t.endo?Math.ceil(L/2):L);return N.BASE.precompute(8),N}function Age(e){return Uint8Array.of(e?2:3)}function Cge(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function aqe(e,t={}){let{Fn:r}=e,n=t.randomBytes||_y,o=Object.assign(Cge(e.Fp,r),{seed:wge(r.ORDER)});function s(p){try{return!!Z6(r,p)}catch{return!1}}function i(p,h){let{publicKey:y,publicKeyUncompressed:w}=o;try{let x=p.length;return h===!0&&x!==y||h===!1&&x!==w?!1:!!e.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return zje(Ay(p,o.seed,"seed"),r.ORDER)}function c(p,h=!0){return e.BASE.multiply(Z6(r,p)).toBytes(h)}function u(p){let h=a(p);return{secretKey:h,publicKey:c(h)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof e)return!0;let{secretKey:h,publicKey:y,publicKeyUncompressed:w}=o;if(r.allowedLengths||h===y)return;let x=Ss("key",p).length;return x===y||x===w}function f(p,h,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(h)===!1)throw new Error("second arg must be public key");let w=Z6(r,p);return e.fromHex(h).multiply(w).toBytes(y)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:p=>Z6(r,p),precompute(p=8,h=e.BASE){return h.precompute(p,!1)}},lengths:o})}function cqe(e,t,r={}){j7(t),J7(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||_y,o=r.hmac||((B,...C)=>Z7(t,B,Dm(...C))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h}=aqe(e,r),y={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function x(B){let C=a>>Y6;return B>C}function v(B,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${B}: out of range 1..Point.Fn.ORDER`);return C}function T(B,C){KF(C);let A=h.signature,U=C==="compact"?A:C==="recovered"?A+1:void 0;return Ay(B,U,`${C} signature`)}class E{constructor(C,A,U){this.r=v("r",C),this.s=v("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(C,A=w){T(C,A);let U;if(A==="der"){let{r:j,s:W}=Cp.toSig(Ay(C));return new E(j,W)}A==="recovered"&&(U=C[0],A="compact",C=C.subarray(1));let H=i.BYTES,k=C.subarray(0,H),F=C.subarray(H,H*2);return new E(i.fromBytes(k),i.fromBytes(F),U)}static fromHex(C,A){return this.fromBytes(B7(C),A)}addRecoveryBit(C){return new E(this.r,this.s,C)}recoverPublicKey(C){let A=s.ORDER,{r:U,s:H,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*Ege1)throw new Error("recovery id is ambiguous for h>1 curve");let F=k===2||k===3?U+a:U;if(!s.isValid(F))throw new Error("recovery id 2 or 3 invalid");let j=s.toBytes(F),W=e.fromBytes(Dm(Age((k&1)===0),j)),ae=i.inv(F),te=_(Ss("msgHash",C)),X=i.create(-te*ae),pe=i.create(H*ae),me=e.BASE.multiplyUnsafe(X).add(W.multiplyUnsafe(pe));if(me.is0())throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return x(this.s)}toBytes(C=w){if(KF(C),C==="der")return B7(Cp.hexFromSig(this));let A=i.toBytes(this.r),U=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Dm(Uint8Array.of(this.recovery),A,U)}return Dm(A,U)}toHex(C){return G6(this.toBytes(C))}assertValidity(){}static fromCompact(C){return E.fromBytes(Ss("sig",C),"compact")}static fromDER(C){return E.fromBytes(Ss("sig",C),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return G6(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return G6(this.toBytes("compact"))}}let S=r.bits2int||function(B){if(B.length>8192)throw new Error("input is too large");let C=Y7(B),A=B.length*8-c;return A>0?C>>BigInt(A):C},_=r.bits2int_modN||function(B){return i.create(S(B))},O=U5(c);function D(B){return jF("num < 2^"+c,B,Sp,O),i.toBytes(B)}function M(B,C){return Ay(B,void 0,"message"),C?Ay(t(B),void 0,"prehashed message"):B}function N(B,C,A){if(["recovered","canonical"].some(pe=>pe in A))throw new Error("sign() legacy options not supported");let{lowS:U,prehash:H,extraEntropy:k}=_F(A,y);B=M(B,H);let F=_(B),j=Z6(i,C),W=[D(j),D(F)];if(k!=null&&k!==!1){let pe=k===!0?n(h.secretKey):k;W.push(Ss("extraEntropy",pe))}let ae=Dm(...W),te=F;function X(pe){let me=S(pe);if(!i.isValidNot0(me))return;let Ne=i.inv(me),ye=e.BASE.multiply(me).toAffine(),Re=i.create(ye.x);if(Re===Sp)return;let Et=i.create(Ne*i.create(te+Re*j));if(Et===Sp)return;let kt=(ye.x===Re?0:2)|Number(ye.y&Y6),At=Et;return U&&x(Et)&&(At=i.neg(Et),kt^=1),new E(Re,At,kt)}return{seed:ae,k2sig:X}}function L(B,C,A={}){B=Ss("message",B);let{seed:U,k2sig:H}=N(B,C,A);return Bje(t.outputLen,i.BYTES,o)(U,H)}function P(B){let C,A=typeof B=="string"||V7(B),U=!A&&B!==null&&typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)C=new E(B.r,B.s);else if(A){try{C=E.fromBytes(Ss("sig",B),"der")}catch(H){if(!(H instanceof Cp.Err))throw H}if(!C)try{C=E.fromBytes(Ss("sig",B),"compact")}catch{return!1}}return C||!1}function R(B,C,A,U={}){let{lowS:H,prehash:k,format:F}=_F(U,y);if(A=Ss("publicKey",A),C=M(Ss("message",C),k),"strict"in U)throw new Error("options.strict was renamed to lowS");let j=F===void 0?P(B):E.fromBytes(Ss("sig",B),F);if(j===!1)return!1;try{let W=e.fromBytes(A);if(H&&j.hasHighS())return!1;let{r:ae,s:te}=j,X=_(C),pe=i.inv(te),me=i.create(X*pe),Ne=i.create(ae*pe),ye=e.BASE.multiplyUnsafe(me).add(W.multiplyUnsafe(Ne));return ye.is0()?!1:i.create(ye.x)===ae}catch{return!1}}function I(B,C,A={}){let{prehash:U}=_F(A,y);return C=M(C,U),E.fromBytes(B,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h,Point:e,sign:L,verify:R,recoverPublicKey:I,Signature:E,hash:t})}function lqe(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Fm(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function uqe(e){let{CURVE:t,curveOpts:r}=lqe(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function dqe(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,gge(r.Fn.ORDER,r.Fn.BITS))})}function fqe(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:o}=uqe(e),s=iqe(t,r),i=cqe(s,n,o);return dqe(e,i)}function GF(e,t){let r=n=>fqe({...e,hash:n});return{...r(t),create:r}}function Nge(){let e=WF.utils.randomPrivateKey(),t=WF.getPublicKey(e);return{privateKey:Ut(e,Is),publicKey:Ut(t,Is)}}function Q7(){let e=_y(mz);return Ut(e,Is)}function Rge(e,t){let r=WF.getSharedSecret(Qt(e,Is),Qt(t,Is)),n=Rje(G7,r,void 0,void 0,mz);return Ut(n,Is)}function tx(e){let t=G7(Qt(e,Is));return Ut(t,Is)}function Wi(e){let t=G7(Qt(e,D5));return Ut(t,Is)}function Oge(e){return Qt(`${e}`,_ge)}function Hm(e){return Number(Ut(e,_ge))}function Bge(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kge(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}function Uge(e){let t=Oge(typeof e.type<"u"?e.type:Pge);if(Hm(t)===vl&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof e.senderPublicKey<"u"?Qt(e.senderPublicKey,Is):void 0,n=typeof e.iv<"u"?Qt(e.iv,Is):_y(S5),o=Qt(e.symKey,Is),s=sge(o,n).encrypt(Qt(e.message,D5)),i=Hge({type:t,sealed:s,iv:n,senderPublicKey:r});return e.encoding===Np?Bge(i):i}function Dge(e){let t=Qt(e.symKey,Is),{sealed:r,iv:n}=rx({encoded:e.encoded,encoding:e.encoding}),o=sge(t,n).decrypt(r);if(o===null)throw new Error("Failed to decrypt");return Ut(o,D5)}function Lge(e,t){let r=Oge(ex),n=_y(S5),o=Qt(e,D5),s=Hge({type:r,sealed:o,iv:n});return t===Np?Bge(s):s}function Mge(e,t){let{sealed:r}=rx({encoded:e,encoding:t});return Ut(r,D5)}function Hge(e){if(Hm(e.type)===ex)return Ut(Ms([e.type,e.sealed]),Ts);if(Hm(e.type)===vl){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ut(Ms([e.type,e.senderPublicKey,e.iv,e.sealed]),Ts)}return Ut(Ms([e.type,e.iv,e.sealed]),Ts)}function rx(e){let t=(e.encoding||Ts)===Np?kge(e.encoded):e.encoded,r=Qt(t,Ts),n=r.slice(wqe,h1e),o=h1e;if(Hm(n)===vl){let c=o+mz,u=c+S5,d=r.slice(o,c),f=r.slice(c,u),p=r.slice(u);return{type:n,sealed:p,iv:f,senderPublicKey:d}}if(Hm(n)===ex){let c=r.slice(o),u=_y(S5);return{type:n,sealed:c,iv:u}}let s=o+S5,i=r.slice(o,s),a=r.slice(s);return{type:n,sealed:a,iv:i}}function $ge(e,t){let r=rx({encoded:e,encoding:t?.encoding});return gz({type:Hm(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ut(r.senderPublicKey,Is):void 0,receiverPublicKey:t?.receiverPublicKey})}function gz(e){let t=e?.type||Pge;if(t===vl){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function yz(e){return e.type===vl&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function wz(e){return e.type===ex}function bqe(e){let t=Buffer.from(e.x,"base64"),r=Buffer.from(e.y,"base64");return Ms([new Uint8Array([4]),t,r])}function Fge(e,t){let[r,n,o]=e.split("."),s=Buffer.from(kge(o),"base64");if(s.length!==64)throw new Error("Invalid signature length");let i=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=G7(c),d=bqe(t);if(!yqe.verify(Ms([i,a]),u,d))throw new Error("Invalid signature");return Hl(e).payload}function L5(e){return e?.relay||{protocol:xqe}}function Py(e){let t=kC[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Tqe(e,t="-"){let r={},n="relay"+t;return Object.keys(e).forEach(o=>{if(o.startsWith(n)){let s=o.replace(n,""),i=e[o];r[s]=i}}),r}function bz(e){if(!e.includes("wc:")){let u=k1e(e);u!=null&&u.includes("wc:")&&(e=u)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;let t=e.indexOf(":"),r=e.indexOf("?")!==-1?e.indexOf("?"):void 0,n=e.substring(0,t),o=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",i=new URLSearchParams(s),a=Object.fromEntries(i.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:_qe(o[0]),version:parseInt(o[1],10),symKey:a.symKey,relay:Tqe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function _qe(e){return e.startsWith("//")?e.substring(2):e}function Pqe(e,t="-"){let r="relay",n={};return Object.keys(e).forEach(o=>{let s=o,i=r+t+s;e[s]&&(n[i]=e[s])}),n}function xz(e){let t=new URLSearchParams,r=PF(PF(Iqe(PF({},Pqe(e.relay)),{symKey:e.symKey}),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")});return Object.entries(r).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!==void 0&&t.append(n,String(o))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function M5(e,t,r){return`${e}?wc_ev=${r}&topic=${t}`}function nx(e){let t=[];return e.forEach(r=>{let[n,o]=r.split(":");t.push(`${n}:${o}`)}),t}function vz(e){let t=[];return Object.values(e).forEach(r=>{t.push(...nx(r.accounts))}),[...new Set(t)]}function zge(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.methods)}),[...new Set(t)]}function Vge(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.events)}),[...new Set(t)]}function Lqe(e,t){let r=[];return Object.values(e).forEach(n=>{nx(n.accounts).includes(t)&&r.push(...n.methods)}),r}function Mqe(e,t){let r=[];return Object.values(e).forEach(n=>{nx(n.accounts).includes(t)&&r.push(...n.events)}),r}function H5(e){return e.includes(":")}function Ny(e){return H5(e)?e.split(":")[0]:e}function b1e(e){var t,r,n;let o={};if(!xc(e))return o;for(let[s,i]of Object.entries(e)){let a=H5(s)?[s]:i.chains,c=i.methods||[],u=i.events||[],d=Ny(s);o[d]=Dqe(Uqe({},o[d]),{chains:ml(a,(t=o[d])==null?void 0:t.chains),methods:ml(c,(r=o[d])==null?void 0:r.methods),events:ml(u,(n=o[d])==null?void 0:n.events)})}return o}function Hqe(e){let t={};return e?.forEach(r=>{var n;let[o,s]=r.split(":");t[o]||(t[o]={accounts:[],chains:[],events:[],methods:[]}),t[o].accounts.push(r),(n=t[o].chains)==null||n.push(`${o}:${s}`)}),t}function Ez(e,t){t=t.map(n=>n.replace("did:pkh:",""));let r=Hqe(t);for(let[n,o]of Object.entries(r))o.methods?o.methods=ml(o.methods,e):o.methods=e,o.events=["chainChanged","accountsChanged"];return r}function jge(e,t){var r,n,o,s,i,a;let c=b1e(e),u=b1e(t),d={},f=Object.keys(c).concat(Object.keys(u));for(let p of f)d[p]={chains:ml((r=c[p])==null?void 0:r.chains,(n=u[p])==null?void 0:n.chains),methods:ml((o=c[p])==null?void 0:o.methods,(s=u[p])==null?void 0:s.methods),events:ml((i=c[p])==null?void 0:i.events,(a=u[p])==null?void 0:a.events)};return d}function Ie(e,t){let{message:r,code:n}=Fqe[e];return{message:t?`${r} ${t}`:r,code:n}}function Rr(e,t){let{message:r,code:n}=$qe[e];return{message:t?`${r} ${t}`:r,code:n}}function El(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function xc(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Ln(e){return typeof e>"u"}function An(e,t){return t&&Ln(e)?!0:typeof e=="string"&&!!e.trim().length}function Az(e,t){return t&&Ln(e)?!0:typeof e=="number"&&!isNaN(e)}function qge(e,t){let{requiredNamespaces:r}=t,n=Object.keys(e.namespaces),o=Object.keys(r),s=!0;return Ey(o,n)?(n.forEach(i=>{let{accounts:a,methods:c,events:u}=e.namespaces[i],d=nx(a),f=r[i];(!Ey(C1e(i,f),d)||!Ey(f.methods,c)||!Ey(f.events,u))&&(s=!1)}),s):!1}function H7(e){return An(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function zqe(e){if(An(e,!1)&&e.includes(":")){let t=e.split(":");if(t.length===3){let r=t[0]+":"+t[1];return!!t[2]&&H7(r)}}return!1}function Wge(e){function t(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(An(e,!1)){if(t(e))return!0;let r=k1e(e);return t(r)}}catch{}return!1}function Kge(e){var t;return(t=e?.proposer)==null?void 0:t.publicKey}function Zge(e){return e?.topic}function Gge(e,t){let r=null;return An(e?.publicKey,!1)||(r=Ie("MISSING_OR_INVALID",`${t} controller public key should be a string`)),r}function x1e(e){let t=!0;return El(e)?e.length&&(t=e.every(r=>An(r,!1))):t=!1,t}function Vqe(e,t,r){let n=null;return El(t)&&t.length?t.forEach(o=>{n||H7(o)||(n=Rr("UNSUPPORTED_CHAINS",`${r}, chain ${o} should be a string and conform to "namespace:chainId" format`))}):H7(e)||(n=Rr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function jqe(e,t,r){let n=null;return Object.entries(e).forEach(([o,s])=>{if(n)return;let i=Vqe(o,C1e(o,s),`${t} ${r}`);i&&(n=i)}),n}function qqe(e,t){let r=null;return El(e)?e.forEach(n=>{r||zqe(n)||(r=Rr("UNSUPPORTED_ACCOUNTS",`${t}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=Rr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function Wqe(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=qqe(n?.accounts,`${t} namespace`);o&&(r=o)}),r}function Kqe(e,t){let r=null;return x1e(e?.methods)?x1e(e?.events)||(r=Rr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Rr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}function Yge(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=Kqe(n,`${t}, namespace`);o&&(r=o)}),r}function Jge(e,t,r){let n=null;if(e&&xc(e)){let o=Yge(e,t);o&&(n=o);let s=jqe(e,t,r);s&&(n=s)}else n=Ie("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return n}function X7(e,t){let r=null;if(e&&xc(e)){let n=Yge(e,t);n&&(r=n);let o=Wqe(e,t);o&&(r=o)}else r=Ie("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function Cz(e){return An(e.protocol,!0)}function Qge(e,t){let r=!1;return t&&!e?r=!0:e&&El(e)&&e.length&&e.forEach(n=>{r=Cz(n)}),r}function Xge(e){return typeof e=="number"}function _s(e){return typeof e<"u"&&typeof e!==null}function eye(e){return!(!e||typeof e!="object"||!e.code||!Az(e.code,!1)||!e.message||!An(e.message,!1))}function tye(e){return!(Ln(e)||!An(e.method,!1))}function rye(e){return!(Ln(e)||Ln(e.result)&&Ln(e.error)||!Az(e.id,!1)||!An(e.jsonrpc,!1))}function nye(e){return!(Ln(e)||!An(e.name,!1))}function Sz(e,t){return!(!H7(t)||!vz(e).includes(t))}function oye(e,t,r){return An(r,!1)?Lqe(e,t).includes(r):!1}function sye(e,t,r){return An(r,!1)?Mqe(e,t).includes(r):!1}function Iz(e,t,r){let n=null,o=Zqe(e),s=Gqe(t),i=Object.keys(o),a=Object.keys(s),c=v1e(Object.keys(e)),u=v1e(Object.keys(t)),d=c.filter(f=>!u.includes(f));return d.length&&(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. +${a}`,o=!0}}o||(Error.captureStackTrace?Error.captureStackTrace(this,e):this.stack||(this.stack=`${this.name}: ${this.message}`))}}});var Pa,mHe,Wn,y_=b(()=>{l();Lr();Hn();gs();Pa=rt({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),mHe={state:Pa,subscribeNetworkImages(e){return Dt(Pa.networkImages,()=>e(Pa.networkImages))},subscribeKey(e,t){return Tt(Pa,e,t)},subscribe(e){return Dt(Pa,()=>e(Pa))},setWalletImage(e,t){Pa.walletImages[e]=t},setNetworkImage(e,t){Pa.networkImages[e]=t},setChainImage(e,t){Pa.chainImages[e]=t},setConnectorImage(e,t){Pa.connectorImages={...Pa.connectorImages,[e]:t}},setTokenImage(e,t){Pa.tokenImages[e]=t},setCurrencyImage(e,t){Pa.currencyImages[e]=t}},Wn=vr(mHe)});var tpe,B6,St,yH=b(()=>{l();Lr();ut();Cu();y_();Un();tpe={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:"",ton:"20f673c0-095e-49b2-07cf-eb5049dcf600"},B6=rt({networkImagePromises:{},tokenImagePromises:{}}),St={async fetchWalletImage(e){if(e)return await ge._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;let t=this.getNetworkImageById(e);return t||(B6.networkImagePromises[e]||(B6.networkImagePromises[e]=ge._fetchNetworkImage(e)),await B6.networkImagePromises[e],this.getNetworkImageById(e))},async fetchTokenImage(e){if(e)return B6.tokenImagePromises[e]||(B6.tokenImagePromises[e]=ge._fetchTokenImage(e)),await B6.tokenImagePromises[e],this.getTokenImage(e)},getWalletImageById(e){if(e)return Wn.state.walletImages[e]},getWalletImage(e){if(e?.image_url)return e?.image_url;if(e?.image_id)return Wn.state.walletImages[e.image_id]},getNetworkImage(e){if(e?.assets?.imageUrl)return e?.assets?.imageUrl;if(e?.assets?.imageId)return Wn.state.networkImages[e.assets.imageId]},getNetworkImageById(e){if(e)return Wn.state.networkImages[e]},getConnectorImage(e){if(e?.imageUrl)return e.imageUrl;if(e?.info?.icon)return e.info.icon;if(e?.imageId)return Wn.state.connectorImages[e.imageId]},getChainImage(e){return Wn.state.networkImages[tpe[e]]},getTokenImage(e){if(e)return Wn.state.tokenImages[e]},getWalletImageUrl(e){if(!e)return"";let{projectId:t,sdkType:r,sdkVersion:n}=Y.state,o=new URL(`${Z.W3M_API_URL}/getWalletImage/${e}`);return o.searchParams.set("projectId",t),o.searchParams.set("st",r),o.searchParams.set("sv",n),o.toString()},getAssetImageUrl(e){if(!e)return"";let{projectId:t,sdkType:r,sdkVersion:n}=Y.state,o=new URL(`${Z.W3M_API_URL}/public/getAssetImage/${e}`);return o.searchParams.set("projectId",t),o.searchParams.set("st",r),o.searchParams.set("sv",n),o.toString()},getChainNamespaceImageUrl(e){return this.getAssetImageUrl(tpe[e])},async getImageByToken(e,t){if(e==="native"){let n=Z.NATIVE_IMAGE_IDS_BY_NAMESPACE[t]??null;return n?St.fetchNetworkImage(n):void 0}let[,r]=Object.entries(Z.TOKEN_SYMBOLS_BY_ADDRESS).find(([n])=>n.toLowerCase()===e.toLowerCase())??[];if(r)return St.fetchTokenImage(r)}}});var Na,rpe,wH=b(()=>{l();ut();$r();Na={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},rpe={handleMobileDeeplinkRedirect(e,t){let r=window.location.href,n=encodeURIComponent(r);if(e===Na.PHANTOM.id&&!("phantom"in window)){let o=r.startsWith("https")?"https":"http",s=r.split("/")[2],i=encodeURIComponent(`${o}://${s}`);window.location.href=`${Na.PHANTOM.url}/ul/browse/${n}?ref=${i}`}if(e===Na.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Na.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),t===Z.CHAIN.SOLANA&&e===Na.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Na.COINBASE.url}/dapp?cb_url=${n}`),t===Z.CHAIN.BITCOIN&&e===Na.BINANCE.id&&!("binancew3w"in window)){let o=$.state.activeCaipNetwork,s=window.btoa("/pages/browser/index"),i=window.btoa(`url=${n}&defaultChainId=${o?.id??1}`),a=new URL(Na.BINANCE.deeplink);a.searchParams.set("appId",Na.BINANCE.appId),a.searchParams.set("startPagePath",s),a.searchParams.set("startPageQuery",i);let c=new URL(Na.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}}});var gHe,yHe,wHe,bHe,npe,En,Ae,mc=b(()=>{l();Lr();$n();O6();$r();Un();gHe=se.getAnalyticsUrl(),yHe=new Li({baseUrl:gHe,clientId:null}),wHe=["MODAL_CREATED"],bHe=45,npe=1e3*10,En=rt({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),Ae={state:En,subscribe(e){return Dt(En,()=>e(En))},getSdkProperties(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t,sv:r||"html-wagmi-4.2.2"}},shouldFlushEvents(){let e=JSON.stringify(En.pendingEvents).length/1024>bHe,t=En.lastFlush+npe"u")return;let r=$.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t,properties:{..."properties"in e.data?e.data.properties:{},caipNetworkId:r}}}),En.reportedErrors.FORBIDDEN=!1,Ae.shouldFlushEvents()&&Ae._submitPendingEvents()}catch(t){console.warn("_setPendingEvent",t)}},sendEvent(e){En.timestamp=Date.now(),En.data=e;let t=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];(Y.state.features?.analytics||t.includes(e.event))&&Ae._setPendingEvent(En),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(e){En.walletImpressions.push(e)},_transformPendingEventsForBatch(e){try{return e.filter(t=>t.props.event!=="WALLET_IMPRESSION_V2")}catch{return e}},_submitPendingEvents(){if(En.lastFlush=Date.now(),!(En.pendingEvents.length===0&&En.walletImpressions.length===0))try{let e=Ae._transformPendingEventsForBatch(En.pendingEvents);En.walletImpressions.length&&e.push({eventId:se.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...En.walletImpressions]}}),yHe.sendBeacon({path:"/batch",params:Ae.getSdkProperties(),body:e}),En.reportedErrors.FORBIDDEN=!1,En.pendingEvents=[],En.walletImpressions=[]}catch{En.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){En.subscribedToVisibilityChange||typeof document>"u"||(En.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",()=>{document.visibilityState==="hidden"&&Ae._submitPendingEvents()}),document?.addEventListener?.("freeze",()=>{Ae._submitPendingEvents()}),window?.addEventListener?.("pagehide",()=>{Ae._submitPendingEvents()}),setInterval(()=>{Ae._submitPendingEvents()},npe))}}});var xHe,ii,vHe,ope,EHe,mt,ge,Cu=b(()=>{l();Lr();Hn();ut();yH();$n();O6();wH();ma();y_();$r();To();mc();Un();xHe=se.getApiUrl(),ii=new Li({baseUrl:xHe,clientId:null}),vHe=40,ope=4,EHe=20,mt=rt({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[],plan:{tier:"none",hasExceededUsageLimit:!1,limits:{isAboveRpcLimit:!1,isAboveMauLimit:!1}}}),ge={state:mt,subscribeKey(e,t){return Tt(mt,e,t)},_getSdkProperties(){let{projectId:e,sdkType:t,sdkVersion:r}=Y.state;return{projectId:e,st:t||"appkit",sv:r||"html-wagmi-4.2.2"}},_filterOutExtensions(e){return Y.state.isUniversalProvider?e.filter(t=>!!(t.mobile_link||t.desktop_link||t.webapp_link)):e},async _fetchWalletImage(e){let t=`${ii.baseUrl}/getWalletImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setWalletImage(e,URL.createObjectURL(r))},async _fetchNetworkImage(e){let t=`${ii.baseUrl}/public/getAssetImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setNetworkImage(e,URL.createObjectURL(r))},async _fetchConnectorImage(e){let t=`${ii.baseUrl}/public/getAssetImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setConnectorImage(e,URL.createObjectURL(r))},async _fetchCurrencyImage(e){let t=`${ii.baseUrl}/public/getCurrencyImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setCurrencyImage(e,URL.createObjectURL(r))},async _fetchTokenImage(e){let t=`${ii.baseUrl}/public/getTokenImage/${e}`,r=await ii.getBlob({path:t,params:ge._getSdkProperties()});Wn.setTokenImage(e,URL.createObjectURL(r))},_filterWalletsByPlatform(e){let t=e.length,r=se.isMobile()?e?.filter(o=>o.mobile_link||o.webapp_link?!0:Object.values(Na).map(i=>i.id).includes(o.id)):e,n=t-r.length;return{filteredWallets:r,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await ii.get({path:"/appkit/v1/config",params:ge._getSdkProperties()})).features},async fetchUsage(){try{let e=await ii.get({path:"/appkit/v1/project-limits",params:ge._getSdkProperties()}),{tier:t,isAboveMauLimit:r,isAboveRpcLimit:n}=e.planLimits,o=t==="starter",s=r||n;ge.state.plan={tier:t,hasExceededUsageLimit:o&&s,limits:{isAboveRpcLimit:n,isAboveMauLimit:r}}}catch(e){console.warn("Failed to fetch usage",e)}},async fetchAllowedOrigins(){try{let{allowedOrigins:e}=await ii.get({path:"/projects/v1/origins",params:ge._getSdkProperties()});return e}catch(e){if(e instanceof Error&&e.cause instanceof Response){let t=e.cause.status;if(t===Z.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:e});if(t>=Z.HTTP_STATUS_CODES.SERVER_ERROR&&t<600)throw new Error("SERVER_ERROR",{cause:e});return[]}return[]}},async fetchNetworkImages(){let t=$.getAllRequestedCaipNetworks()?.map(({assets:r})=>r?.imageId).filter(Boolean).filter(r=>!St.getNetworkImageById(r));t&&await Promise.allSettled(t.map(r=>ge._fetchNetworkImage(r)))},async fetchConnectorImages(){let{connectors:e}=re.state,t=e.map(({imageId:r})=>r).filter(Boolean);await Promise.allSettled(t.map(r=>ge._fetchConnectorImage(r)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(t=>ge._fetchCurrencyImage(t)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(t=>ge._fetchTokenImage(t)))},async fetchWallets(e){let t=e.exclude??[];ge._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(Na).map(i=>i.id));let n=await ii.get({path:"/getWallets",params:{...ge._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}}),{filteredWallets:o,mobileFilteredOutWalletsLength:s}=ge._filterWalletsByPlatform(n?.data);return{data:o||[],count:n?.count,mobileFilteredOutWalletsLength:s}},async prefetchWalletRanks(){let e=re.state.connectors;if(!e?.length)return;let t={page:1,entries:20,badge:"certified"};if(t.names=e.map(o=>o.name).join(","),$.state.activeChain===Z.CHAIN.EVM){let o=[...e.flatMap(s=>s.connectors?.map(i=>i.info?.rdns)||[]),...e.map(s=>s.info?.rdns)].filter(s=>typeof s=="string"&&s.length>0);o.length&&(t.rdns=o.join(","))}let{data:r}=await ge.fetchWallets(t);mt.explorerWallets=r,re.extendConnectorsWithExplorerWallets(r);let n=$.getRequestedCaipNetworkIds().join(",");mt.explorerFilteredWallets=r.filter(o=>o.chains?.some(s=>n.includes(s)))},async fetchFeaturedWallets(){let{featuredWalletIds:e}=Y.state;if(e?.length){let t={...ge._getSdkProperties(),page:1,entries:e?.length??ope,include:e},{data:r}=await ge.fetchWallets(t),n=[...r].sort((s,i)=>e.indexOf(s.id)-e.indexOf(i.id)),o=n.map(s=>s.image_id).filter(Boolean);await Promise.allSettled(o.map(s=>ge._fetchWalletImage(s))),mt.featured=n,mt.allFeatured=n}},async fetchRecommendedWallets(){try{mt.isFetchingRecommendedWallets=!0;let{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:r}=Y.state,n=[...t??[],...r??[]].filter(Boolean),o=$.getRequestedCaipNetworkIds().join(","),s={page:1,entries:ope,include:e,exclude:n,chains:o},{data:i,count:a}=await ge.fetchWallets(s),c=de.getRecentWallets(),u=i.map(f=>f.image_id).filter(Boolean),d=c.map(f=>f.image_id).filter(Boolean);await Promise.allSettled([...u,...d].map(f=>ge._fetchWalletImage(f))),mt.recommended=i,mt.allRecommended=i,mt.count=a??0}catch{}finally{mt.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){let{includeWalletIds:t,excludeWalletIds:r,featuredWalletIds:n}=Y.state,o=$.getRequestedCaipNetworkIds().join(","),s=[...mt.recommended.map(({id:f})=>f),...r??[],...n??[]].filter(Boolean),i={page:e,entries:vHe,include:t,exclude:s,chains:o},{data:a,count:c,mobileFilteredOutWalletsLength:u}=await ge.fetchWallets(i);mt.mobileFilteredOutWalletsLength=u+(mt.mobileFilteredOutWalletsLength??0);let d=a.slice(0,EHe).map(f=>f.image_id).filter(Boolean);await Promise.allSettled(d.map(f=>ge._fetchWalletImage(f))),mt.wallets=se.uniqueBy([...mt.wallets,...ge._filterOutExtensions(a)],"id").filter(f=>f.chains?.some(p=>o.includes(p))),mt.count=c>mt.count?c:mt.count,mt.page=e},async initializeExcludedWallets({ids:e}){let t={page:1,entries:e.length,include:e},{data:r}=await ge.fetchWallets(t);r&&r.forEach(n=>{mt.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:e,badge:t}){let{includeWalletIds:r,excludeWalletIds:n}=Y.state,o=$.getRequestedCaipNetworkIds().join(",");mt.search=[];let s={page:1,entries:100,search:e?.trim(),badge_type:t,include:r,exclude:n,chains:o},{data:i}=await ge.fetchWallets(s);Ae.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});let a=i.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>ge._fetchWalletImage(c)),se.wait(300)]),mt.search=ge._filterOutExtensions(i)},initPromise(e,t){let r=mt.promises[e];return r||(mt.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:r=!0,fetchNetworkImages:n=!0,fetchWalletRanks:o=!0}={}){let s=[e&&ge.initPromise("connectorImages",ge.fetchConnectorImages),t&&ge.initPromise("featuredWallets",ge.fetchFeaturedWallets),r&&ge.initPromise("recommendedWallets",ge.fetchRecommendedWallets),n&&ge.initPromise("networkImages",ge.fetchNetworkImages),o&&ge.initPromise("walletRanks",ge.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(s)},prefetchAnalyticsConfig(){Y.state.features?.analytics&&ge.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{let{isAnalyticsEnabled:e}=await ii.get({path:"/getAnalyticsConfig",params:ge._getSdkProperties()});Y.setFeatures({analytics:e})}catch{Y.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length){mt.featured=mt.allFeatured,mt.recommended=mt.allRecommended;return}let t=$.getRequestedCaipNetworkIds().join(",");mt.featured=mt.allFeatured.filter(r=>r.chains?.some(n=>t.includes(n))),mt.recommended=mt.allRecommended.filter(r=>r.chains?.some(n=>t.includes(n))),mt.filteredWallets=mt.wallets.filter(r=>r.chains?.some(n=>t.includes(n)))},clearFilterByNamespaces(){mt.filteredWallets=[]},setFilterByNamespace(e){if(!e){mt.featured=mt.allFeatured,mt.recommended=mt.allRecommended;return}let t=$.getRequestedCaipNetworkIds().join(",");mt.featured=mt.allFeatured.filter(r=>r.chains?.some(n=>t.includes(n))),mt.recommended=mt.allRecommended.filter(r=>r.chains?.some(n=>t.includes(n))),mt.filteredWallets=mt.wallets.filter(r=>r.chains?.some(n=>t.includes(n)))}}});var ys,bH=b(()=>{l();ut();Cu();ai();To();Un();w_();ha();$n();ma();ys={filterOutDuplicatesByRDNS(e){let t=Y.state.enableEIP6963?re.state.connectors:[],r=de.getRecentWallets(),n=t.map(a=>a.info?.rdns).filter(Boolean),o=r.map(a=>a.rdns).filter(Boolean),s=n.concat(o);if(s.includes("io.metamask.mobile")&&se.isMobile()){let a=s.indexOf("io.metamask.mobile");s[a]="io.metamask"}return e.filter(a=>!(a?.rdns&&s.includes(String(a.rdns))||!a?.rdns&&t.some(u=>u.name===a.name)))},filterOutDuplicatesByIds(e){let t=re.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"||a.type==="MULTI_CHAIN"),r=de.getRecentWallets(),n=t.map(a=>a.explorerId||a.explorerWallet?.id||a.id),o=r.map(a=>a.id),s=n.concat(o);return e.filter(a=>!s.includes(a?.id))},filterOutDuplicateWallets(e){let t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){let{connectors:t}=re.state,{featuredWalletIds:r}=Y.state,n=t.filter(i=>i.type==="ANNOUNCED").reduce((i,a)=>(a.info?.rdns&&(i[a.info.rdns]=!0),i),{});return e.map(i=>({...i,installed:!!i.rdns&&!!n[i.rdns??""]})).sort((i,a)=>{let c=Number(a.installed)-Number(i.installed);if(c!==0)return c;if(r?.length){let u=r.indexOf(i.id),d=r.indexOf(a.id);if(u!==-1&&d!==-1)return u-d;if(u!==-1)return-1;if(d!==-1)return 1}return 0})},getConnectOrderMethod(e,t){let r=e?.connectMethodsOrder||Y.state.features?.connectMethodsOrder,n=t||re.state.connectors;if(r)return r;let{injected:o,announced:s}=Dn.getConnectorsByType(n,ge.state.recommended,ge.state.featured),i=o.filter(Dn.showConnector),a=s.filter(Dn.showConnector);return i.length||a.length?["wallet","email","social"]:Ye.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){let t=!!e.rdns&&ge.state.excludedWallets.some(n=>n.rdns===e.rdns),r=!!e.name&&ge.state.excludedWallets.some(n=>l4.isLowerCaseMatch(n.name,e.name));return t||r},markWalletsWithDisplayIndex(e){return e.map((t,r)=>({...t,display_index:r}))},filterWalletsByWcSupport(e){return ee.state.wcBasic?e.filter(t=>t.supports_wc):se.isMobile()?e.filter(t=>t.supports_wc||Ye.MANDATORY_WALLET_IDS_ON_MOBILE.includes(t.id)):e},getWalletConnectWallets(e){let t=[...ge.state.featured,...ge.state.recommended];ge.state.filteredWallets?.length>0?t.push(...ge.state.filteredWallets):t.push(...e);let r=se.uniqueBy(t,"id"),n=ys.markWalletsAsInstalled(r),o=ys.filterWalletsByWcSupport(n);return ys.markWalletsWithDisplayIndex(o)}}});var Dn,w_=b(()=>{l();ut();Cu();$r();ai();To();Un();$n();gH();ma();bH();Dn={getConnectorsByType(e,t,r){let{customWallets:n}=Y.state,o=de.getRecentWallets(),s=ys.filterOutDuplicateWallets(t),i=ys.filterOutDuplicateWallets(r),a=e.filter(f=>f.type==="MULTI_CHAIN"),c=e.filter(f=>f.type==="ANNOUNCED"),u=e.filter(f=>f.type==="INJECTED"),d=e.filter(f=>f.type==="EXTERNAL");return{custom:n,recent:o,external:d,multiChain:a,announced:c,injected:u,recommended:s,featured:i}},showConnector(e){let t=e.info?.rdns,r=!!t&&ge.state.excludedWallets.some(o=>!!o.rdns&&o.rdns===t),n=!!e.name&&ge.state.excludedWallets.some(o=>l4.isLowerCaseMatch(o.name,e.name));return!(e.type==="INJECTED"&&(e.name==="Browser Wallet"&&(!se.isMobile()||se.isMobile()&&!t&&!ee.checkInstalled())||r||n)||(e.type==="ANNOUNCED"||e.type==="EXTERNAL")&&(r||n))},getIsConnectedWithWC(){return Array.from($.state.chains.values()).some(r=>re.getConnectorId(r.namespace)===Z.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:e,featured:t,custom:r,recent:n,announced:o,injected:s,multiChain:i,external:a,overriddenConnectors:c=Y.state.features?.connectorTypeOrder??[]}){let d=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...s,...o,...i].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:r&&r.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter(y=>y.isEnabled),f=new Set(d.map(y=>y.type)),p=c.filter(y=>f.has(y)).map(y=>({type:y,isEnabled:!0})),h=d.filter(({type:y})=>!p.some(({type:x})=>x===y));return Array.from(new Set([...p,...h].map(({type:y})=>y)))},sortConnectorsByExplorerWallet(e){return[...e].sort((t,r)=>t.explorerWallet&&r.explorerWallet?(t.explorerWallet.order??0)-(r.explorerWallet.order??0):t.explorerWallet?-1:r.explorerWallet?1:0)},getPriority(e){return e.id===Z.CONNECTOR_ID.BASE_ACCOUNT?0:e.id===Z.CONNECTOR_ID.COINBASE||e.id===Z.CONNECTOR_ID.COINBASE_SDK?1:2},sortConnectorsByPriority(e){return[...e].sort((t,r)=>Dn.getPriority(t)-Dn.getPriority(r))},getAuthName({email:e,socialUsername:t,socialProvider:r}){return t?r&&r==="discord"&&t.endsWith("0")?t.slice(0,-1):t:e.length>30?`${e.slice(0,-3)}...`:e},async fetchProviderData(e){try{if(e.name==="Browser Wallet"&&!se.isMobile())return{accounts:[],chainId:void 0};if(e.id===Z.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};let[t,r]=await Promise.all([e.provider?.request({method:"eth_accounts"}),e.provider?.request({method:"eth_chainId"}).then(n=>Number(n))]);return{accounts:t,chainId:r}}catch(t){return console.warn(`Failed to fetch provider data for ${e.name}`,t),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(e){let t=de.getRecentWallets(),r=re.state.connectors.map(i=>i.info?.rdns).filter(Boolean),n=t.map(i=>i.rdns).filter(Boolean),o=r.concat(n);if(o.includes("io.metamask.mobile")&&se.isMobile()){let i=o.indexOf("io.metamask.mobile");o[i]="io.metamask"}return e.filter(i=>!o.includes(String(i?.rdns)))},hasWalletConnector(e){return re.state.connectors.some(t=>t.id===e.id||t.name===e.name)},isWalletCompatibleWithCurrentChain(e){let t=$.state.activeChain;return t&&e.chains?e.chains.some(r=>{let n=r.split(":")[0];return t===n}):!0},getFilteredRecentWallets(){return de.getRecentWallets().filter(r=>!ys.isExcluded(r)).filter(r=>!this.hasWalletConnector(r)).filter(r=>this.isWalletCompatibleWithCurrentChain(r))},getCappedRecommendedWallets(e){let{connectors:t}=re.state,{customWallets:r,featuredWalletIds:n}=Y.state,o=t.find(T=>T.id==="walletConnect"),s=t.filter(T=>T.type==="INJECTED"||T.type==="ANNOUNCED"||T.type==="MULTI_CHAIN");if(!o&&!s.length&&!r?.length)return[];let i=J3.isEmailEnabled(),a=J3.isSocialsEnabled(),c=s.filter(T=>T.name!=="Browser Wallet"&&T.name!=="WalletConnect"),u=n?.length||0,d=r?.length||0,f=c.length||0,p=i?1:0,h=a?1:0,y=u+d+f+p+h,x=Math.max(0,4-y);return x<=0?[]:ys.filterOutDuplicateWallets(e).slice(0,x)},processConnectorsByType(e,t=!0){let r=Dn.sortConnectorsByExplorerWallet([...e]);return t?r.filter(Dn.showConnector):r},connectorList(){let e=Dn.getConnectorsByType(re.state.connectors,ge.state.recommended,ge.state.featured),t=this.processConnectorsByType(e.announced.filter(h=>h.id!=="walletConnect")),r=this.processConnectorsByType(e.injected),n=this.processConnectorsByType(e.multiChain.filter(h=>h.name!=="WalletConnect"),!1),o=e.custom,s=e.recent,i=this.processConnectorsByType(e.external.filter(h=>h.id!==Z.CONNECTOR_ID.COINBASE_SDK&&h.id!==Z.CONNECTOR_ID.BASE_ACCOUNT)),a=e.recommended,c=e.featured,u=Dn.getConnectorTypeOrder({custom:o,recent:s,announced:t,injected:r,multiChain:n,recommended:a,featured:c,external:i}),d=re.state.connectors.find(h=>h.id==="walletConnect"),f=se.isMobile(),p=[];for(let h of u)switch(h){case"walletConnect":{!f&&d&&p.push({kind:"connector",subtype:"walletConnect",connector:d});break}case"recent":{Dn.getFilteredRecentWallets().forEach(w=>p.push({kind:"wallet",subtype:"recent",wallet:w}));break}case"injected":{n.forEach(y=>p.push({kind:"connector",subtype:"multiChain",connector:y})),t.forEach(y=>p.push({kind:"connector",subtype:"announced",connector:y})),r.forEach(y=>p.push({kind:"connector",subtype:"injected",connector:y}));break}case"featured":{c.forEach(y=>p.push({kind:"wallet",subtype:"featured",wallet:y}));break}case"custom":{Dn.getFilteredCustomWallets(o??[]).forEach(w=>p.push({kind:"wallet",subtype:"custom",wallet:w}));break}case"external":{i.forEach(y=>p.push({kind:"connector",subtype:"external",connector:y}));break}case"recommended":{Dn.getCappedRecommendedWallets(a).forEach(w=>p.push({kind:"wallet",subtype:"recommended",wallet:w}));break}default:console.warn(`Unknown connector type: ${h}`)}return p},hasInjectedConnectors(){return re.state.connectors.filter(e=>(e.type==="INJECTED"||e.type==="ANNOUNCED"||e.type==="MULTI_CHAIN")&&e.name!=="Browser Wallet"&&e.name!=="WalletConnect").length}}});var AHe,pr,CHe,J,gc=b(()=>{l();Lr();Hn();gs();Cu();$r();To();up();Un();AHe=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],pr=rt({view:"Connect",history:["Connect"],transactionStack:[]}),CHe={state:pr,subscribeKey(e,t){return Tt(pr,e,t)},pushTransactionStack(e){pr.transactionStack.push(e)},popTransactionStack(e){let t=pr.transactionStack.pop();if(!t)return;let{onSuccess:r,onError:n,onCancel:o}=t;switch(e){case"success":r?.();break;case"error":n?.(),J.goBack();break;case"cancel":o?.(),J.goBack();break;default:}},push(e,t){let r=e,n=t;ge.state.plan.hasExceededUsageLimit&&AHe.includes(e)&&(r="UsageExceeded",n=void 0),r!==pr.view&&(pr.view=r,pr.history.push(r),pr.data=n)},reset(e,t){pr.view=e,pr.history=[e],pr.data=t},replace(e,t){pr.history.at(-1)===e||(pr.view=e,pr.history[pr.history.length-1]=e,pr.data=t)},goBack(){let e=$.state.activeCaipAddress,t=J.state.view==="ConnectingFarcaster",r=!e&&t;if(pr.history.length>1){pr.history.pop();let[n]=pr.history.slice(-1);n&&(e&&n==="Connect"?pr.view="Account":pr.view=n)}else De.close();pr.data?.wallet&&(pr.data.wallet=void 0),pr.data?.redirectView&&(pr.data.redirectView=void 0),setTimeout(()=>{if(r){$.setAccountProp("farcasterUrl",void 0,$.state.activeChain);let n=re.getAuthConnector();n?.provider?.reload();let o=Kl(Y.state);n?.provider?.syncDappData?.({metadata:o.metadata,sdkVersion:o.sdkVersion,projectId:o.projectId,sdkType:o.sdkType})}},100)},goBackToIndex(e){if(pr.history.length>1){pr.history=pr.history.slice(0,e+1);let[t]=pr.history.slice(-1);t&&(pr.view=t)}},goBackOrCloseModal(){J.state.history.length>1?J.goBack():De.close()}},J=vr(CHe)});var dp,xH,nn,vH=b(()=>{l();Lr();ut();gs();To();dp=rt({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),xH={state:dp,subscribe(e){return Dt(dp,()=>e(dp))},setThemeMode(e){dp.themeMode=e;try{let t=re.getAuthConnector();if(t){let r=xH.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:r,w3mThemeVariables:Y1(r,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){dp.themeVariables={...dp.themeVariables,...e};try{let t=re.getAuthConnector();if(t){let r=xH.getSnapshot().themeVariables;t.provider.syncTheme({themeVariables:r,w3mThemeVariables:Y1(dp.themeVariables,dp.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Kl(dp)}},nn=vr(xH)});var spe,SHe,Kt,IHe,re,To=b(()=>{l();Lr();Hn();ut();mm();yc();w_();wH();ma();gs();Cu();$r();up();Un();gc();vH();spe=Object.fromEntries(sI.map(e=>[e,void 0])),SHe=Object.fromEntries(sI.map(e=>[e,!0])),Kt=rt({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:spe,filterByNamespaceMap:SHe}),IHe={state:Kt,subscribe(e){return Dt(Kt,()=>{e(Kt)})},subscribeKey(e,t){return Tt(Kt,e,t)},initialize(e){e.forEach(t=>{let r=de.getConnectedConnectorId(t);r&&re.setConnectorId(r,t)})},setActiveConnector(e){e&&(Kt.activeConnector=vf(e))},setConnectors(e){e.filter(o=>!Kt.allConnectors.some(s=>s.id===o.id&&re.getConnectorName(s.name)===re.getConnectorName(o.name)&&s.chain===o.chain)).forEach(o=>{o.type!=="MULTI_CHAIN"&&Kt.allConnectors.push(vf(o))});let r=re.getEnabledNamespaces(),n=re.getEnabledConnectors(r);Kt.connectors=re.mergeMultiChainConnectors(n)},filterByNamespaces(e){Object.keys(Kt.filterByNamespaceMap).forEach(t=>{Kt.filterByNamespaceMap[t]=!1}),e.forEach(t=>{Kt.filterByNamespaceMap[t]=!0}),re.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){Kt.filterByNamespaceMap[e]=t,re.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){let e=re.getEnabledNamespaces(),t=re.getEnabledConnectors(e),r=re.areAllNamespacesEnabled();Kt.connectors=re.mergeMultiChainConnectors(t),r?ge.clearFilterByNamespaces():ge.filterByNamespaces(e)},getEnabledNamespaces(){return Object.entries(Kt.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e)},getEnabledConnectors(e){return Kt.allConnectors.filter(t=>e.includes(t.chain))},areAllNamespacesEnabled(){return Object.values(Kt.filterByNamespaceMap).every(e=>e)},mergeMultiChainConnectors(e){let t=re.generateConnectorMapByName(e),r=[];return t.forEach(n=>{let o=n[0],s=o?.id===Z.CONNECTOR_ID.AUTH;n.length>1&&o?r.push({name:o.name,imageUrl:o.imageUrl,imageId:o.imageId,connectors:[...n],type:s?"AUTH":"MULTI_CHAIN",chain:"eip155",id:o?.id||""}):o&&r.push(o)}),r},generateConnectorMapByName(e){let t=new Map;return e.forEach(r=>{let{name:n}=r,o=re.getConnectorName(n);if(!o)return;let s=t.get(o)||[];s.find(a=>a.chain===r.chain)||s.push(r),t.set(o,s)}),t},getConnectorName(e){return e&&({"Trust Wallet":"Trust"}[e]||e)},getUniqueConnectorsByName(e){let t=[];return e.forEach(r=>{t.find(n=>n.chain===r.chain)||t.push(r)}),t},addConnector(e){if(e.id===Z.CONNECTOR_ID.AUTH){let t=e,r=Kl(Y.state),n=nn.getSnapshot().themeMode,o=nn.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType}),t?.provider?.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Y1(o,n)}),re.setConnectors([e])}else re.setConnectors([e])},getAuthConnector(e){let t=e||$.state.activeChain,r=Kt.connectors.find(n=>n.id===Z.CONNECTOR_ID.AUTH);if(r)return r?.connectors?.length?r.connectors.find(o=>o.chain===t):r},getAnnouncedConnectorRdns(){return Kt.connectors.filter(e=>e.type==="ANNOUNCED").map(e=>e.info?.rdns)},getConnectorById(e){return Dn.sortConnectorsByPriority(Kt.allConnectors).find(r=>r.id===e)},getConnector({id:e,namespace:t}){let r=t||$.state.activeChain,n=Kt.allConnectors.filter(i=>i.chain===r);return Dn.sortConnectorsByPriority(n).find(i=>i.id===e||i.explorerId===e)},syncIfAuthConnector(e){if(e.id!=="AUTH")return;let t=e,r=Kl(Y.state),n=nn.getSnapshot().themeMode,o=nn.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,sdkType:r.sdkType,projectId:r.projectId}),t.provider.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Y1(o,n)})},getConnectorsByNamespace(e){let t=Kt.allConnectors.filter(r=>r.chain===e);return re.mergeMultiChainConnectors(t)},canSwitchToSmartAccount(e){return $.checkIfSmartAccountEnabled()&&Fr(e)===Kr.ACCOUNT_TYPES.EOA},selectWalletConnector(e){let t=J.state.data?.redirectView,r=$.state.activeChain,n=r?re.getConnector({id:e.id,namespace:r}):void 0;rpe.handleMobileDeeplinkRedirect(n?.explorerId||e.id,$.state.activeChain),n?J.push("ConnectingExternal",{connector:n,wallet:e,redirectView:t}):J.push("ConnectingWalletConnect",{wallet:e,redirectView:t})},getConnectors(e){return e?re.getConnectorsByNamespace(e):re.mergeMultiChainConnectors(Kt.allConnectors)},setFilterByNamespace(e){Kt.filterByNamespace=e,Kt.connectors=re.getConnectors(e),ge.setFilterByNamespace(e)},setConnectorId(e,t){e&&(Kt.activeConnectorIds={...Kt.activeConnectorIds,[t]:e},de.setConnectedConnectorId(t,e))},removeConnectorId(e){Kt.activeConnectorIds={...Kt.activeConnectorIds,[e]:void 0},de.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return Kt.activeConnectorIds[e]},isConnected(e){return e?!!Kt.activeConnectorIds[e]:Object.values(Kt.activeConnectorIds).some(t=>!!t)},resetConnectorIds(){Kt.activeConnectorIds={...spe}},extendConnectorsWithExplorerWallets(e){Kt.allConnectors.forEach(n=>{let o=e.find(s=>s.id===n.id||s.rdns&&s.rdns===n.info?.rdns);o&&(n.explorerWallet=o)});let t=re.getEnabledNamespaces(),r=re.getEnabledConnectors(t);Kt.connectors=re.mergeMultiChainConnectors(r)},async connect(e={}){let{namespace:t}=e;return re.setFilterByNamespace(t),J.push("Connect",{addWalletForNamespace:t}),new Promise((r,n)=>{if(t){let o=$.subscribeChainProp("accountState",i=>{i?.caipAddress&&(r({caipAddress:i?.caipAddress}),o())},t),s=De.subscribeKey("open",i=>{i||(n(new Error("Modal closed")),s())})}else{let o=$.subscribeKey("activeCaipAddress",i=>{i&&(r({caipAddress:i}),o())}),s=De.subscribeKey("open",i=>{i||(n(new Error("Modal closed")),s())})}})}},re=vr(IHe)});var THe,k6,ipe=b(()=>{l();ut();ut();mm();$r();ai();To();mc();up();gc();yc();ha();$n();ma();THe=1e3,k6={checkNamespaceConnectorId(e,t){return re.getConnectorId(e)===t},isSocialProvider(e){return Ye.DEFAULT_REMOTE_FEATURES.socials.includes(e)},connectWalletConnect({walletConnect:e,connector:t,closeModalOnConnect:r=!0,redirectViewOnModalClose:n="Connect",onOpen:o,onConnect:s}){return new Promise((i,a)=>{if(e&&re.setActiveConnector(t),o?.(se.isMobile()&&e),n){let u=De.subscribeKey("open",d=>{d||(J.state.view!==n&&J.replace(n),u(),a(new Error("Modal closed")))})}let c=$.subscribeKey("activeCaipAddress",u=>{u&&(s?.(),r&&De.close(),c(),i(lt.parseCaipAddress(u)))})})},connectExternal(e){return new Promise((t,r)=>{let n=$.subscribeKey("activeCaipAddress",o=>{o&&(De.close(),n(),t(lt.parseCaipAddress(o)))});ee.connectExternal(e,e.chain).catch(()=>{n(),r(new Error("Connection rejected"))})})},connectSocial({social:e,namespace:t,closeModalOnConnect:r=!0,onOpenFarcaster:n,onConnect:o}){let s,i=!1,a=null,c=t||$.state.activeChain,u=$.subscribeKey("activeCaipAddress",d=>{d&&(r&&De.close(),u())});return new Promise((d,f)=>{async function p(y){if(y.data?.resultUri)if(y.origin===Z.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",p,!1);try{let w=re.getAuthConnector(c);if(w&&!i){s&&s.close(),i=!0;let x=y.data.resultUri;Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:e}}),de.setConnectedSocialProvider(e),await ee.connectExternal({id:w.id,type:w.type,socialUri:x},w.chain);let v=$.state.activeCaipAddress;if(!v){f(new Error("Failed to connect"));return}d(lt.parseCaipAddress(v)),Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:e}})}}catch(w){Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:se.parseError(w)}}),f(new Error("Failed to connect"))}}else Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:"Untrusted Origin"}})}async function h(){if(Ae.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:e}}),e==="farcaster"){n?.();let y=De.subscribeKey("open",x=>{!x&&e==="farcaster"&&(f(new Error("Popup closed")),o?.(),y())}),w=re.getAuthConnector();if(w&&!$.getAccountData(c)?.farcasterUrl)try{let{url:v}=await w.provider.getFarcasterUri();$.setAccountProp("farcasterUrl",v,c)}catch{f(new Error("Failed to connect to farcaster"))}}else{let y=re.getAuthConnector();a=se.returnOpenHref(`${Z.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(y){let{uri:w}=await y.provider.getSocialRedirectUri({provider:e});if(a&&w){a.location.href=w,s=a;let x=setInterval(()=>{s?.closed&&!i&&(f(new Error("Popup closed")),clearInterval(x))},1e3);window.addEventListener("message",p,!1)}else a?.close(),f(new Error("Failed to initiate social connection"))}}catch{f(new Error("Failed to initiate social connection")),a?.close()}}}h()})},connectEmail({closeModalOnConnect:e=!0,redirectViewOnModalClose:t="Connect",onOpen:r,onConnect:n}){return new Promise((o,s)=>{if(r?.(),t){let a=De.subscribeKey("open",c=>{c||(J.state.view!==t&&J.replace(t),a(),s(new Error("Modal closed")))})}let i=$.subscribeKey("activeCaipAddress",a=>{a&&(n?.(),e&&De.close(),i(),o(lt.parseCaipAddress(a)))})})},async updateEmail(){let e=de.getConnectedConnectorId($.state.activeChain),t=re.getAuthConnector();if(!t)throw new Error("No auth connector found");if(e!==Z.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");let r=t.provider.getEmail()??"";return await De.open({view:"UpdateEmailWallet",data:{email:r,redirectView:void 0}}),new Promise((n,o)=>{let s=setInterval(()=>{let a=t.provider.getEmail()??"";a!==r&&(De.close(),clearInterval(s),i(),n({email:a}))},THe),i=De.subscribeKey("open",a=>{a||(J.state.view!=="Connect"&&J.push("Connect"),clearInterval(s),i(),o(new Error("Modal closed")))})})},canSwitchToSmartAccount(e){return $.checkIfSmartAccountEnabled()&&Fr(e)===Kr.ACCOUNT_TYPES.EOA}}});function U6(){let e=$.state.activeCaipNetwork?.chainNamespace||"eip155",t=$.state.activeCaipNetwork?.id||1,r=Ye.NATIVE_TOKEN_ADDRESS[e];return`${e}:${t}:${r}`}function EH(e){return Ye.NATIVE_TOKEN_ADDRESS[e]}function Fr(e){return $.getAccountData(e)?.preferredAccountType}function oy(e){return e?$.state.chains.get(e)?.networkState?.caipNetwork:$.state.activeCaipNetwork}var yc=b(()=>{l();$r();ha()});var fp,AH=b(()=>{l();ai();To();mc();Un();$n();fp={getConnectionStatus(e,t){let r=re.state.activeConnectorIds[t],n=ee.getConnections(t);return!!r&&e.connectorId===r?"connected":n.some(i=>i.connectorId.toLowerCase()===e.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:e,connectorId:t,addresses:r}){return e.map(n=>{if((t?n.connectorId.toLowerCase()===t.toLowerCase():!1)&&r){let s=n.accounts.filter(i=>!r.some(c=>c.toLowerCase()===i.address.toLowerCase()));return{...n,accounts:s}}return n})},excludeExistingConnections(e,t){let r=new Set(e);return t.filter(n=>!r.has(n.connectorId))},getConnectionsByConnectorId(e,t){return e.filter(r=>r.connectorId.toLowerCase()===t.toLowerCase())},getConnectionsData(e){let t=!!Y.state.remoteFeatures?.multiWallet,r=re.state.activeConnectorIds[e],n=ee.getConnections(e),s=(ee.state.recentConnections.get(e)??[]).filter(a=>re.getConnectorById(a.connectorId)),i=fp.excludeExistingConnections([...n.map(a=>a.connectorId),...r?[r]:[]],s);return t?{connections:n,recentConnections:i}:{connections:n.filter(a=>a.connectorId.toLowerCase()===r?.toLowerCase()),recentConnections:[]}},onConnectMobile(e){let t=ee.state.wcUri;if(e?.mobile_link&&t)try{ee.setWcError(!1);let{mobile_link:r,link_mode:n,name:o}=e,{redirect:s,redirectUniversalLink:i,href:a}=se.formatNativeUrl(r,t,n),c=s,u=i,d=se.isIframe()?"_top":"_self";ee.setWcLinking({name:o,href:a}),ee.setRecentWallet(e),Y.state.experimental_preferUniversalLinks&&u?se.openHref(u,d):se.openHref(c,d)}catch(r){Ae.sendEvent({type:"track",event:"CONNECT_PROXY_ERROR",properties:{message:r instanceof Error?r.message:"Error parsing the deep link",uri:t,mobile_link:e.mobile_link,name:e.name}}),ee.setWcError(!0)}}}});var D6,ws,Q3=b(()=>{l();Lr();Hn();D6=rt({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1,connectingWallet:void 0}),ws={state:D6,subscribe(e){return Dt(D6,()=>e(D6))},subscribeOpen(e){return Tt(D6,"open",e)},set(e){Object.assign(D6,{...D6,...e})}}});var on,_He,X3,ape=b(()=>{l();Lr();mm();yc();gs();lp();$r();mc();Un();hm();on=rt({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),_He={state:on,subscribe(e){return Dt(on,()=>e(on))},setLastNetworkInView(e){on.lastNetworkInView=e},async fetchTransactions(e){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");on.loading=!0;try{let t=await ze.fetchTransactions({account:e,cursor:on.next,chainId:$.state.activeCaipNetwork?.caipNetworkId}),r=X3.filterSpamTransactions(t.data),n=X3.filterByConnectedChain(r),o=[...on.transactions,...n];on.loading=!1,on.transactions=o,on.transactionsByYear=X3.groupTransactionsByYearAndMonth(on.transactionsByYear,n),on.empty=o.length===0,on.next=t.next?t.next:void 0}catch{let r=$.state.activeChain;Ae.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:Y.state.projectId,cursor:on.next,isSmartAccount:Fr(r)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),Je.showError("Failed to fetch transactions"),on.loading=!1,on.empty=!0,on.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){let r=e;return t.forEach(n=>{let o=new Date(n.metadata.minedAt).getFullYear(),s=new Date(n.metadata.minedAt).getMonth(),i=r[o]??{},c=(i[s]??[]).filter(u=>u.id!==n.id);r[o]={...i,[s]:[...c,n].sort((u,d)=>new Date(d.metadata.minedAt).getTime()-new Date(u.metadata.minedAt).getTime())}}),r},filterSpamTransactions(e){return e.filter(t=>!t.transfers?.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(e){let t=$.state.activeCaipNetwork?.caipNetworkId;return e.filter(n=>n.metadata.chain===t)},clearCursor(){on.next=void 0},resetTransactions(){on.transactions=[],on.transactionsByYear={},on.lastNetworkInView=void 0,on.loading=!1,on.empty=!1,on.next=void 0}},X3=vr(_He,"API_ERROR")});var Lt,sy,PHe,ee,ai=b(()=>{l();Lr();Hn();ut();yc();AH();ipe();$n();ma();gs();$r();To();mc();up();Q3();gc();ape();Lt=rt({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,wcFetchingUri:!1,buffering:!1,status:"disconnected"}),PHe={state:Lt,subscribe(e){return Dt(Lt,()=>e(Lt))},subscribeKey(e,t){return Tt(Lt,e,t)},_getClient(){return Lt._client},setClient(e){Lt._client=vf(e)},initialize(e){let t=e.filter(r=>!!r.namespace).map(r=>r.namespace);ee.syncStorageConnections(t)},syncStorageConnections(e){let t=de.getConnections(),r=e??Array.from($.state.chains.keys());for(let n of r){let o=t[n]??[],s=new Map(Lt.recentConnections);s.set(n,o),Lt.recentConnections=s}},getConnections(e){return e?Lt.connections.get(e)??[]:[]},hasAnyConnection(e){let t=ee.state.connections;return Array.from(t.values()).flatMap(r=>r).some(({connectorId:r})=>r===e)},async connectWalletConnect({cache:e="auto"}={}){Lt.wcFetchingUri=!0;let t=se.isTelegram()||se.isSafari()&&se.isIos();if(e==="always"||e==="auto"&&t){if(sy){await sy,sy=void 0;return}if(!se.isPairingExpired(Lt?.wcPairingExpiry)){let r=Lt.wcUri;Lt.wcUri=r;return}sy=ee._getClient()?.connectWalletConnect?.().catch(()=>{}),ee.state.status="connecting",await sy,sy=void 0,Lt.wcPairingExpiry=void 0,ee.state.status="connected"}else await ee._getClient()?.connectWalletConnect?.()},async connectExternal(e,t,r=!0){let n=await ee._getClient()?.connectExternal?.(e);r&&$.setActiveNamespace(t);let o=re.state.allConnectors.find(i=>i.id===e?.id),s=e.type==="AUTH"?"email":"browser";return Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s,name:o?.name||"Unknown",view:J.state.view,walletRank:o?.explorerWallet?.order}}),n},async reconnectExternal(e){await ee._getClient()?.reconnectExternal?.(e);let t=e.chain||$.state.activeChain;t&&re.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){if(!t)return;De.setLoading(!0,$.state.activeChain);let r=re.getAuthConnector();r&&($.setAccountProp("preferredAccountType",e,t),await r.provider.setPreferredAccount(e),de.setPreferredAccountTypes(Object.entries($.state.chains).reduce((n,[o,s])=>{let i=o,a=Fr(i);return a!==void 0&&(n[i]=a),n},{})),await ee.reconnectExternal(r),De.setLoading(!1,$.state.activeChain),Ae.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:$.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(e){return ee._getClient()?.signMessage(e)},parseUnits(e,t){return ee._getClient()?.parseUnits(e,t)},formatUnits(e,t){return ee._getClient()?.formatUnits(e,t)},updateBalance(e){return ee._getClient()?.updateBalance(e)},async sendTransaction(e){return ee._getClient()?.sendTransaction(e)},async getCapabilities(e){return ee._getClient()?.getCapabilities(e)},async grantPermissions(e){return ee._getClient()?.grantPermissions(e)},async walletGetAssets(e){return ee._getClient()?.walletGetAssets(e)??{}},async estimateGas(e){return ee._getClient()?.estimateGas(e)},async writeContract(e){return ee._getClient()?.writeContract(e)},async writeSolanaTransaction(e){return ee._getClient()?.writeSolanaTransaction(e)},async getEnsAddress(e){return ee._getClient()?.getEnsAddress(e)},async getEnsAvatar(e){return ee._getClient()?.getEnsAvatar(e)},checkInstalled(e){return ee._getClient()?.checkInstalled?.(e)||!1},resetWcConnection(){Lt.wcUri=void 0,Lt.wcPairingExpiry=void 0,Lt.wcLinking=void 0,Lt.recentWallet=void 0,Lt.wcFetchingUri=!1,Lt.status="disconnected",X3.resetTransactions(),de.deleteWalletConnectDeepLink(),de.deleteRecentWallet(),ws.set({connectingWallet:void 0})},resetUri(){Lt.wcUri=void 0,Lt.wcPairingExpiry=void 0,sy=void 0,Lt.wcFetchingUri=!1,ws.set({connectingWallet:void 0})},finalizeWcConnection(e){let{wcLinking:t,recentWallet:r}=ee.state;t&&de.setWalletConnectDeepLink(t),r&&de.setAppKitRecent(r),e&&Ae.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:t?"mobile":"qrcode",name:J.state.data?.wallet?.name||"Unknown",view:J.state.view,walletRank:r?.order}})},setWcBasic(e){Lt.wcBasic=e},setUri(e){Lt.wcUri=e,Lt.wcFetchingUri=!1,Lt.wcPairingExpiry=se.getPairingExpiry()},setWcLinking(e){Lt.wcLinking=e},setWcError(e){Lt.wcError=e,Lt.wcFetchingUri=!1,Lt.buffering=!1},setRecentWallet(e){Lt.recentWallet=e},setBuffering(e){Lt.buffering=e},setStatus(e){Lt.status=e},setIsSwitchingConnection(e){Lt.isSwitchingConnection=e},async disconnect({id:e,namespace:t,initialDisconnect:r}={}){try{await ee._getClient()?.disconnect({id:e,chainNamespace:t,initialDisconnect:r})}catch(n){throw new hc("Failed to disconnect","INTERNAL_SDK_ERROR",n)}},async disconnectConnector({id:e,namespace:t}){try{await ee._getClient()?.disconnectConnector({id:e,namespace:t})}catch(r){throw new hc("Failed to disconnect connector","INTERNAL_SDK_ERROR",r)}},setConnections(e,t){let r=new Map(Lt.connections);r.set(t,e),Lt.connections=r},async handleAuthAccountSwitch({address:e,namespace:t}){let n=$.getAccountData(t)?.user?.accounts?.find(s=>s.type==="smartAccount"),o=n&&n.address.toLowerCase()===e.toLowerCase()&&k6.canSwitchToSmartAccount(t)?"smartAccount":"eoa";await ee.setPreferredAccountType(o,t)},async handleActiveConnection({connection:e,namespace:t,address:r}){let n=re.getConnectorById(e.connectorId),o=e.connectorId===Z.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${e.connectorId}`);if(o)r&&await ee.handleAuthAccountSwitch({address:r,namespace:t});else return(await ee.connectExternal({id:n.id,type:n.type,provider:n.provider,address:r,chain:t},t))?.address;return r},async handleDisconnectedConnection({connection:e,namespace:t,address:r,closeModalOnConnect:n}){let o=re.getConnectorById(e.connectorId),s=e.auth?.name?.toLowerCase(),i=e.connectorId===Z.CONNECTOR_ID.AUTH,a=e.connectorId===Z.CONNECTOR_ID.WALLET_CONNECT;if(!o)throw new Error(`No connector found for connection: ${e.connectorId}`);let c;if(i)if(s&&k6.isSocialProvider(s)){let{address:u}=await k6.connectSocial({social:s,closeModalOnConnect:n,onOpenFarcaster(){De.open({view:"ConnectingFarcaster"})},onConnect(){J.replace("ProfileWallets")}});c=u}else{let{address:u}=await k6.connectEmail({closeModalOnConnect:n,onOpen(){De.open({view:"EmailLogin"})},onConnect(){J.replace("ProfileWallets")}});c=u}else if(a){let{address:u}=await k6.connectWalletConnect({walletConnect:!0,connector:o,closeModalOnConnect:n,onOpen(d){let f=d?"AllWallets":"ConnectingWalletConnect";De.state.open?J.push(f):De.open({view:f})},onConnect(){J.replace("ProfileWallets")}});c=u}else{let u=await ee.connectExternal({id:o.id,type:o.type,provider:o.provider,chain:t},t);u&&(c=u.address)}return i&&r&&await ee.handleAuthAccountSwitch({address:r,namespace:t}),c},async switchConnection({connection:e,address:t,namespace:r,closeModalOnConnect:n,onChange:o}){let s,i=$.getAccountData(r)?.caipAddress;if(i){let{address:c}=lt.parseCaipAddress(i);s=c}let a=fp.getConnectionStatus(e,r);switch(a){case"connected":case"active":{let c=await ee.handleActiveConnection({connection:e,namespace:r,address:t});if(s&&c){let u=c.toLowerCase()!==s.toLowerCase();o?.({address:c,namespace:r,hasSwitchedAccount:u,hasSwitchedWallet:a==="active"})}break}case"disconnected":{let c=await ee.handleDisconnectedConnection({connection:e,namespace:r,address:t,closeModalOnConnect:n});c&&o?.({address:c,namespace:r,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},ee=vr(PHe)});var b_,cpe=b(()=>{l();R6();b_={createBalance(e,t){let r={name:e.metadata.name||"",symbol:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:r.name,symbol:r.symbol,chainId:t,address:e.address==="native"?void 0:this.convertAddressToCAIP10Address(e.address,t),value:r.value,price:r.price,quantity:{decimals:r.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:r.decimals})},iconUrl:r.iconUrl}},convertHexToBalance({hex:e,decimals:t}){return pc(BigInt(e),t)},convertAddressToCAIP10Address(e,t){return`${t}:${e}`},createCAIP2ChainId(e,t){return`${t}:${parseInt(e,16)}`},getChainIdHexFromCAIP2ChainId(e){let t=e.split(":");if(t.length<2||!t[1])return"0x0";let r=t[1],n=parseInt(r,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(e){return typeof e!="object"||e===null?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(r=>this.isValidAsset(r)))},isValidAsset(e){return typeof e=="object"&&e!==null&&typeof e.address=="string"&&typeof e.balance=="string"&&(e.type==="ERC20"||e.type==="NATIVE")&&typeof e.metadata=="object"&&e.metadata!==null&&typeof e.metadata.name=="string"&&typeof e.metadata.symbol=="string"&&typeof e.metadata.decimals=="number"&&typeof e.metadata.price=="number"&&typeof e.metadata.iconUrl=="string"}}});async function lpe(){if(!CH){let{createPublicClient:e,http:t,defineChain:r}=await Promise.resolve().then(()=>(R6(),Yfe));CH={createPublicClient:e,http:t,defineChain:r}}return CH}var CH,x_,upe=b(()=>{l();ut();Un();x_={getBlockchainApiRpcUrl(e,t){let r=new URL("https://rpc.walletconnect.org/v1/");return r.searchParams.set("chainId",e),r.searchParams.set("projectId",t),r.toString()},async getViemChain(e){let{defineChain:t}=await lpe(),{chainId:r}=lt.parseCaipNetworkId(e.caipNetworkId);return t({...e,id:Number(r)})},async createViemPublicClient(e){let{createPublicClient:t,http:r}=await lpe(),n=Y.state.projectId,o=await x_.getViemChain(e);if(!o)throw new Error(`Chain ${e.caipNetworkId} not found in viem/chains`);return t({chain:o,transport:r(x_.getBlockchainApiRpcUrl(e.caipNetworkId,n))})}}});var al,L6=b(()=>{l();R6();ut();lp();$r();ai();To();cpe();ma();upe();al={async getMyTokensWithBalance(e={forceUpdate:void 0,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address}){let{forceUpdate:t,caipNetwork:r,address:n}=e,o=re.getConnectorId("eip155")===Z.CONNECTOR_ID.AUTH;if(!n)return[];let s=r?`${r.caipNetworkId}:${n}`:n,i=de.getBalanceCacheForCaipAddress(s);if(i)return i.balances;if(r&&r.chainNamespace===Z.CHAIN.EVM&&o){let c=await this.getEIP155Balances(n,r);if(c)return this.filterLowQualityTokens(c)}let a=await ze.getBalance(n,r?.caipNetworkId,t);return this.filterLowQualityTokens(a.balances)},async getEIP155Balances(e,t){try{let r=b_.getChainIdHexFromCAIP2ChainId(t.caipNetworkId);if(!(await ee.getCapabilities(e))?.[r]?.assetDiscovery?.supported)return null;let o=await ee.walletGetAssets({account:e,chainFilter:[r]});if(!b_.isWalletGetAssetsResponse(o))return null;let i=(o[r]||[]).map(a=>b_.createBalance(a,t.caipNetworkId));return de.updateBalanceCache({caipAddress:`${t.caipNetworkId}:${e}`,balance:{balances:i},timestamp:Date.now()}),i}catch{return null}},filterLowQualityTokens(e){return e.filter(t=>t.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:e,assetAddress:t,caipNetwork:r}){let n=await x_.createViemPublicClient(r),{address:o}=lt.parseCaipAddress(e),[{result:s},{result:i},{result:a},{result:c}]=await n.multicall({contracts:[{address:t,functionName:"name",args:[],abi:Hr},{address:t,functionName:"symbol",args:[],abi:Hr},{address:t,functionName:"balanceOf",args:[o],abi:Hr},{address:t,functionName:"decimals",args:[],abi:Hr}]});return{name:s,symbol:i,decimals:c,balance:a&&c?pc(a,c):"0"}}}});var SH,iy,IH=b(()=>{l();SH={adapters:{}},iy={state:SH,initialize(e){SH.adapters={...e}},get(e){return SH.adapters[e]}}});var v_,Mi,ar,E_=b(()=>{l();Lr();Hn();v_={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:void 0},Mi=rt({providers:{...v_},providerIds:{...v_}}),ar={state:Mi,subscribeKey(e,t){return Tt(Mi,e,t)},subscribe(e){return Dt(Mi,()=>{e(Mi)})},subscribeProviders(e){return Dt(Mi.providers,()=>e(Mi.providers))},setProvider(e,t){e&&t&&(Mi.providers[e]=vf(t))},getProvider(e){if(e)return Mi.providers[e]},setProviderId(e,t){t&&(Mi.providerIds[e]=t)},getProviderId(e){if(e)return Mi.providerIds[e]},reset(){Mi.providers={...v_},Mi.providerIds={...v_}},resetChain(e){Mi.providers[e]=void 0,Mi.providerIds[e]=void 0}}});var ym,TH=b(()=>{l();lp();$r();ai();L6();yc();ym={async getTokenList(e){return(await ze.fetchSwapTokens({chainId:e}))?.tokens?.map(n=>({...n,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){let e=$.state.activeCaipNetwork;if(!e)return null;try{if(e.chainNamespace==="solana"){let t=(await ee?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:t,fast:t,instant:t}}else return await ze.fetchGasPrice({chainId:e.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:e,userAddress:t,sourceTokenAmount:r,sourceTokenDecimals:n}){let o=await ze.fetchSwapAllowance({tokenAddress:e,userAddress:t});if(o?.allowance&&r&&n){let s=ee.parseUnits(r,n)||0;return BigInt(o.allowance)>=s}return!1},async getMyTokensWithBalance(e){let t=await al.getMyTokensWithBalance({forceUpdate:e,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address});return $.setAccountProp("tokenBalance",t,$.state.activeChain),this.mapBalancesToSwapTokens(t)},mapBalancesToSwapTokens(e){return e?.map(t=>({...t,address:t?.address?t.address:U6(),decimals:parseInt(t.quantity.decimals,10),logoUri:t.iconUrl,eip2612:!1}))||[]},async handleSwapError(e){try{let t=e?.cause;return t?.json&&(await t.json())?.reasons?.[0]?.description?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}}});var Zt,NHe,xt,_H=b(()=>{l();Lr();Hn();ut();ut();mm();L6();yc();ha();$n();TH();gs();$r();ai();mc();gc();hm();Zt=rt({tokenBalances:[],loading:!1}),NHe={state:Zt,subscribe(e){return Dt(Zt,()=>e(Zt))},subscribeKey(e,t){return Tt(Zt,e,t)},setToken(e){e&&(Zt.token=vf(e))},setTokenAmount(e){Zt.sendTokenAmount=e},setReceiverAddress(e){Zt.receiverAddress=e},setReceiverProfileImageUrl(e){Zt.receiverProfileImageUrl=e},setReceiverProfileName(e){Zt.receiverProfileName=e},setNetworkBalanceInUsd(e){Zt.networkBalanceInUSD=e},setLoading(e){Zt.loading=e},getSdkEventProperties(e){return{message:se.parseError(e),isSmartAccount:Fr($.state.activeChain)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:Zt.token?.symbol||"",amount:Zt.sendTokenAmount??0,network:$.state.activeCaipNetwork?.caipNetworkId||""}},async sendToken(){try{switch(xt.setLoading(!0),$.state.activeCaipNetwork?.chainNamespace){case"eip155":await xt.sendEvmToken();return;case"solana":await xt.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw js.isUserRejectedRequestError(e)?new Z1(e):e}finally{xt.setLoading(!1)}},async sendEvmToken(){let e=$.state.activeChain;if(!e)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");let t=Fr(e);if(!xt.state.sendTokenAmount||!xt.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!xt.state.token)throw new Error("A token is required");if(xt.state.token?.address){Ae.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token.address,amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||""}});let{hash:r}=await xt.sendERC20Token({receiverAddress:xt.state.receiverAddress,tokenAddress:xt.state.token.address,sendTokenAmount:xt.state.sendTokenAmount,decimals:xt.state.token.quantity.decimals});r&&(Zt.hash=r)}else{Ae.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token.symbol||"",amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||""}});let{hash:r}=await xt.sendNativeToken({receiverAddress:xt.state.receiverAddress,sendTokenAmount:xt.state.sendTokenAmount,decimals:xt.state.token.quantity.decimals});r&&(Zt.hash=r)}},async fetchTokenBalance(e){Zt.loading=!0;let t=$.state.activeChain,r=$.state.activeCaipNetwork?.caipNetworkId,n=$.state.activeCaipNetwork?.chainNamespace,o=$.getAccountData(t)?.caipAddress??$.state.activeCaipAddress,s=o?se.getPlainAddress(o):void 0;if(Zt.lastRetry&&!se.isAllowedRetry(Zt.lastRetry,30*Ye.ONE_SEC_MS))return Zt.loading=!1,[];try{if(s&&r&&n){let i=await al.getMyTokensWithBalance();return Zt.tokenBalances=i,Zt.lastRetry=void 0,i}}catch(i){Zt.lastRetry=Date.now(),e?.(i),Je.showError("Token Balance Unavailable")}finally{Zt.loading=!1}return[]},fetchNetworkBalance(){if(Zt.tokenBalances.length===0)return;let e=ym.mapBalancesToSwapTokens(Zt.tokenBalances);if(!e)return;let t=e.find(r=>r.address===U6());t&&(Zt.networkBalanceInUSD=t?ht.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){J.pushTransactionStack({});let t=e.receiverAddress,r=$.getAccountData()?.address,n=ee.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),s=await ee.sendTransaction({chainNamespace:Z.CHAIN.EVM,to:t,address:r,data:"0x",value:n??BigInt(0)});return Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Fr("eip155")===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token?.symbol||"",amount:e.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:s||""}}),ee._getClient()?.updateBalance("eip155"),xt.resetSend(),{hash:s}},async sendERC20Token(e){J.pushTransactionStack({onSuccess(){J.replace("Account")}});let t=ee.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),r=$.getAccountData()?.address;if(r&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){let n=se.getPlainAddress(e.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");let o=await ee.writeContract({fromAddress:r,tokenAddress:n,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:f4.getERC20Abi(n),chainNamespace:Z.CHAIN.EVM});return Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Fr("eip155")===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,token:xt.state.token?.symbol||"",amount:e.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:o||""}}),xt.resetSend(),{hash:o}}return{hash:void 0}},async sendSolanaToken(){if(!xt.state.sendTokenAmount||!xt.state.receiverAddress)throw new Error("An amount and receiver address are required");J.pushTransactionStack({onSuccess(){J.replace("Account")}});let e;xt.state.token&&xt.state.token.address!==Ye.SOLANA_NATIVE_TOKEN_ADDRESS&&(se.isCaipAddress(xt.state.token.address)?e=se.getPlainAddress(xt.state.token.address):e=xt.state.token.address);let t=await ee.sendTransaction({chainNamespace:"solana",tokenMint:e,to:xt.state.receiverAddress,value:xt.state.sendTokenAmount});t&&(Zt.hash=t),ee._getClient()?.updateBalance("solana"),Ae.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:xt.state.token?.symbol||"",amount:xt.state.sendTokenAmount,network:$.state.activeCaipNetwork?.caipNetworkId||"",hash:t||""}}),xt.resetSend()},resetSend(){Zt.token=void 0,Zt.sendTokenAmount=void 0,Zt.receiverAddress=void 0,Zt.receiverProfileImageUrl=void 0,Zt.receiverProfileName=void 0,Zt.loading=!1,Zt.tokenBalances=[]}},xt=vr(NHe)});var PH,A_,Oe,dpe,$,$r=b(()=>{l();Lr();Hn();ut();_te();L6();ha();$n();ma();gs();IH();ai();To();mc();up();Un();E_();Q3();_H();hm();PH={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},A_={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},Oe=rt({chains:Cte(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),dpe={state:Oe,subscribe(e){return Dt(Oe,()=>{e(Oe)})},subscribeKey(e,t){return Tt(Oe,e,t)},subscribeAccountStateProp(e,t,r){let n=r||Oe.activeChain;return n?Tt(Oe.chains.get(n)?.accountState||{},e,t):()=>{}},subscribeChainProp(e,t,r){let n;return Dt(Oe.chains,()=>{let o=r||Oe.activeChain;if(o){let s=Oe.chains.get(o)?.[e];n!==s&&(n=s,t(s))}})},initialize(e,t,r){let{chainId:n,namespace:o}=de.getActiveNetworkProps(),s=t?.find(d=>d.id.toString()===n?.toString()),a=e.find(d=>d?.namespace===o)||e?.[0],c=e.map(d=>d.namespace).filter(d=>d!==void 0),u=Y.state.enableEmbedded?new Set([...c]):new Set([...t?.map(d=>d.chainNamespace)??[]]);(e?.length===0||!a)&&(Oe.noAdapters=!0),Oe.noAdapters||(Oe.activeChain=a?.namespace,Oe.activeCaipNetwork=s,$.setChainNetworkData(a?.namespace,{caipNetwork:s}),Oe.activeChain&&ws.set({activeChain:a?.namespace})),u.forEach(d=>{let f=t?.filter(y=>y.chainNamespace===d),p=de.getPreferredAccountTypes()||{},h={...Y.state.defaultAccountTypes,...p};$.state.chains.set(d,{namespace:d,networkState:rt({...A_,caipNetwork:f?.[0]}),accountState:rt({...PH,preferredAccountType:h[d]}),caipNetworks:f??[],...r}),$.setRequestedCaipNetworks(f??[],d)})},removeAdapter(e){if(Oe.activeChain===e){let t=Array.from(Oe.chains.entries()).find(([r])=>r!==e);if(t){let r=t[1]?.caipNetworks?.[0];r&&$.setActiveCaipNetwork(r)}}Oe.chains.delete(e)},addAdapter(e,{connectionControllerClient:t},r){if(!e.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");Oe.chains.set(e.namespace,{namespace:e.namespace,networkState:{...A_,caipNetwork:r[0]},accountState:{...PH},caipNetworks:r,connectionControllerClient:t}),$.setRequestedCaipNetworks(r?.filter(n=>n.chainNamespace===e.namespace)??[],e.namespace)},addNetwork(e){let t=Oe.chains.get(e.chainNamespace);if(t){let r=[...t.caipNetworks||[]];t.caipNetworks?.find(n=>n.id===e.id)||r.push(e),Oe.chains.set(e.chainNamespace,{...t,caipNetworks:r}),$.setRequestedCaipNetworks(r,e.chainNamespace),re.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){let r=Oe.chains.get(e);if(r){let n=Oe.activeCaipNetwork?.id===t,o=[...r.caipNetworks?.filter(s=>s.id!==t)||[]];n&&r?.caipNetworks?.[0]&&$.setActiveCaipNetwork(r.caipNetworks[0]),Oe.chains.set(e,{...r,caipNetworks:o}),$.setRequestedCaipNetworks(o||[],e),o.length===0&&re.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){let r=Oe.chains.get(e);r&&(r.networkState={...r.networkState||A_,...t},Oe.chains.set(e,r))},setChainAccountData(e,t,r=!0){if(!e)throw new Error("Chain is required to update chain account data");let n=Oe.chains.get(e);if(n){let o={...n.accountState||PH,...t};Oe.chains.set(e,{...n,accountState:o}),(Oe.chains.size===1||Oe.activeChain===e)&&t.caipAddress&&(Oe.activeCaipAddress=t.caipAddress)}},setChainNetworkData(e,t){if(!e)return;let r=Oe.chains.get(e);if(r){let n={...r.networkState||A_,...t};Oe.chains.set(e,{...r,networkState:n})}},setAccountProp(e,t,r,n=!0){$.setChainAccountData(r,{[e]:t},n)},setActiveNamespace(e){Oe.activeChain=e;let t=e?Oe.chains.get(e):void 0,r=t?.networkState?.caipNetwork;r?.id&&e&&(Oe.activeCaipAddress=t?.accountState?.caipAddress,Oe.activeCaipNetwork=r,$.setChainNetworkData(e,{caipNetwork:r}),de.setActiveCaipNetworkId(r?.caipNetworkId),ws.set({activeChain:e,selectedNetworkId:r?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;let t=Oe.activeChain===e.chainNamespace;t||$.setIsSwitchingNamespace(!0);let r=Oe.chains.get(e.chainNamespace);Oe.activeChain=e.chainNamespace,Oe.activeCaipNetwork=e,$.setChainNetworkData(e.chainNamespace,{caipNetwork:e});let n=r?.accountState?.address;if(n)Oe.activeCaipAddress=`${e.chainNamespace}:${e.id}:${n}`;else if(t&&Oe.activeCaipAddress){let{address:s}=lt.parseCaipAddress(Oe.activeCaipAddress);n=s,Oe.activeCaipAddress=`${e.caipNetworkId}:${n}`}else Oe.activeCaipAddress=void 0;$.setChainAccountData(e.chainNamespace,{address:n,caipAddress:Oe.activeCaipAddress}),xt.resetSend(),ws.set({activeChain:Oe.activeChain,selectedNetworkId:Oe.activeCaipNetwork?.caipNetworkId}),de.setActiveCaipNetworkId(e.caipNetworkId),!$.checkIfSupportedNetwork(e.chainNamespace)&&Y.state.enableNetworkSwitch&&!Y.state.allowUnsupportedChain&&!ee.state.wcBasic&&$.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;let t=Oe.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;let t=e!==$.state.activeChain,r=$.getNetworkData(e)?.caipNetwork,n=$.getCaipNetworkByNamespace(e,r?.id);t&&n&&await $.switchActiveNetwork(n)},async switchActiveNetwork(e,{throwOnFailure:t=!1}={}){let r=$.state.activeChain;if(!r)throw new Error("ChainController:switchActiveNetwork - namespace is required");let n=ar.getProviderId(Oe.activeChain)==="AUTH",o=$.getAccountData(r)?.address,s=Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e.chainNamespace);try{if(o&&e.chainNamespace===r||n&&s){let i=iy.get(e.chainNamespace);if(!i)throw new Error("Adapter not found");await i.switchNetwork({caipNetwork:e})}$.setActiveCaipNetwork(e)}catch(i){if(t)throw i}Ae.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})},getConnectionControllerClient(e){let t=e||Oe.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");let r=Oe.chains.get(t);if(!r?.connectionControllerClient)throw new Error("ConnectionController client not set");return r.connectionControllerClient},getNetworkProp(e,t){let r=Oe.chains.get(t)?.networkState;if(r)return r[e]},getRequestedCaipNetworks(e){let t=Oe.chains.get(e),{approvedCaipNetworkIds:r=[],requestedCaipNetworks:n=[]}=t?.networkState||{};return se.sortRequestedNetworks(r,n).filter(i=>i?.id)},getAllRequestedCaipNetworks(){let e=[];return Oe.chains.forEach(t=>{if(!t.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");let r=$.getRequestedCaipNetworks(t.namespace);e.push(...r)}),e},setRequestedCaipNetworks(e,t){$.setAdapterNetworkState(t,{requestedCaipNetworks:e});let n=$.getAllRequestedCaipNetworks().map(s=>s.chainNamespace),o=Array.from(new Set(n));re.filterByNamespaces(o)},getAllApprovedCaipNetworkIds(){let e=[];return Oe.chains.forEach(t=>{if(!t.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");let r=$.getApprovedCaipNetworkIds(t.namespace);e.push(...r)}),e},getActiveCaipNetwork(e){return e?Oe.chains.get(e)?.networkState?.caipNetwork:Oe.activeCaipNetwork},getActiveCaipAddress(){return Oe.activeCaipAddress},getApprovedCaipNetworkIds(e){return Oe.chains.get(e)?.networkState?.approvedCaipNetworkIds||[]},setApprovedCaipNetworksData(e,t){$.setAdapterNetworkState(e,t)},checkIfSupportedNetwork(e,t){let r=t||Oe.activeCaipNetwork?.caipNetworkId,n=$.getRequestedCaipNetworks(e);return n.length?n?.some(o=>o.caipNetworkId===r):!0},checkIfSupportedChainId(e){return Oe.activeChain?$.getRequestedCaipNetworks(Oe.activeChain)?.some(r=>r.id===e):!0},checkIfSmartAccountEnabled(){let e=V1.caipNetworkIdToNumber(Oe.activeCaipNetwork?.caipNetworkId);return!Oe.activeChain||!e?!1:!!(Ew.get(Qa.SMART_ACCOUNT_ENABLED_NETWORKS)?.split(",")||[])?.includes(e.toString())},showUnsupportedChainUI(){De.open({view:"UnsupportedChain"})},checkIfNamesSupported(){let e=Oe.activeCaipNetwork;return!!(e?.chainNamespace&&Ye.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){$.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(e){let t=e;if(!t)throw new Error("Chain is required to set account prop");let r=$.state.chains.get(t)?.accountState?.preferredAccountType,n=Y.state.defaultAccountTypes[t];Oe.activeCaipAddress=void 0,$.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:n||r,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),re.removeConnectorId(t)},setIsSwitchingNamespace(e){Oe.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){let e=[],t;if(Oe.chains.forEach(r=>{Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&e.push(r.namespace)}),e.length>0){let r=e[0];return t=r?Oe.chains.get(r)?.caipNetworks?.[0]:void 0,t}},getAccountData(e){let t=e||Oe.activeChain;if(t)return $.state.chains.get(t)?.accountState},getNetworkData(e){let t=e||Oe.activeChain;if(t)return $.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;let r=$.state.chains.get(e),n=r?.caipNetworks?.find(o=>o.id.toString()===t?.toString());return n||r?.networkState?.caipNetwork||r?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){let e=re.state.filterByNamespace;return(e?[Oe.chains.get(e)]:Array.from(Oe.chains.values())).flatMap(r=>r?.caipNetworks||[]).map(r=>r.caipNetworkId)},getCaipNetworks(e){return e?$.getRequestedCaipNetworks(e):$.getAllRequestedCaipNetworks()},getCaipNetworkById(e,t){return dpe.getCaipNetworks(t).find(r=>r.id.toString()===e.toString()||r.caipNetworkId.toString()===e.toString())},setLastConnectedSIWECaipNetwork(e){Oe.lastConnectedSIWECaipNetwork=e},getLastConnectedSIWECaipNetwork(){return Oe.lastConnectedSIWECaipNetwork},async fetchTokenBalance(e){let t=$.getAccountData();if(!t)return[];let r=$.state.activeCaipNetwork?.caipNetworkId,n=$.state.activeCaipNetwork?.chainNamespace,o=$.state.activeCaipAddress,s=o?se.getPlainAddress(o):void 0;if($.setAccountProp("balanceLoading",!0,n),t.lastRetry&&!se.isAllowedRetry(t.lastRetry,30*Ye.ONE_SEC_MS))return $.setAccountProp("balanceLoading",!1,n),[];try{if(s&&r&&n){let i=await al.getMyTokensWithBalance();return $.setAccountProp("tokenBalance",i,n),$.setAccountProp("lastRetry",void 0,n),$.setAccountProp("balanceLoading",!1,n),i}}catch(i){$.setAccountProp("lastRetry",Date.now(),n),e?.(i),Je.showError("Token Balance Unavailable")}finally{$.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(e){let t=e.chainNamespace,r=!!$.getAccountData(t)?.caipAddress,n=$.getAllApprovedCaipNetworkIds(),o=$.getNetworkProp("supportsAllNetworks",t)!==!1,s=re.getConnectorId(t),i=re.getAuthConnector(),a=s===Z.CONNECTOR_ID.AUTH&&i;return!r||o||a?!1:!n?.includes(e.caipNetworkId)}},$=vr(dpe)});var fpe,ppe=b(()=>{l();ut();$r();To();gc();fpe={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){let r=$.state.activeCaipNetwork,n=$.state.activeChain,o=J.state.data;if(e.id===r?.id)return;let i=!!$.getAccountData(n)?.address,a=!!$.getAccountData(e.chainNamespace)?.address,c=e.chainNamespace!==n,d=re.getConnectorId(n)===Z.CONNECTOR_ID.AUTH,f=Z.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(p=>p===e.chainNamespace);t||d&&f?J.push("SwitchNetwork",{...o,network:e}):i&&c&&!a?J.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):J.push("SwitchNetwork",{...o,network:e})}}});var Hi,RHe,De,up=b(()=>{l();Lr();Hn();$n();ppe();gs();Cu();$r();ai();To();mc();Un();Q3();gc();Hi=rt({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),RHe={state:Hi,subscribe(e){return Dt(Hi,()=>e(Hi))},subscribeKey(e,t){return Tt(Hi,e,t)},async open(e){let t=e?.namespace,r=$.state.activeChain,n=t&&t!==r,o=$.getAccountData(e?.namespace)?.caipAddress,s=$.state.noAdapters;if(ee.state.wcBasic?ge.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await ge.prefetch(),re.setFilterByNamespace(e?.namespace),De.setLoading(!0,t),t&&n){let i=$.getNetworkData(t)?.caipNetwork||$.getRequestedCaipNetworks(t)[0];i&&(s?(await $.switchActiveNetwork(i),J.push("ConnectingWalletConnectBasic")):fpe.onSwitchNetwork({network:i,ignoreSwitchConfirmation:!0}))}else Y.state.manualWCControl||s&&!o?se.isMobile()?J.reset("AllWallets"):J.reset("ConnectingWalletConnectBasic"):e?.view?J.reset(e.view,e.data):o?J.reset("Account"):J.reset("Connect");Hi.open=!0,ws.set({open:!0}),Ae.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!o}})},close(){let e=Y.state.enableEmbedded,t=!!$.state.activeCaipAddress;Hi.open&&Ae.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),Hi.open=!1,J.reset("Connect"),De.clearLoading(),e?t?J.replace("Account"):J.push("Connect"):ws.set({open:!1}),ee.resetUri()},setLoading(e,t){t&&Hi.loadingNamespaceMap.set(t,e),Hi.loading=e,ws.set({loading:e})},clearLoading(){Hi.loadingNamespaceMap.clear(),Hi.loading=!1,ws.set({loading:!1})},shake(){Hi.shake||(Hi.shake=!0,setTimeout(()=>{Hi.shake=!1},500))}},De=vr(RHe)});var e5,NH,OHe,Jt,BHe,t5,hpe=b(()=>{l();Lr();Hn();ut();ha();gs();Cu();lp();$r();Un();e5={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},NH={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},OHe={providers:BU,selectedProvider:null,error:null,purchaseCurrency:e5,paymentCurrency:NH,purchaseCurrencies:[e5],paymentCurrencies:[],quotesLoading:!1},Jt=rt(OHe),BHe={state:Jt,subscribe(e){return Dt(Jt,()=>e(Jt))},subscribeKey(e,t){return Tt(Jt,e,t)},setSelectedProvider(e){if(e&&e.name==="meld"){let t=$.state.activeChain,r=t===Z.CHAIN.SOLANA?"SOL":"USDC",n=t?$.state.chains.get(t)?.accountState?.address??"":"",o=new URL(e.url);o.searchParams.append("publicKey",Ste),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",n),o.searchParams.append("externalCustomerId",Y.state.projectId),Jt.selectedProvider={...e,url:o.toString()}}else Jt.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(t=>typeof t=="string")){let t=e,r=BU.filter(n=>t.includes(n.name));Jt.providers=r}else Jt.providers=[]},setPurchaseCurrency(e){Jt.purchaseCurrency=e},setPaymentCurrency(e){Jt.paymentCurrency=e},setPurchaseAmount(e){t5.state.purchaseAmount=e},setPaymentAmount(e){t5.state.paymentAmount=e},async getAvailableCurrencies(){let e=await ze.getOnrampOptions();Jt.purchaseCurrencies=e.purchaseCurrencies,Jt.paymentCurrencies=e.paymentCurrencies,Jt.paymentCurrency=e.paymentCurrencies[0]||NH,Jt.purchaseCurrency=e.purchaseCurrencies[0]||e5,await ge.fetchCurrencyImages(e.paymentCurrencies.map(t=>t.id)),await ge.fetchTokenImages(e.purchaseCurrencies.map(t=>t.symbol))},async getQuote(){Jt.quotesLoading=!0;try{let e=await ze.getOnrampQuote({purchaseCurrency:Jt.purchaseCurrency,paymentCurrency:Jt.paymentCurrency,amount:Jt.paymentAmount?.toString()||"0",network:Jt.purchaseCurrency?.symbol});return Jt.quotesLoading=!1,Jt.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return Jt.error=e.message,Jt.quotesLoading=!1,null}finally{Jt.quotesLoading=!1}},resetState(){Jt.selectedProvider=null,Jt.error=null,Jt.purchaseCurrency=e5,Jt.paymentCurrency=NH,Jt.purchaseCurrencies=[e5],Jt.paymentCurrencies=[],Jt.paymentAmount=void 0,Jt.purchaseAmount=void 0,Jt.quotesLoading=!1}},t5=vr(BHe)});function kHe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let u=0;u>>0,w=new Uint8Array(y);for(;p!==h;){let T=u[p],E=0;for(let S=y-1;(T!==0||E>>0,w[S]=T%r>>>0,T=T/r>>>0;if(T!==0)throw new Error("Non-zero carry");f=E,p++}let x=y-f;for(;x!==y&&w[x]===0;)x++;let v=n.repeat(d);for(;x>>0,y=new Uint8Array(h);for(;d255)return;let E=t[T];if(E===255)return;let S=0;for(let _=h-1;(E!==0||S>>0,y[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");p=S,d++}let w=h-p;for(;w!==h&&y[w]===0;)w++;let x=new Uint8Array(f+(h-w)),v=f;for(;w!==h;)x[v++]=y[w++];return x}function c(u){let d=a(u);if(d)return d;throw new Error("Non-base"+r+" character")}return{encode:i,decodeUnsafe:a,decode:c}}var mpe,gpe=b(()=>{l();mpe=kHe});var UHe,wm,RH=b(()=>{l();gpe();UHe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",wm=mpe(UHe)});var DHe,LHe,MHe,Yrr,HHe,Jrr,C_=b(()=>{l();$c();cw();rI();DHe=Ht(ks(),1),LHe="wc",MHe="universal_provider",Yrr=`${LHe}@2:${MHe}:`,HHe="https://rpc.walletconnect.org/v1/",Jrr=`${HHe}bundler`});var ype,wpe=b(()=>{l();ype={convertEVMChainIdToCoinType(e){if(e>=2147483648)throw new Error("Invalid chainId");return(2147483648|e)>>>0}}});var wc,$He,bm,OH=b(()=>{l();Lr();Hn();wpe();ma();gs();lp();$r();ai();To();gc();wc=rt({suggestions:[],loading:!1}),$He={state:wc,subscribe(e){return Dt(wc,()=>e(wc))},subscribeKey(e,t){return Tt(wc,e,t)},async resolveName(e){try{return await ze.lookupEnsName(e)}catch(t){let r=t;throw new Error(r?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await ze.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{wc.loading=!0,wc.suggestions=[];let t=await ze.getEnsNameSuggestions(e);return wc.suggestions=t.suggestions||[],wc.suggestions}catch(t){let r=bm.parseEnsApiError(t,"Error fetching name suggestions");throw new Error(r)}finally{wc.loading=!1}},async getNamesForAddress(e){try{if(!$.state.activeCaipNetwork)return[];let r=de.getEnsFromCacheForAddress(e);if(r)return r;let n=await ze.reverseLookupEnsName({address:e});return de.updateEnsCache({address:e,ens:n,timestamp:Date.now()}),n}catch(t){let r=bm.parseEnsApiError(t,"Error fetching names for address");throw new Error(r)}},async registerName(e){let t=$.state.activeCaipNetwork,r=$.getAccountData(t?.chainNamespace)?.address,n=re.getAuthConnector();if(!t)throw new Error("Network not found");if(!r||!n)throw new Error("Address or auth connector not found");wc.loading=!0;try{let o=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});J.pushTransactionStack({onCancel(){J.replace("RegisterAccountName")}});let s=await ee.signMessage(o);wc.loading=!1;let i=t.id;if(!i)throw new Error("Network not found");let a=ype.convertEVMChainIdToCoinType(Number(i));await ze.registerEnsName({coinType:a,address:r,signature:s,message:o}),$.setAccountProp("profileName",e,t.chainNamespace),de.updateEnsCache({address:r,ens:[{name:e,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),J.replace("RegisterAccountNameSuccess")}catch(o){let s=bm.parseEnsApiError(o,`Error registering name ${e}`);throw J.replace("RegisterAccountName"),new Error(s)}finally{wc.loading=!1}},validateName(e){return/^[a-zA-Z0-9-]{4,}$/u.test(e)},parseEnsApiError(e,t){return e?.reasons?.[0]?.description||t}},bm=vr($He)});function S_(e){try{return new URL(e)}catch{return null}}function FHe(e){let t=e.split("/"),r=t.length>0&&t[0]!==void 0?t[0]:"",n=r.lastIndexOf(":");return n===-1?{host:r}:{host:r.slice(0,n),port:r.slice(n+1)}}function zHe(e){let t=e.indexOf("://");if(t===-1)return null;let r=e.slice(0,t),n=t+3,o=e.indexOf("/",n);o===-1&&(o=e.length);let s=e.slice(n,o),i=s.lastIndexOf(":");return i===-1?{scheme:r,host:s}:{scheme:r,host:s.slice(0,i),port:s.slice(i+1)}}function bpe(e,t){if(t.includes("://")){let i=S_(t);return i?i.origin===e:!1}let{host:r,port:n}=FHe(t),o=e.indexOf("://");if(o!==-1){let i=o+3,a=e.indexOf("/",i);a===-1&&(a=e.length);let c=e.slice(i,a);if(n!==void 0)return`${r}:${n}`===c;let u=c.split(":")[0];return r===u}let s=S_(e);return s?n!==void 0?r===s.hostname&&n===(s.port||void 0):r===s.hostname:!1}function xpe(e,t,r){let n=r,o,s=n.indexOf("://");s!==-1&&(o=n.slice(0,s),n=n.slice(s+3));let i=n.indexOf("/");i!==-1&&(n=n.slice(0,i));let a=n,c,u=a.lastIndexOf(":");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let d=a.split(".");for(let w of d)if(w.includes("*")&&w!=="*")return!1;let f=e.protocol.replace(/:$/u,"");if(o&&o!==f||c!==void 0&&c!=="*"&&c!==e.port)return!1;let p=zHe(t),y=(p?p.host:e.hostname).split(".");if(d.length!==y.length)return!1;for(let w=d.length-1;w>=0;w-=1){let x=d[w],v=y[w];if(x!=="*"&&x!==v)return!1}return!0}var vpe=b(()=>{l()});var VHe,cl,I_=b(()=>{l();ut();OH();vpe();VHe={ton:["ton_sendMessage","ton_signData"],solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},cl={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(e){return VHe[e]||[]},createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};let r={...e},n=new Set;if(t.methods&&Object.keys(t.methods).forEach(o=>n.add(o)),t.chains&&Object.keys(t.chains).forEach(o=>n.add(o)),t.events&&Object.keys(t.events).forEach(o=>n.add(o)),t.rpcMap&&Object.keys(t.rpcMap).forEach(o=>{let[s]=o.split(":");s&&n.add(s)}),n.forEach(o=>{r[o]||(r[o]=this.createDefaultNamespace(o))}),t.methods&&Object.entries(t.methods).forEach(([o,s])=>{r[o]&&(r[o].methods=s)}),t.chains&&Object.entries(t.chains).forEach(([o,s])=>{r[o]&&(r[o].chains=s)}),t.events&&Object.entries(t.events).forEach(([o,s])=>{r[o]&&(r[o].events=s)}),t.rpcMap){let o=new Set;Object.entries(t.rpcMap).forEach(([s,i])=>{let[a,c]=s.split(":");!a||!c||!r[a]||(r[a].rpcMap||(r[a].rpcMap={}),o.has(a)||(r[a].rpcMap={},o.add(a)),r[a].rpcMap[c]=i)})}return r},createNamespaces(e,t){let r=e.reduce((n,o)=>{let{id:s,chainNamespace:i,rpcUrls:a}=o,c=a.default.http[0];n[i]||(n[i]=this.createDefaultNamespace(i));let u=`${i}:${s}`,d=n[i];switch(d.chains.push(u),u){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":d.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":d.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break;default:}return d?.rpcMap&&c&&(d.rpcMap[s]=c),n},{});return this.applyNamespaceOverrides(r,t)},resolveReownName:async e=>{let t=await bm.resolveName(e);return(t?.addresses?Object.values(t.addresses):[])[0]?.address||!1},getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{let r=t.chains||[],n=t.accounts.map(o=>{let[s,i]=o.split(":");return`${s}:${i}`});return Array.from(new Set([...r,...n]))})},isSessionEventData(e){return typeof e=="object"&&e!==null&&"id"in e&&"topic"in e&&"params"in e&&typeof e.params=="object"&&e.params!==null&&"chainId"in e.params&&"event"in e.params&&typeof e.params.event=="object"&&e.params.event!==null},isUserRejectedRequestError(e){try{if(typeof e=="object"&&e!==null){let t=e,r=typeof t.code=="number",n=r&&t.code===cl.RPC_ERROR_CODE.USER_REJECTED_METHODS,o=r&&t.code===cl.RPC_ERROR_CODE.USER_REJECTED;return n||o}return!1}catch{return!1}},isOriginAllowed(e,t,r){let n=[...t,...r];if(t.length===0)return!0;let o=S_(e);if(!o)return n.some(s=>!s.includes("*")&&s===e);if(o.hostname==="localhost"||o.hostname==="127.0.0.1")return!0;for(let s of n)if(s.includes("*")){if(xpe(o,e,s))return!0}else if(bpe(e,s))return!0;return!1},listenWcProvider({universalProvider:e,namespace:t,onConnect:r,onDisconnect:n,onAccountsChanged:o,onChainChanged:s,onDisplayUri:i}){r&&e.on("connect",()=>{let a=cl.getWalletConnectAccounts(e,t);r(a)}),n&&e.on("disconnect",()=>{n()}),o&&e.on("accountsChanged",a=>{try{let c=e.session?.namespaces?.[t]?.accounts||[],u=e.rpcProviders?.[t]?.getDefaultChain(),d=a.map(f=>{let p=c.find(w=>w.includes(`${t}:${u}:${f}`));if(!p)return;let{chainId:h,chainNamespace:y}=lt.parseCaipAddress(p);return{address:f,chainId:h,chainNamespace:y}}).filter(f=>f!==void 0);d.length>0&&o(d)}catch(c){console.warn("Failed to parse accounts for namespace on accountsChanged event",t,a,c)}}),s&&e.on("chainChanged",a=>{s(a)}),i&&e.on("display_uri",a=>{i(a)})},getWalletConnectAccounts(e,t){let r=new Set,n=e?.session?.namespaces?.[t]?.accounts?.map(o=>lt.parseCaipAddress(o)).filter(({address:o})=>r.has(o.toLowerCase())?!1:(r.add(o.toLowerCase()),!0));return n&&n.length>0?n:[]}}});var jHe,r5,Epe=b(()=>{l();C_();ut();yc();$n();I_();$r();To();E_();jHe=[Z.CONNECTOR_ID.AUTH,Z.CONNECTOR_ID.WALLET_CONNECT],r5=class{constructor(t){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=r=>$.getCaipNetworks(r),this.getConnectorId=r=>re.getConnectorId(r),t&&this.construct(t)}construct(t){this.projectId=t.projectId,this.namespace=t.namespace,this.adapterType=t.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:t,chainId:r}){let n=this.getCaipNetworks().filter(o=>o.chainNamespace===this.namespace).find(o=>o.id.toString()===r?.toString());t&&n&&this.addConnection({connectorId:Z.CONNECTOR_ID.AUTH,accounts:t,caipNetwork:n})}setAuthProvider(t){t.onConnect(this.onAuthConnected.bind(this)),t.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:Z.CONNECTOR_ID.AUTH,type:"AUTH",name:Z.CONNECTOR_NAMES.AUTH,provider:t,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...t){let r=new Set;this.availableConnectors=[...t,...this.availableConnectors].filter(n=>r.has(n.id)?!1:(r.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...t){let r=new Set;this.availableConnections=[...t,...this.availableConnections].filter(n=>r.has(n.connectorId.toLowerCase())?!1:(r.add(n.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(t){this.availableConnections=this.availableConnections.filter(r=>r.connectorId.toLowerCase()!==t.toLowerCase()),this.emit("connections",this.availableConnections)}clearConnections(t=!1){this.availableConnections=[],t&&this.emit("connections",this.availableConnections)}setStatus(t,r){$.setAccountProp("status",t,r)}on(t,r){this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t)?.add(r)}off(t,r){let n=this.eventListeners.get(t);n&&n.delete(r)}removeAllEventListeners(){this.eventListeners.forEach(t=>{t.clear()})}emit(t,r){let n=this.eventListeners.get(t);n&&n.forEach(o=>o(r))}async connectWalletConnect(t){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(r){throw cl.isUserRejectedRequestError(r)?new Z1(r):r}}async switchNetwork(t){let{caipNetwork:r}=t,n=ar.getProviderId(r.chainNamespace),o=ar.getProvider(r.chainNamespace);if(!o)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){o.setDefaultChain(r.caipNetworkId);return}if(n==="AUTH"){let s=re.getAuthConnector()?.provider;if(!s)throw new Error("Auth provider not found");let i=Fr(r.chainNamespace);await s.switchNetwork({chainId:r.caipNetworkId});let a=await s.getUser({chainId:r.caipNetworkId,preferredAccountType:i});this.emit("switchNetwork",a)}}getWalletConnectConnector(){let t=this.connectors.find(r=>r.id==="walletConnect");if(!t)throw new Error("WalletConnectConnector not found");return t}onConnect(t,r){if(t.length>0){let{address:n,chainId:o}=se.getAccount(t[0]),s=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===o?.toString()),i=this.connectors.find(a=>a.id===r);n&&(this.emit("accountChanged",{address:n,chainId:o,connector:i}),this.addConnection({connectorId:r,accounts:t.map(a=>{let{address:c}=se.getAccount(a);return{address:c}}),caipNetwork:s}))}}onAccountsChanged(t,r,n=!0){if(t.length>0){let{address:o}=se.getAccount(t[0]),s=this.getConnection({connectorId:r,connections:this.connections,connectors:this.connectors});o&&this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===r.toLowerCase()&&this.emit("accountChanged",{address:o,chainId:s?.caipNetwork?.id,connector:s?.connector}),this.addConnection({connectorId:r,accounts:t.map(i=>{let{address:a}=se.getAccount(i);return{address:a}}),caipNetwork:s?.caipNetwork})}else n&&this.onDisconnect(r)}onDisconnect(t){this.removeProviderListeners(t),this.deleteConnection(t),this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===t.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(t,r){let n=typeof t=="string"&&t.startsWith("0x")?parseInt(t,16).toString():t.toString(),o=this.getConnection({connectorId:r,connections:this.connections,connectors:this.connectors}),s=this.getCaipNetworks().filter(i=>i.chainNamespace===this.namespace).find(i=>i.id.toString()===n);o&&this.addConnection({connectorId:r,accounts:o.accounts,caipNetwork:s}),this.getConnectorId(Z.CHAIN.EVM)?.toLowerCase()===r.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(t,r){if(jHe.includes(t))return;let n=i=>this.onAccountsChanged(i,t),o=i=>this.onChainChanged(i,t),s=()=>this.onDisconnect(t);this.providerHandlers[t]||(r.on("disconnect",s),r.on("accountsChanged",n),r.on("chainChanged",o),this.providerHandlers[t]={provider:r,disconnect:s,accountsChanged:n,chainChanged:o})}removeProviderListeners(t){if(this.providerHandlers[t]){let{provider:r,disconnect:n,accountsChanged:o,chainChanged:s}=this.providerHandlers[t];r.removeListener("disconnect",n),r.removeListener("accountsChanged",o),r.removeListener("chainChanged",s),this.providerHandlers[t]=null}}emitFirstAvailableConnection(){let t=this.getConnection({connections:this.connections,connectors:this.connectors});if(t){let[r]=t.accounts;this.emit("accountChanged",{address:r?.address,chainId:t.caipNetwork?.id,connector:t.connector})}}getConnection({address:t,connectorId:r,connections:n,connectors:o}){if(r){let i=n.find(u=>u.connectorId.toLowerCase()===r.toLowerCase());if(!i)return null;let a=o.find(u=>u.id.toLowerCase()===i.connectorId.toLowerCase()),c=t?i.accounts.find(u=>u.address.toLowerCase()===t.toLowerCase()):i.accounts[0];return{...i,account:c,connector:a}}let s=n.find(i=>i.accounts.length>0&&o.some(a=>a.id.toLowerCase()===i.connectorId.toLowerCase()));if(s){let[i]=s.accounts,a=o.find(c=>c.id.toLowerCase()===s.connectorId.toLowerCase());return{...s,account:i,connector:a}}return null}}});var ay,_o,T_=b(()=>{l();C_();ut();mm();$r();ai();To();mc();up();Un();gc();hm();yc();$n();ay=null,_o={getSIWX(){return Y.state.siwx},async initializeIfEnabled(e=$.getActiveCaipAddress()){let t=Y.state.siwx;if(!(t&&e))return;let[r,n,o]=e.split(":");if($.checkIfSupportedNetwork(r,`${r}:${n}`))try{if(Y.state.remoteFeatures?.emailCapture){let i=$.getAccountData(r)?.user;await De.open({view:"DataCapture",data:{email:i?.email??void 0}});return}if(ay&&await ay,(await t.getSessions(`${r}:${n}`,o)).length)return;await De.open({view:"SIWXSignMessage"})}catch(s){console.error("SIWXUtil:initializeIfEnabled",s),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(s)}),await ee._getClient()?.disconnect().catch(console.error),J.reset("Connect"),Je.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(e=$.getActiveCaipAddress()){if(!Y.state.siwx||!e)return!0;let{chainNamespace:r,chainId:n,address:o}=lt.parseCaipAddress(e),s=`${r}:${n}`;return(await _o.getSessions({address:o,caipNetworkId:s})).length>0},async requestSignMessage(){let e=Y.state.siwx,t=se.getPlainAddress($.getActiveCaipAddress()),r=oy();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!r)throw new Error("No ActiveCaipNetwork or client found");try{let n=await e.createMessage({chainId:r.caipNetworkId,accountAddress:t}),o=n.toString(),s="";e.signMessage?s=await e.signMessage({message:o,chainId:r.caipNetworkId,accountAddress:t}):(re.getConnectorId(r.chainNamespace)===Z.CONNECTOR_ID.AUTH&&J.pushTransactionStack({}),s=await ee.signMessage(o)||""),await e.addSession({data:n,message:o,signature:s}),$.setLastConnectedSIWECaipNetwork(r),De.close(),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(n){(!De.state.open||J.state.view==="ApproveTransaction")&&await De.open({view:"SIWXSignMessage"}),Je.showError("Error signing message"),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(n)}),console.error("SWIXUtil:requestSignMessage",n)}},async cancelSignMessage(){try{let e=this.getSIWX();if(e?.getRequired?.()){let r=$.getLastConnectedSIWECaipNetwork();if(r){let n=await e?.getSessions(r?.caipNetworkId,se.getPlainAddress($.getActiveCaipAddress())||"");n&&n.length>0?await $.switchActiveNetwork(r):await ee.disconnect()}else await ee.disconnect()}else De.close();De.close(),Ae.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){let e=this.getSIWX(),t=$.getAllRequestedCaipNetworks(),r=[];return await Promise.all(t.map(async n=>{let o=await e?.getSessions(n.caipNetworkId,se.getPlainAddress($.getActiveCaipAddress())||"");o&&r.push(...o)})),r},async getSessions(e){let t=Y.state.siwx,r=e?.address;if(!r){let o=$.getActiveCaipAddress();r=se.getPlainAddress(o)}let n=e?.caipNetworkId;return n||(n=$.getActiveCaipNetwork()?.caipNetworkId),t&&r&&n?t.getSessions(n,r):[]},async isSIWXCloseDisabled(){let e=this.getSIWX();if(e){let t=J.state.view==="ApproveTransaction",r=J.state.view==="SIWXSignMessage";if(t||r)return e.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:e,chainId:t,socialUri:r,preferredAccountType:n,chainNamespace:o}){let s=_o.getSIWX(),i=oy();if(!s||!o.includes(Z.CHAIN.EVM)||Y.state.remoteFeatures?.emailCapture){let f=await e.connect({chainId:t,socialUri:r,preferredAccountType:n});return{address:f.address,chainId:f.chainId,accounts:f.accounts}}let a=`${o}:${t}`,c=await s.createMessage({chainId:a,accountAddress:"<>"}),u={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await e.connect({chainId:t,socialUri:r,siwxMessage:u,preferredAccountType:n});return u.accountAddress=d.address,u.serializedMessage=d.message||"",d.signature&&d.message&&await _o.addEmbeddedWalletSession(u,d.message,d.signature),$.setLastConnectedSIWECaipNetwork(i),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(e,t,r){if(ay)return ay;let n=_o.getSIWX();return n?(ay=n.addSession({data:e,message:t,signature:r}).finally(()=>{ay=null}),ay):Promise.resolve()},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:r}){let n=_o.getSIWX(),o=oy(),s=new Set(t.map(u=>u.split(":")[0]));if(!n||s.size!==1||!s.has("eip155"))return!1;let i=await n.createMessage({chainId:oy()?.caipNetworkId||"",accountAddress:""}),a=await e.authenticate({nonce:i.nonce,domain:i.domain,uri:i.uri,exp:i.expirationTime,iat:i.issuedAt,nbf:i.notBefore,requestId:i.requestId,version:i.version,resources:i.resources,statement:i.statement,chainId:i.chainId,methods:r,chains:[i.chainId,...t.filter(u=>u!==i.chainId)]});Je.showLoading("Authenticating...",{autoClose:!1});let c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if($.setAccountProp("connectedWalletInfo",c,Array.from(s)[0]),a?.auths?.length){let u=a.auths.map(d=>{let f=e.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud??"",version:d.p.version||i.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:f,signature:d.s.s,cacao:d}});try{await n.setSessions(u),o&&$.setLastConnectedSIWECaipNetwork(o),Ae.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:_o.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),Ae.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:_o.getSIWXEventProperties(d)}),await e.disconnect().catch(console.error),d}finally{Je.hide()}}return!0},getSIWXEventProperties(e){let t=$.state.activeChain;if(!t)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:$.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Fr(t)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT,message:e?se.parseError(e):void 0}},async clearSessions(){let e=this.getSIWX();e&&await e.setSessions([])}}});var n5,qHe,Ape=b(()=>{l();C_();ut();T_();I_();$r();Un();n5=class{constructor({provider:t,namespace:r}){this.id=Z.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=$.getCaipNetworks.bind($),this.caipNetworks=this.getCaipNetworks(),this.provider=t,this.chain=r}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){let r=this.getCaipNetworks(),n=Y.state.universalProviderConfigOverride,o=cl.createNamespaces(r,n);await this.provider.connect({optionalNamespaces:o})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){let t=this.chains.map(r=>r.caipNetworkId);return _o.universalProviderAuthenticate({universalProvider:this.provider,chains:t,methods:qHe})}},qHe=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"]});var pp,Cpe=b(()=>{l();ut();pp={getGasPriceInEther(e,t){let r=t*e;return Number(r)/1e18},getGasPriceInUSD(e,t,r){let n=pp.getGasPriceInEther(t,r);return ht.bigNumber(e).times(n).toNumber()},getPriceImpact({sourceTokenAmount:e,sourceTokenPriceInUSD:t,toTokenPriceInUSD:r,toTokenAmount:n}){let o=ht.bigNumber(e).times(t),s=ht.bigNumber(n).times(r);return o.minus(s).div(o).times(100).toNumber()},getMaxSlippage(e,t){let r=ht.bigNumber(e).div(100);return ht.multiply(t,r).toNumber()},getProviderFee(e,t=.0085){return ht.bigNumber(e).times(t).toString()},isInsufficientNetworkTokenForGas(e,t){let r=t||"0";return ht.bigNumber(e).eq(0)?!0:ht.bigNumber(ht.bigNumber(r)).gt(e)},isInsufficientSourceTokenForSwap(e,t,r){let n=r?.find(s=>s.address===t)?.quantity?.numeric;return ht.bigNumber(n||"0").lt(e)}}});var ll,WHe,sn,BH=b(()=>{l();Lr();Hn();ut();gs();Un();ll=rt({message:"",variant:"info",open:!1}),WHe={state:ll,subscribeKey(e,t){return Tt(ll,e,t)},open(e,t){let{debug:r}=Y.state,{code:n,displayMessage:o,debugMessage:s}=e;if(o&&r&&(ll.message=o,ll.variant=t,ll.open=!0),s){if(!Z.IS_DEVELOPMENT)return;let i=typeof s=="function"?s():s,a=n?{code:n}:void 0;t==="error"?console.error(i,a):t==="warning"?console.warn(i,a):console.info(i,a)}},warn(e,t,r){ll.open=!0,ll.message=e,ll.variant="warning",t&&console.warn(t,r)},close(){ll.open=!1,ll.message="",ll.variant="info"}},sn=vr(WHe)});var Spe,KHe,bs,Q,__,ot,Ipe=b(()=>{l();Lr();Hn();ut();ut();mm();L6();yc();ha();$n();TH();Cpe();gs();BH();lp();$r();ai();To();mc();gc();hm();Spe=15e4,KHe=6,bs={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,switchingTokens:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:Ye.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},Q=rt({...bs}),__={state:Q,subscribe(e){return Dt(Q,()=>e(Q))},subscribeKey(e,t){return Tt(Q,e,t)},getParams(){let e=$.state.activeChain,t=$.getAccountData(e)?.caipAddress??$.state.activeCaipAddress,r=se.getPlainAddress(t),n=U6(),o=re.getConnectorId($.state.activeChain);if(!r)throw new Error("No address found to swap the tokens from.");let s=!Q.toToken?.address||!Q.toToken?.decimals,i=!Q.sourceToken?.address||!Q.sourceToken?.decimals||!ht.bigNumber(Q.sourceTokenAmount).gt(0),a=!Q.sourceTokenAmount;return{networkAddress:n,fromAddress:r,fromCaipAddress:t,sourceTokenAddress:Q.sourceToken?.address,toTokenAddress:Q.toToken?.address,toTokenAmount:Q.toTokenAmount,toTokenDecimals:Q.toToken?.decimals,sourceTokenAmount:Q.sourceTokenAmount,sourceTokenDecimals:Q.sourceToken?.decimals,invalidToToken:s,invalidSourceToken:i,invalidSourceTokenAmount:a,availableToSwap:t&&!s&&!i&&!a,isAuthConnector:o===Z.CONNECTOR_ID.AUTH}},async setSourceToken(e){if(!e){Q.sourceToken=e,Q.sourceTokenAmount="",Q.sourceTokenPriceInUSD=0;return}Q.sourceToken=e,await ot.setTokenPrice(e.address,"sourceToken")},setSourceTokenAmount(e){Q.sourceTokenAmount=e},async setToToken(e){if(!e){Q.toToken=e,Q.toTokenAmount="",Q.toTokenPriceInUSD=0;return}Q.toToken=e,await ot.setTokenPrice(e.address,"toToken")},setToTokenAmount(e){Q.toTokenAmount=e?ht.toFixed(e,KHe):""},async setTokenPrice(e,t){let r=Q.tokensPriceMap[e]||0;r||(Q.loadingPrices=!0,r=await ot.getAddressPrice(e)),t==="sourceToken"?Q.sourceTokenPriceInUSD=r:t==="toToken"&&(Q.toTokenPriceInUSD=r),Q.loadingPrices&&(Q.loadingPrices=!1),ot.getParams().availableToSwap&&!Q.switchingTokens&&ot.swapTokens()},async switchTokens(){if(!(Q.initializing||!Q.initialized||Q.switchingTokens)){Q.switchingTokens=!0;try{let e=Q.toToken?{...Q.toToken}:void 0,t=Q.sourceToken?{...Q.sourceToken}:void 0,r=e&&Q.toTokenAmount===""?"1":Q.toTokenAmount;ot.setSourceTokenAmount(r),ot.setToTokenAmount(""),await ot.setSourceToken(e),await ot.setToToken(t),Q.switchingTokens=!1,ot.swapTokens()}catch(e){throw Q.switchingTokens=!1,e}}},resetState(){Q.myTokensWithBalance=bs.myTokensWithBalance,Q.tokensPriceMap=bs.tokensPriceMap,Q.initialized=bs.initialized,Q.initializing=bs.initializing,Q.switchingTokens=bs.switchingTokens,Q.sourceToken=bs.sourceToken,Q.sourceTokenAmount=bs.sourceTokenAmount,Q.sourceTokenPriceInUSD=bs.sourceTokenPriceInUSD,Q.toToken=bs.toToken,Q.toTokenAmount=bs.toTokenAmount,Q.toTokenPriceInUSD=bs.toTokenPriceInUSD,Q.networkPrice=bs.networkPrice,Q.networkTokenSymbol=bs.networkTokenSymbol,Q.networkBalanceInUSD=bs.networkBalanceInUSD,Q.inputError=bs.inputError},resetValues(){let{networkAddress:e}=ot.getParams(),t=Q.tokens?.find(r=>r.address===e);ot.setSourceToken(t),ot.setToToken(void 0)},getApprovalLoadingState(){return Q.loadingApprovalTransaction},clearError(){Q.transactionError=void 0},async initializeState(){if(!Q.initializing){if(Q.initializing=!0,!Q.initialized)try{await ot.fetchTokens(),Q.initialized=!0}catch{Q.initialized=!1,Je.showError("Failed to initialize swap"),J.goBack()}Q.initializing=!1}},async fetchTokens(){let{networkAddress:e}=ot.getParams();await ot.getNetworkTokenPrice(),await ot.getMyTokensWithBalance();let t=Q.myTokensWithBalance?.find(r=>r.address===e);t&&(Q.networkTokenSymbol=t.symbol,ot.setSourceToken(t),ot.setSourceTokenAmount("0"))},async getTokenList(){let e=$.state.activeCaipNetwork?.caipNetworkId;if(!(Q.caipNetworkId===e&&Q.tokens))try{Q.tokensLoading=!0;let t=await ym.getTokenList(e);Q.tokens=t,Q.caipNetworkId=e,Q.popularTokens=t.sort((i,a)=>i.symbola.symbol?1:0);let n=(e&&Ye.SUGGESTED_TOKENS_BY_CHAIN?.[e]||[]).map(i=>t.find(a=>a.symbol===i)).filter(i=>!!i),s=(Ye.SWAP_SUGGESTED_TOKENS||[]).map(i=>t.find(a=>a.symbol===i)).filter(i=>!!i).filter(i=>!n.some(a=>a.address===i.address));Q.suggestedTokens=[...n,...s]}catch{Q.tokens=[],Q.popularTokens=[],Q.suggestedTokens=[]}finally{Q.tokensLoading=!1}},async getAddressPrice(e){let t=Q.tokensPriceMap[e];if(t)return t;let n=(await ze.fetchTokenPrice({addresses:[e]}))?.fungibles||[],s=[...Q.tokens||[],...Q.myTokensWithBalance||[]]?.find(c=>c.address===e)?.symbol,i=n.find(c=>c.symbol.toLowerCase()===s?.toLowerCase())?.price||0,a=parseFloat(i.toString());return Q.tokensPriceMap[e]=a,a},async getNetworkTokenPrice(){let{networkAddress:e}=ot.getParams(),r=(await ze.fetchTokenPrice({addresses:[e]}).catch(()=>(Je.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],n=r?.price.toString()||"0";Q.tokensPriceMap[e]=parseFloat(n),Q.networkTokenSymbol=r?.symbol||"",Q.networkPrice=n},async getMyTokensWithBalance(e){let t=await al.getMyTokensWithBalance({forceUpdate:e,caipNetwork:$.state.activeCaipNetwork,address:$.getAccountData()?.address}),r=ym.mapBalancesToSwapTokens(t);r&&(await ot.getInitialGasPrice(),ot.setBalances(r))},setBalances(e){let{networkAddress:t}=ot.getParams(),r=$.state.activeCaipNetwork;if(!r)return;let n=e.find(o=>o.address===t);e.forEach(o=>{Q.tokensPriceMap[o.address]=o.price||0}),Q.myTokensWithBalance=e.filter(o=>o.address.startsWith(r.caipNetworkId)),Q.networkBalanceInUSD=n?ht.multiply(n.quantity.numeric,n.price).toString():"0"},async getInitialGasPrice(){let e=await ym.fetchGasPrice();if(!e)return{gasPrice:null,gasPriceInUSD:null};switch($.state?.activeCaipNetwork?.chainNamespace){case Z.CHAIN.SOLANA:return Q.gasFee=e.standard??"0",Q.gasPriceInUSD=ht.multiply(e.standard,Q.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(Q.gasFee),gasPriceInUSD:Number(Q.gasPriceInUSD)};case Z.CHAIN.EVM:default:let t=e.standard??"0",r=BigInt(t),n=BigInt(Spe),o=pp.getGasPriceInUSD(Q.networkPrice,n,r);return Q.gasFee=t,Q.gasPriceInUSD=o,{gasPrice:r,gasPriceInUSD:o}}},async swapTokens(){let e=$.getAccountData()?.address,t=Q.sourceToken,r=Q.toToken,n=ht.bigNumber(Q.sourceTokenAmount).gt(0);if(n||ot.setToTokenAmount(""),!r||!t||Q.loadingPrices||!n||!e)return;Q.loadingQuote=!0;let o=ht.bigNumber(Q.sourceTokenAmount).times(10**t.decimals).round(0).toFixed(0);try{let s=await ze.fetchSwapQuote({userAddress:e,from:t.address,to:r.address,gasPrice:Q.gasFee,amount:o.toString()});Q.loadingQuote=!1;let i=s?.quotes?.[0]?.toAmount;if(!i){sn.open({displayMessage:"Incorrect amount",debugMessage:"Please enter a valid amount"},"error");return}let a=ht.bigNumber(i).div(10**r.decimals).toString();ot.setToTokenAmount(a),ot.hasInsufficientToken(Q.sourceTokenAmount,t.address)?Q.inputError="Insufficient balance":(Q.inputError=void 0,ot.setTransactionDetails())}catch(s){let i=await ym.handleSwapError(s);Q.loadingQuote=!1,Q.inputError=i||"Insufficient balance"}},async getTransaction(){let{fromCaipAddress:e,availableToSwap:t}=ot.getParams(),r=Q.sourceToken,n=Q.toToken;if(!(!e||!t||!r||!n||Q.loadingQuote))try{Q.loadingBuildTransaction=!0;let o=await ym.fetchSwapAllowance({userAddress:e,tokenAddress:r.address,sourceTokenAmount:Q.sourceTokenAmount,sourceTokenDecimals:r.decimals}),s;return o?s=await ot.createSwapTransaction():s=await ot.createAllowanceTransaction(),Q.loadingBuildTransaction=!1,Q.fetchError=!1,s}catch{J.goBack(),Je.showError("Failed to check allowance"),Q.loadingBuildTransaction=!1,Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}},async createAllowanceTransaction(){let{fromCaipAddress:e,sourceTokenAddress:t,toTokenAddress:r}=ot.getParams();if(!(!e||!r)){if(!t)throw new Error("createAllowanceTransaction - No source token address found.");try{let n=await ze.generateApproveCalldata({from:t,to:r,userAddress:e}),o=se.getPlainAddress(n.tx.from);if(!o)throw new Error("SwapController:createAllowanceTransaction - address is required");let s={data:n.tx.data,to:o,gasPrice:BigInt(n.tx.eip155.gasPrice),value:BigInt(n.tx.value),toAmount:Q.toTokenAmount};return Q.swapTransaction=void 0,Q.approvalTransaction={data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount},{data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount}}catch{J.goBack(),Je.showError("Failed to create approval transaction"),Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}}},async createSwapTransaction(){let{networkAddress:e,fromCaipAddress:t,sourceTokenAmount:r}=ot.getParams(),n=Q.sourceToken,o=Q.toToken;if(!t||!r||!n||!o)return;let s=ee.parseUnits(r,n.decimals)?.toString();try{let i=await ze.generateSwapCalldata({userAddress:t,from:n.address,to:o.address,amount:s,disableEstimate:!0}),a=n.address===e,c=BigInt(i.tx.eip155.gas),u=BigInt(i.tx.eip155.gasPrice),d=se.getPlainAddress(i.tx.to);if(!d)throw new Error("SwapController:createSwapTransaction - address is required");let f={data:i.tx.data,to:d,gas:c,gasPrice:u,value:BigInt(a?s??"0":"0"),toAmount:Q.toTokenAmount};return Q.gasPriceInUSD=pp.getGasPriceInUSD(Q.networkPrice,c,u),Q.approvalTransaction=void 0,Q.swapTransaction=f,f}catch{J.goBack(),Je.showError("Failed to create transaction"),Q.approvalTransaction=void 0,Q.swapTransaction=void 0,Q.fetchError=!0;return}},onEmbeddedWalletApprovalSuccess(){Je.showLoading("Approve limit increase in your wallet"),J.replace("SwapPreview")},async sendTransactionForApproval(e){let{fromAddress:t,isAuthConnector:r}=ot.getParams();Q.loadingApprovalTransaction=!0,r?J.pushTransactionStack({onSuccess:ot.onEmbeddedWalletApprovalSuccess}):Je.showLoading("Approve limit increase in your wallet");try{await ee.sendTransaction({address:t,to:e.to,data:e.data,value:e.value,chainNamespace:Z.CHAIN.EVM}),await ot.swapTokens(),await ot.getTransaction(),Q.approvalTransaction=void 0,Q.loadingApprovalTransaction=!1}catch(o){let s=o;Q.transactionError=s?.displayMessage,Q.loadingApprovalTransaction=!1,Je.showError(s?.displayMessage||"Transaction error"),Ae.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.displayMessage||s?.message||"Unknown",network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(e){if(!e)return;let{fromAddress:t,toTokenAmount:r,isAuthConnector:n}=ot.getParams();Q.loadingTransaction=!0;let o=`Swapping ${Q.sourceToken?.symbol} to ${ht.formatNumberToLocalString(r,3)} ${Q.toToken?.symbol}`,s=`Swapped ${Q.sourceToken?.symbol} to ${ht.formatNumberToLocalString(r,3)} ${Q.toToken?.symbol}`;n?J.pushTransactionStack({onSuccess(){J.replace("Account"),Je.showLoading(o),__.resetState()}}):Je.showLoading("Confirm transaction in your wallet");try{let i=[Q.sourceToken?.address,Q.toToken?.address].join(","),a=await ee.sendTransaction({address:t,to:e.to,data:e.data,value:e.value,chainNamespace:Z.CHAIN.EVM});return Q.loadingTransaction=!1,Je.showSuccess(s),Ae.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}}),__.resetState(),n||J.replace("Account"),__.getMyTokensWithBalance(i),a}catch(i){let a=i;Q.transactionError=a?.displayMessage,Q.loadingTransaction=!1,Je.showError(a?.displayMessage||"Transaction error"),Ae.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:a?.displayMessage||a?.message||"Unknown",network:$.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:ot.state.sourceToken?.symbol||"",swapToToken:ot.state.toToken?.symbol||"",swapFromAmount:ot.state.sourceTokenAmount||"",swapToAmount:ot.state.toTokenAmount||"",isSmartAccount:Fr(Z.CHAIN.EVM)===Kr.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(e,t){return pp.isInsufficientSourceTokenForSwap(e,t,Q.myTokensWithBalance)},setTransactionDetails(){let{toTokenAddress:e,toTokenDecimals:t}=ot.getParams();!e||!t||(Q.gasPriceInUSD=pp.getGasPriceInUSD(Q.networkPrice,BigInt(Q.gasFee),BigInt(Spe)),Q.priceImpact=pp.getPriceImpact({sourceTokenAmount:Q.sourceTokenAmount,sourceTokenPriceInUSD:Q.sourceTokenPriceInUSD,toTokenPriceInUSD:Q.toTokenPriceInUSD,toTokenAmount:Q.toTokenAmount}),Q.maxSlippage=pp.getMaxSlippage(Q.slippage,Q.toTokenAmount),Q.providerFee=pp.getProviderFee(Q.sourceTokenAmount))}},ot=vr(__)});var ul,ZHe,ci,Tpe=b(()=>{l();Lr();Hn();gs();ul=rt({message:"",open:!1,triggerRect:{width:0,height:0,top:0,left:0},variant:"shade"}),ZHe={state:ul,subscribe(e){return Dt(ul,()=>e(ul))},subscribeKey(e,t){return Tt(ul,e,t)},showTooltip({message:e,triggerRect:t,variant:r}){ul.open=!0,ul.message=e,ul.triggerRect=t,ul.variant=r},hide(){ul.open=!1,ul.message="",ul.triggerRect={width:0,height:0,top:0,left:0}}},ci=vr(ZHe)});var kH,UH,_pe=b(()=>{l();kH={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},UH={network:"eip155:84532",asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}}});var o5,Ppe=b(()=>{l();ai();up();gc();T_();o5={isUnsupportedChainView(){return J.state.view==="UnsupportedChain"||J.state.view==="SwitchNetwork"&&J.state.history.includes("UnsupportedChain")},async safeClose(){if(this.isUnsupportedChainView()){De.shake();return}if(await _o.isSIWXCloseDisabled()){De.shake();return}(J.state.view==="DataCapture"||J.state.view==="DataCaptureOtpConfirm")&&ee.disconnect(),De.close()}}});var ct=b(()=>{l();up();gc();$r();E_();hpe();IH();Epe();Ape();ai();AH();To();hm();Cu();y_();vH();Un();lp();Q3();mc();Ipe();_H();Tpe();OH();BH();yH();ha();bH();$n();w_();ma();T_();Ppe();gs();_pe();O6();yc();I_()});var Ope,GHe,YHe,Npe,P_,JHe,QHe,XHe,N_,R_,O_,B_,k_,U_,D_,L_,M_,H_,e$e,t$e,Rpe,$_,F_,DH=b(()=>{l();tS();Ope=Ht(ks()),GHe=Object.defineProperty,YHe=(e,t,r)=>t in e?GHe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Npe=(e,t,r)=>YHe(e,typeof t!="symbol"?t+"":t,r),P_=class extends yo{constructor(t){super(),this.opts=t,Npe(this,"protocol","wc"),Npe(this,"version",2)}},JHe=Object.defineProperty,QHe=(e,t,r)=>t in e?JHe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,XHe=(e,t,r)=>QHe(e,typeof t!="symbol"?t+"":t,r),N_=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r,XHe(this,"records",new Map)}},R_=class{constructor(t,r){this.logger=t,this.core=r}},O_=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},B_=class extends yo{constructor(t){super()}},k_=class{constructor(t,r,n,o){this.core=t,this.logger=r,this.name=n}},U_=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},D_=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r}},L_=class{constructor(t,r,n){this.core=t,this.logger=r,this.store=n}},M_=class{constructor(t,r){this.projectId=t,this.logger=r}},H_=class{constructor(t,r,n){this.core=t,this.logger=r,this.telemetryEnabled=n}},e$e=Object.defineProperty,t$e=(e,t,r)=>t in e?e$e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Rpe=(e,t,r)=>t$e(e,typeof t!="symbol"?t+"":t,r),$_=class{constructor(t){this.opts=t,Rpe(this,"protocol","wc"),Rpe(this,"version",2)}},F_=class{constructor(t){this.client=t}}});var Bpe=b(()=>{l()});var kpe,Upe=b(()=>{l();kpe="0.1.1"});function Dpe(){return kpe}var Lpe=b(()=>{l();Upe()});function Mpe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?Mpe(e.cause,t):t?null:e}var zt,xm=b(()=>{l();Lpe();zt=class e extends Error{constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=`https://oxlib.sh${o??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0]:[]].filter(c=>typeof c=="string").join(` +`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Dpe()}`}),this.cause=r.cause,this.details=n,this.docs=i,this.docsPath=o,this.shortMessage=t}walk(t){return Mpe(this,t)}}});var ly,Hpe=b(()=>{l();ly=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function n$e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function uy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Su(e,...t){if(!n$e(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function $pe(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");uy(e.outputLen),uy(e.blockLen)}function hp(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function z_(e,t){Su(e);let r=t.outputLen;if(e.length>>t}function s$e(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function i$e(e){for(let t=0;te().update(dy(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Vpe(e=32){if(ly&&typeof ly.getRandomValues=="function")return ly.getRandomValues(new Uint8Array(e));if(ly&&typeof ly.randomBytes=="function")return Uint8Array.from(ly.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var o$e,LH,vm,fy=b(()=>{l();Hpe();o$e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;LH=o$e?e=>e:i$e;vm=class{}});function c$e(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function jpe(e,t,r){return e&t^~e&r}function qpe(e,t,r){return e&t^e&r^t&r}var q_,mp,Wpe=b(()=>{l();fy();q_=class extends vm{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=V_(this.buffer)}update(t){hp(this),t=dy(t),Su(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>Kpe&W_)}:{h:Number(e>>Kpe&W_)|0,l:Number(e&W_)|0}}function Zpe(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s{l();W_=BigInt(4294967295),Kpe=BigInt(32);Gpe=(e,t,r)=>e<>>32-r,Ype=(e,t,r)=>t<>>32-r,Jpe=(e,t,r)=>t<>>64-r,Qpe=(e,t,r)=>e<>>64-r});function y$e(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=ehe(u,d,1)^r[a],p=the(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=nhe[i],c=ehe(o,s,a),u=the(o,s,a),d=rhe[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=m$e[n],e[1]^=g$e[n]}Iu(r)}var u$e,s5,d$e,f$e,p$e,h$e,rhe,nhe,ohe,she,m$e,g$e,ehe,the,MH,w$e,ihe,ahe=b(()=>{l();Xpe();fy();u$e=BigInt(0),s5=BigInt(1),d$e=BigInt(2),f$e=BigInt(7),p$e=BigInt(256),h$e=BigInt(113),rhe=[],nhe=[],ohe=[];for(let e=0,t=s5,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],rhe.push(2*(5*n+r)),nhe.push((e+1)*(e+2)/2%64);let o=u$e;for(let s=0;s<7;s++)t=(t<>f$e)*h$e)%p$e,t&d$e&&(o^=s5<<(s5<r>32?Jpe(e,t,r):Gpe(e,t,r),the=(e,t,r)=>r>32?Qpe(e,t,r):Ype(e,t,r);MH=class e extends vm{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,uy(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return uy(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(z_(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Iu(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},w$e=(e,t,r)=>j_(()=>new MH(t,e,r)),ihe=w$e(1,136,256/8)});var b$e,Em,HH,che,lhe=b(()=>{l();Wpe();fy();b$e=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Em=new Uint32Array(64),HH=class extends q_{constructor(t=32){super(64,t,8,!1),this.A=mp[0]|0,this.B=mp[1]|0,this.C=mp[2]|0,this.D=mp[3]|0,this.E=mp[4]|0,this.F=mp[5]|0,this.G=mp[6]|0,this.H=mp[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,r){for(let f=0;f<16;f++,r+=4)Em[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=Em[f-15],h=Em[f-2],y=dl(p,7)^dl(p,18)^p>>>3,w=dl(h,17)^dl(h,19)^h>>>10;Em[f]=w+Em[f-7]+y+Em[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=dl(a,6)^dl(a,11)^dl(a,25),h=d+p+jpe(a,c,u)+b$e[f]+Em[f]|0,w=(dl(n,2)^dl(n,13)^dl(n,22))+qpe(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){Iu(Em)}destroy(){this.set(0,0,0,0,0,0,0,0),Iu(this.buffer)}},che=j_(()=>new HH)});function M6(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function jH(e){if(!M6(e))throw new Error("Uint8Array expected")}function H6(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function i5(e){let t=e.toString(16);return t.length&1?"0"+t:t}function fhe(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?VH:BigInt("0x"+e)}function $6(e){if(jH(e),phe)return e.toHex();let t="";for(let r=0;r=gp._0&&e<=gp._9)return e-gp._0;if(e>=gp.A&&e<=gp.F)return e-(gp.A-10);if(e>=gp.a&&e<=gp.f)return e-(gp.a-10)}function a5(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(phe)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oVH;e>>=zH,t+=1);return t}function mhe(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=FH(e),o=FH(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=FH(0))=>{o=a(dhe([0]),f),n=a(),f.length!==0&&(o=a(dhe([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}function gy(e,t,r={}){let n=(o,s,i)=>{let a=v$e[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function KH(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var VH,zH,phe,x$e,gp,$H,my,FH,dhe,v$e,Z_=b(()=>{l();VH=BigInt(0),zH=BigInt(1);phe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",x$e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));gp={_0:48,_9:57,A:65,F:70,a:97,f:102};$H=e=>typeof e=="bigint"&&VH<=e;my=e=>(zH<new Uint8Array(e),dhe=e=>Uint8Array.from(e);v$e={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||M6(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function ghe(e,t){if(ZH(e)>t)throw new G_({givenSize:ZH(e),maxSize:t})}function GH(e){if(e>=wp.zero&&e<=wp.nine)return e-wp.zero;if(e>=wp.A&&e<=wp.F)return e-(wp.A-10);if(e>=wp.a&&e<=wp.f)return e-(wp.a-10)}function yhe(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new Y_({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;s{l();Am();wp={zero:48,nine:57,A:65,F:70,a:97,f:102}});function l5(e,t){if(Fi(e)>t)throw new J_({givenSize:Fi(e),maxSize:t})}function bhe(e,t){if(typeof t=="number"&&t>0&&t>Fi(e)-1)throw new u5({offset:t,position:"start",size:Fi(e)})}function xhe(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Fi(e)!==r-t)throw new u5({offset:r,position:"end",size:Fi(e)})}function YH(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new Q_({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function vhe(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;s{l();bp()});function Sm(e,t,r){return JSON.stringify(e,(n,o)=>typeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+A$e:o,r)}var A$e,F6=b(()=>{l();A$e="#__bigint"});function I$e(e,t={}){let{strict:r=!1}=t;if(!e)throw new X_(e);if(typeof e!="string")throw new X_(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new e7(e);if(!e.startsWith("0x"))throw new e7(e)}function wy(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Tu(e){return e instanceof Uint8Array?li(e):Array.isArray(e)?li(new Uint8Array(e)):e}function Ahe(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(l5(r,t.size),f5(r,t.size)):r}function li(e,t={}){let r="";for(let o=0;os||o{l();xm();JH();F6();C$e=new TextEncoder,S$e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));QH=class extends zt{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number \`${s}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},X_=class extends zt{constructor(t){super(`Value \`${typeof t=="object"?Sm(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}},e7=class extends zt{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}},J_=class extends zt{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}},u5=class extends zt{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}},Q_=class extends zt{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function _$e(e){if(!(e instanceof Uint8Array)){if(!e)throw new z6(e);if(typeof e!="object")throw new z6(e);if(!("BYTES_PER_ELEMENT"in e))throw new z6(e);if(e.BYTES_PER_ELEMENT!==1||e.constructor.name!=="Uint8Array")throw new z6(e)}}function V6(e){return e instanceof Uint8Array?e:typeof e=="string"?h5(e):P$e(e)}function P$e(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function h5(e,t={}){let{size:r}=t,n=e;r&&(l5(e,r),n=p5(e,r));let o=n.slice(2);o.length%2&&(o=`0${o}`);let s=o.length/2,i=new Uint8Array(s);for(let a=0,c=0;a{l();xm();bp();whe();JH();F6();T$e=new TextEncoder;z6=class extends zt{constructor(t){super(`Value \`${typeof t=="object"?Sm(t):t}\` of type \`${typeof t}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}},G_=class extends zt{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},Y_=class extends zt{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}});function t$(e,t={}){let{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=ihe(V6(e));return r==="Bytes"?n:li(n)}var r$=b(()=>{l();ahe();Am();bp()});var t7,_he=b(()=>{l();t7=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});var R$e,r7,n$=b(()=>{l();_he();R$e={checksum:new t7(8192)},r7=R$e.checksum});function Nhe(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new n7({prefix:n,cause:new i$});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new n7({prefix:n,cause:new s$});return}throw new o$({publicKey:e})}function c$(e){let t=(()=>{if(e$(e))return Rhe(e);if(Ihe(e))return O$e(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return Nhe(t),t}function O$e(e){return Rhe(li(e))}function Rhe(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new a$({publicKey:e});if(e.length===130){let n=BigInt(fl(e,0,32)),o=BigInt(fl(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(fl(e,0,1)),o=BigInt(fl(e,1,33)),s=BigInt(fl(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(fl(e,0,1)),r=BigInt(fl(e,1,33));return{prefix:t,x:r}}function Ohe(e,t={}){return h5(m5(e,t))}function m5(e,t={}){Nhe(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return wy(s?ui(r,{size:1}):"0x",ui(n,{size:32}),typeof o=="bigint"?ui(o,{size:32}):"0x")}var o$,n7,s$,i$,a$,o7=b(()=>{l();Am();xm();bp();F6();o$=class extends zt{constructor({publicKey:t}){super(`Value \`${Sm(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},n7=class extends zt{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},s$=class extends zt{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},i$=class extends zt{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},a$=class extends zt{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Fi(Tu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}});function j6(e,t={}){let{strict:r=!0}=t;if(!B$e.test(e))throw new s7({address:e,cause:new u$});if(r){if(e.toLowerCase()===e)return;if(Bhe(e)!==e)throw new s7({address:e,cause:new d$})}}function Bhe(e){if(r7.has(e))return r7.get(e);j6(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=t$(She(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return r7.set(e,o),o}function k$e(e,t={}){let{checksum:r=!1}=t;return j6(e),r?Bhe(e):e}function khe(e,t={}){let r=t$(`0x${m5(e).slice(4)}`).substring(26);return k$e(`0x${r}`,t)}function Uhe(e,t){return j6(e,{strict:!1}),j6(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}var B$e,s7,u$,d$,i7=b(()=>{l();Am();n$();xm();r$();o7();B$e=/^0x[a-fA-F0-9]{40}$/;s7=class extends zt{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},u$=class extends zt{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},d$=class extends zt{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}});var Dhe=b(()=>{l()});var Lhe,Mhe,Hhe,Hir,$ir,Fir,zir,Vir,jir,qir,Wir,Kir,Zir,Gir,Yir,Jir,Qir,Xir,ear,tar,rar,nar,oar,sar,iar,aar,car,lar,uar,dar,far,par,har,mar,gar,yar,war,bar,xar,Ear,Aar,Car,Sar,Iar,Tar,_ar,Par,Nar,Rar,Oar,Bar,kar,Uar,Dar,Lar,Mar,Har,$ar,Far,zar,Var,jar,qar,War,Kar,Zar,Gar,Yar,Jar,Qar,Xar,ecr,tcr,rcr,ncr,ocr,scr,icr,acr,ccr,lcr,ucr,dcr,fcr,pcr,hcr,mcr,gcr,ycr,wcr,bcr,xcr,vcr,Ecr,Acr,Ccr,Scr,Icr,p$,a7=b(()=>{l();Lhe=/^(.*)\[([0-9]*)\]$/,Mhe=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Hhe=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Hir=2n**(8n-1n)-1n,$ir=2n**(16n-1n)-1n,Fir=2n**(24n-1n)-1n,zir=2n**(32n-1n)-1n,Vir=2n**(40n-1n)-1n,jir=2n**(48n-1n)-1n,qir=2n**(56n-1n)-1n,Wir=2n**(64n-1n)-1n,Kir=2n**(72n-1n)-1n,Zir=2n**(80n-1n)-1n,Gir=2n**(88n-1n)-1n,Yir=2n**(96n-1n)-1n,Jir=2n**(104n-1n)-1n,Qir=2n**(112n-1n)-1n,Xir=2n**(120n-1n)-1n,ear=2n**(128n-1n)-1n,tar=2n**(136n-1n)-1n,rar=2n**(144n-1n)-1n,nar=2n**(152n-1n)-1n,oar=2n**(160n-1n)-1n,sar=2n**(168n-1n)-1n,iar=2n**(176n-1n)-1n,aar=2n**(184n-1n)-1n,car=2n**(192n-1n)-1n,lar=2n**(200n-1n)-1n,uar=2n**(208n-1n)-1n,dar=2n**(216n-1n)-1n,far=2n**(224n-1n)-1n,par=2n**(232n-1n)-1n,har=2n**(240n-1n)-1n,mar=2n**(248n-1n)-1n,gar=2n**(256n-1n)-1n,yar=-(2n**(8n-1n)),war=-(2n**(16n-1n)),bar=-(2n**(24n-1n)),xar=-(2n**(32n-1n)),Ear=-(2n**(40n-1n)),Aar=-(2n**(48n-1n)),Car=-(2n**(56n-1n)),Sar=-(2n**(64n-1n)),Iar=-(2n**(72n-1n)),Tar=-(2n**(80n-1n)),_ar=-(2n**(88n-1n)),Par=-(2n**(96n-1n)),Nar=-(2n**(104n-1n)),Rar=-(2n**(112n-1n)),Oar=-(2n**(120n-1n)),Bar=-(2n**(128n-1n)),kar=-(2n**(136n-1n)),Uar=-(2n**(144n-1n)),Dar=-(2n**(152n-1n)),Lar=-(2n**(160n-1n)),Mar=-(2n**(168n-1n)),Har=-(2n**(176n-1n)),$ar=-(2n**(184n-1n)),Far=-(2n**(192n-1n)),zar=-(2n**(200n-1n)),Var=-(2n**(208n-1n)),jar=-(2n**(216n-1n)),qar=-(2n**(224n-1n)),War=-(2n**(232n-1n)),Kar=-(2n**(240n-1n)),Zar=-(2n**(248n-1n)),Gar=-(2n**(256n-1n)),Yar=2n**8n-1n,Jar=2n**16n-1n,Qar=2n**24n-1n,Xar=2n**32n-1n,ecr=2n**40n-1n,tcr=2n**48n-1n,rcr=2n**56n-1n,ncr=2n**64n-1n,ocr=2n**72n-1n,scr=2n**80n-1n,icr=2n**88n-1n,acr=2n**96n-1n,ccr=2n**104n-1n,lcr=2n**112n-1n,ucr=2n**120n-1n,dcr=2n**128n-1n,fcr=2n**136n-1n,pcr=2n**144n-1n,hcr=2n**152n-1n,mcr=2n**160n-1n,gcr=2n**168n-1n,ycr=2n**176n-1n,wcr=2n**184n-1n,bcr=2n**192n-1n,xcr=2n**200n-1n,vcr=2n**208n-1n,Ecr=2n**216n-1n,Acr=2n**224n-1n,Ccr=2n**232n-1n,Scr=2n**240n-1n,Icr=2n**248n-1n,p$=2n**256n-1n});function m$(e,t){if(e.length!==t.length)throw new y$({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n{l();i7();xm();bp();a7();(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return j6(c),f5(c.toLowerCase(),o?32:0)}if(r==="string")return Che(n);if(r==="bytes")return n;if(r==="bool")return f5(Ahe(n),o?32:1);let s=r.match(Hhe);if(s){let[c,u,d="256"]=s,f=Number.parseInt(d,10)/8;return ui(n,{size:o?32:f,signed:u==="int"})}let i=r.match(Mhe);if(i){let[c,u]=i;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new g$({expectedSize:Number.parseInt(u,10),value:n});return p5(n,o?32:0)}let a=r.match(Lhe);if(a&&Array.isArray(n)){let[c,u]=a,d=[];for(let f=0;f{l()});var zhe=b(()=>{l()});var Vhe=b(()=>{l()});var jhe=b(()=>{l()});var qhe=b(()=>{l()});var Whe=b(()=>{l()});var Khe=b(()=>{l()});var Zhe=b(()=>{l()});var c7,b$,Ghe=b(()=>{l();fy();c7=class extends vm{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,$pe(t);let n=dy(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew c7(e,t).update(r).digest();b$.create=(e,t)=>new c7(e,t)});function xs(e,t){let r=e%t;return r>=di?r:t+r}function Ra(e,t,r){let n=e;for(;t-- >di;)n*=n,n%=r;return n}function l7(e,t){if(e===di)throw new Error("invert: expected non-zero number");if(t<=di)throw new Error("invert: expected positive modulus, got "+t);let r=xs(e,t),n=t,o=di,s=vs,i=vs,a=di;for(;r!==di;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==vs)throw new Error("invert: does not exist");return xs(o,t)}function e0e(e,t){let r=(e.ORDER+vs)/Jhe,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function q$e(e,t){let r=(e.ORDER-Qhe)/Xhe,n=e.mul(t,by),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,by),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function W$e(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return e0e;let s=o.pow(n,t),i=(t+vs)/by;return function(c,u){if(c.is0(u))return u;if(Yhe(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=vs<(n[o]="function",n),t);return gy(e,r)}function G$e(e,t,r){if(rdi;)r&vs&&(n=e.mul(n,o)),o=e.sqr(o),r>>=vs;return n}function v$(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function Yhe(e,t){let r=(e.ORDER-vs)/by,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function E$(e,t){t!==void 0&&uy(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function g5(e,t,r=!1,n={}){if(e<=di)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=E$(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:my(o),ZERO:di,ONE:vs,create:c=>xs(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return di<=c&&cc===di,isOdd:c=>(c&vs)===vs,neg:c=>xs(-c,e),eql:(c,u)=>c===u,sqr:c=>xs(c*c,e),add:(c,u)=>xs(c+u,e),sub:(c,u)=>xs(c-u,e),mul:(c,u)=>xs(c*u,e),pow:(c,u)=>G$e(a,c,u),div:(c,u)=>xs(c*l7(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>l7(c,e),sqrt:n.sqrt||(c=>(i||(i=K$e(e)),i(a,c))),toBytes:c=>r?WH(c,s):py(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?qH(c):yp(c)},invertBatch:c=>v$(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function t0e(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function A$(e){let t=t0e(e);return t+Math.ceil(t/2)}function r0e(e,t,r=!1){let n=e.length,o=t0e(t),s=A$(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?qH(e):yp(e),a=xs(i,t-vs)+vs;return r?WH(a,o):py(a,o)}var di,vs,by,j$e,Jhe,Qhe,Xhe,Z$e,u7=b(()=>{l();fy();Z_();di=BigInt(0),vs=BigInt(1),by=BigInt(2),j$e=BigInt(3),Jhe=BigInt(4),Qhe=BigInt(5),Xhe=BigInt(8);Z$e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function C$(e,t){let r=t.negate();return e?r:t}function s0e(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function S$(e,t){s0e(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=my(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function o0e(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=_$);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function Y$e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function J$e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function T$(e){return i0e.get(e)||1}function a0e(e,t){return{constTimeNegate:C$,hasPrecomputes(r){return T$(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>n0e;)n&_$&&(o=o.add(s)),s=s.double(),n>>=_$;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=S$(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=my(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{l();u7();Z_();n0e=BigInt(0),_$=BigInt(1);I$=new WeakMap,i0e=new WeakMap});function u0e(e){e.lowS!==void 0&&H6("lowS",e.lowS),e.prehash!==void 0&&H6("prehash",e.prehash)}function Q$e(e){let t=P$(e);gy(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function N$(e,t){return $6(py(e,t))}function eFe(e){let t=Q$e(e),{Fp:r}=t,n=g5(t.n,t.nBitLength),o=t.toBytes||((E,S,_)=>{let O=S.toAffine();return c5(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,R$),X$e),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return K_(E,Po,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(M6(E)&&(E=$6(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:yp($i("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=xs(M,D)),hy("private key",M,Po,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=KH((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=KH(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=v$(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s($i("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return c0e(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,R$),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,R$),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;hy("scalar",S,vp,O);let D=w.ZERO;if(S===vp)return D;if(this.is0()||S===Po)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>vp||P>vp;)N&Po&&(R=R.add(B)),P&Po&&(I=I.add(B)),B=B.double(),N>>=Po,P>>=Po;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;hy("scalar",S,Po,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===vp||P===Po||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===Po)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===Po?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return H6("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return H6("isCompressed",S),$6(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=a0e(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function tFe(e){let t=P$(e);return gy(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function d0e(e){let t=tFe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return xs(C,n)}function u(C){return l7(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=eFe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=c5;return H6("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=yp(H);if(!K_(k,Po,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&Po)===Po;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>Po;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>yp(C.slice(A,U));class v{constructor(A,U,H){hy("r",A,Po,n),hy("s",U,Po,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=$i("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=xp.toSig($i("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D($i("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+N$(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return a5(this.toDERHex())}toDERHex(){return xp.hexFromSig(this)}toCompactRawBytes(){return a5(this.toCompactHex())}toCompactHex(){let A=o;return N$(this.r,A)+N$(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=A$(t.n);return r0e(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=$i("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=yp(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=my(s);function N(C){return hy("num < 2^"+s,C,vp,M),py(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=$i("msgHash",C),u0e(U),j&&(C=$i("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push($i("extraEntropy",ye))}let pe=c5(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===vp)return;let ur=c(Et*c(me+At*te));if(ur===vp)return;let _r=(kt.x===At?0:2)|Number(kt.y&Po),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return mhe(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=$i("msgHash",A),U=$i("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(u0e(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||M6(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof xp.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}var O$,xp,vp,Po,Jcr,R$,X$e,f0e=b(()=>{l();l0e();u7();Z_();O$=class extends Error{constructor(t=""){super(t)}},xp={Err:O$,_tlv:{encode:(e,t)=>{let{Err:r}=xp;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=i5(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?i5(o.length/2|128):"";return i5(e)+s+o+t},decode(e,t){let{Err:r}=xp,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=xp;if(eb$(e,t,zpe(...r)),randomBytes:Vpe}}function p0e(e,t){let r=n=>d0e({...e,...rFe(n)});return{...r(t),create:r}}var h0e=b(()=>{l();Ghe();fy();f0e();});function sFe(e){let t=y0e,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=Ra(d,r,t)*d%t,p=Ra(f,r,t)*d%t,h=Ra(p,B$,t)*u%t,y=Ra(h,o,t)*h%t,w=Ra(y,s,t)*y%t,x=Ra(w,a,t)*w%t,v=Ra(x,c,t)*x%t,T=Ra(v,a,t)*w%t,E=Ra(T,r,t)*d%t,S=Ra(E,i,t)*y%t,_=Ra(S,n,t)*u%t,O=Ra(_,B$,t);if(!k$.eql(k$.sqr(O),e))throw new Error("Cannot find square root");return O}var y0e,m0e,nFe,oFe,B$,g0e,k$,Oa,U$=b(()=>{l();lhe();h0e();u7();y0e=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),m0e=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),nFe=BigInt(0),oFe=BigInt(1),B$=BigInt(2),g0e=(e,t)=>(e+t/B$)/t;k$=g5(y0e,void 0,void 0,{sqrt:sFe}),Oa=p0e({a:nFe,b:BigInt(7),Fp:k$,n:m0e,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=m0e,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-oFe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=g0e(s*e,t),c=g0e(-n*e,t),u=xs(e-a*r-c*o,t),d=xs(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},che)});var y7={};Te(y7,{InvalidRError:()=>f7,InvalidSError:()=>p7,InvalidSerializedSizeError:()=>d7,InvalidVError:()=>h7,InvalidYParityError:()=>xy,MissingPropertiesError:()=>q6,assert:()=>m7,extract:()=>iFe,from:()=>L$,fromBytes:()=>w0e,fromDerBytes:()=>aFe,fromDerHex:()=>b0e,fromHex:()=>D$,fromLegacy:()=>x0e,fromRpc:()=>v0e,fromTuple:()=>cFe,toBytes:()=>lFe,toDerBytes:()=>uFe,toDerHex:()=>dFe,toHex:()=>E0e,toLegacy:()=>fFe,toRpc:()=>pFe,toTuple:()=>hFe,vToYParity:()=>g7,validate:()=>mFe,yParityToV:()=>M$});function m7(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new q6({signature:e});if(typeof e.s>"u")throw new q6({signature:e});if(r&&typeof e.yParity>"u")throw new q6({signature:e});if(e.r<0n||e.r>p$)throw new f7({value:e.r});if(e.s<0n||e.s>p$)throw new p7({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new xy({value:e.yParity})}function w0e(e){return D$(li(e))}function D$(e){if(e.length!==130&&e.length!==132)throw new d7({signature:e});let t=BigInt(fl(e,0,32)),r=BigInt(fl(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return g7(o)}catch{throw new xy({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function iFe(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return L$(e)}function L$(e){let t=typeof e=="string"?D$(e):e instanceof Uint8Array?w0e(e):typeof e.r=="string"?v0e(e):e.v?x0e(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return m7(t),t}function aFe(e){return b0e(li(e))}function b0e(e){let{r:t,s:r}=Oa.Signature.fromDER(Tu(e).slice(2));return{r:t,s:r}}function x0e(e){return{r:e.r,s:e.s,yParity:g7(e.v)}}function v0e(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=g7(r)),typeof n!="number")throw new xy({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function cFe(e){let[t,r,n]=e;return L$({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function lFe(e){return h5(E0e(e))}function E0e(e){m7(e);let t=e.r,r=e.s;return wy(ui(t,{size:32}),ui(r,{size:32}),typeof e.yParity=="number"?ui(M$(e.yParity),{size:1}):"0x")}function uFe(e){return new Oa.Signature(e.r,e.s).toDERRawBytes()}function dFe(e){return`0x${new Oa.Signature(e.r,e.s).toDERHex()}`}function fFe(e){return{r:e.r,s:e.s,v:M$(e.yParity)}}function pFe(e){let{r:t,s:r,yParity:n}=e;return{r:ui(t,{size:32}),s:ui(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function hFe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":XH(ui(t)),r===0n?"0x":XH(ui(r))]}function mFe(e,t={}){try{return m7(e,t),!0}catch{return!1}}function g7(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new h7({value:e})}function M$(e){if(e===0)return 27;if(e===1)return 28;throw new xy({value:e})}var d7,q6,f7,p7,xy,h7,A0e=b(()=>{l();U$();Am();xm();bp();F6();a7();d7=class extends zt{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Fi(Tu(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},q6=class extends zt{constructor({signature:t}){super(`Signature \`${Sm(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},f7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},p7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},xy=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},h7=class extends zt{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}});var C0e=b(()=>{l()});var S0e=b(()=>{l()});var hlr,mlr,I0e=b(()=>{l();hlr=Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[t,e.charCodeAt(0)])),mlr={...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63}});var T0e=b(()=>{l()});var _0e=b(()=>{l()});var P0e,vFe,N0e,EFe,blr,R0e=b(()=>{l();P0e=6,vFe=32,N0e=4096,EFe=vFe*N0e,blr=EFe*P0e-1-1*N0e*P0e});var O0e=b(()=>{l()});var B0e=b(()=>{l()});var k0e=b(()=>{l()});var U0e=b(()=>{l()});var D0e=b(()=>{l()});var L0e=b(()=>{l()});var M0e=b(()=>{l()});var H0e=b(()=>{l()});var $0e=b(()=>{l()});var F0e=b(()=>{l();pZ()});var z0e=b(()=>{l()});var V0e=b(()=>{l()});var j0e,q0e=b(()=>{l();j0e=!1});var w7={};Te(w7,{createKeyPair:()=>LFe,getPublicKey:()=>W0e,getSharedSecret:()=>MFe,noble:()=>DFe,randomPrivateKey:()=>K0e,recoverAddress:()=>Z0e,recoverPublicKey:()=>G0e,sign:()=>HFe,verify:()=>$Fe});function LFe(e={}){let{as:t="Hex"}=e,r=K0e({as:t}),n=W0e({privateKey:r});return{privateKey:r,publicKey:n}}function W0e(e){let{privateKey:t}=e,r=Oa.ProjectivePoint.fromPrivateKey(Tu(t).slice(2));return c$(r)}function MFe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,i=Oa.ProjectivePoint.fromHex(m5(n).slice(2)).multiply(Oa.utils.normPrivateKeyToScalar(Tu(r).slice(2))).toRawBytes(!0);return t==="Hex"?li(i):i}function K0e(e={}){let{as:t="Hex"}=e,r=Oa.utils.randomPrivateKey();return t==="Hex"?li(r):r}function Z0e(e){return khe(G0e(e))}function G0e(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new Oa.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Tu(t).substring(2));return c$(a)}function HFe(e){let{extraEntropy:t=j0e,hash:r,payload:n,privateKey:o}=e,{r:s,s:i,recovery:a}=Oa.sign(V6(n),V6(o),{extraEntropy:typeof t=="boolean"?t:Tu(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function $Fe(e){let{address:t,hash:r,payload:n,publicKey:o,signature:s}=e;return t?Uhe(t,Z0e({payload:n,signature:s})):Oa.verify(s,V6(n),Ohe(o),...r?[{prehash:!0,lowS:!0}]:[])}var DFe,Y0e=b(()=>{l();U$();i7();Am();bp();q0e();o7();DFe=Oa});var J0e=b(()=>{l()});var Q0e=b(()=>{l()});var X0e=b(()=>{l()});var eme=b(()=>{l();kZ()});var tme=b(()=>{l()});var rme=b(()=>{l()});var zi,H$,$$,F$,z$,V$,j$,q$,W$,K$,Z$,G$,Y$,nme=b(()=>{l();zi=class extends Error{constructor(t){let{cause:r,code:n,message:o,data:s,stack:i}=t;super(o,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.BaseError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=r,this.code=n,this.data=s,this.stack=i??""}},H$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Missing or invalid parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidInputError"})}};Object.defineProperty(H$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});$$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not found."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceNotFoundError"})}};Object.defineProperty($$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});F$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Requested resource not available."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ResourceUnavailableError"})}};Object.defineProperty(F$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});z$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Transaction creation failed."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.TransactionRejectedError"})}};Object.defineProperty(z$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});V$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method is not implemented."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotSupportedError"})}};Object.defineProperty(V$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});j$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Rate limit exceeded."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.LimitExceededError"})}};Object.defineProperty(j$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});q$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"JSON-RPC version not supported."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.VersionNotSupportedError"})}};Object.defineProperty(q$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});W$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Input is not a valid JSON-RPC request."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidRequestError"})}};Object.defineProperty(W$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});K$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Method does not exist."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.MethodNotFoundError"})}};Object.defineProperty(K$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});Z$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Invalid method parameters."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InvalidParamsError"})}};Object.defineProperty(Z$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});G$=class e extends zi{constructor(t={}){super({cause:t.cause,code:e.code,data:t.data,message:t.message??"Internal JSON-RPC error.",stack:t.stack}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.InternalError"})}};Object.defineProperty(G$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Y$=class e extends zi{constructor(t={}){super({code:e.code,data:t.data,message:t.message??"Failed to parse JSON-RPC response."}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RpcResponse.ParseError"})}};Object.defineProperty(Y$,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700})});var fi,J$,Q$,X$,eF,tF,rF,nF,oF,sF,iF,aF,cF,lF,ome=b(()=>{l();MZ();fi=class extends Error{constructor(t,r){super(r),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ProviderRpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t,this.details=r}},J$=class extends fi{constructor({message:t="The user rejected the request."}={}){super(4001,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UserRejectedRequestError"})}};Object.defineProperty(J$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});Q$=class extends fi{constructor({message:t="The requested method and/or account has not been authorized by the user."}={}){super(4100,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnauthorizedError"})}};Object.defineProperty(Q$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});X$=class extends fi{constructor({message:t="The provider does not support the requested method."}={}){super(4200,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedMethodError"})}};Object.defineProperty(X$,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});eF=class extends fi{constructor({message:t="The provider is disconnected from all chains."}={}){super(4900,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DisconnectedError"})}};Object.defineProperty(eF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});tF=class extends fi{constructor({message:t="The provider is not connected to the requested chain."}={}){super(4901,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.ChainDisconnectedError"})}};Object.defineProperty(tF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});rF=class extends fi{constructor({message:t="An error occurred when attempting to switch chain."}={}){super(4902,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.SwitchChainError"})}};Object.defineProperty(rF,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});nF=class extends fi{constructor({message:t="This Wallet does not support a capability that was not marked as optional."}={}){super(5700,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedNonOptionalCapabilityError"})}};Object.defineProperty(nF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});oF=class extends fi{constructor({message:t="This Wallet does not support the requested chain ID."}={}){super(5710,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnsupportedChainIdError"})}};Object.defineProperty(oF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});sF=class extends fi{constructor({message:t="There is already a bundle submitted with this ID."}={}){super(5720,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.DuplicateIdError"})}};Object.defineProperty(sF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});iF=class extends fi{constructor({message:t="This bundle id is unknown / has not been submitted."}={}){super(5730,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.UnknownBundleIdError"})}};Object.defineProperty(iF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});aF=class extends fi{constructor({message:t="The call bundle is too large for the Wallet to process."}={}){super(5740,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.BundleTooLargeError"})}};Object.defineProperty(aF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});cF=class extends fi{constructor({message:t="The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."}={}){super(5750,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicReadyWalletRejectedUpgradeError"})}};Object.defineProperty(cF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});lF=class extends fi{constructor({message:t="The wallet does not support atomic execution but the request requires it."}={}){super(5760,t),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Provider.AtomicityNotSupportedError"})}};Object.defineProperty(lF,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760})});var sme=b(()=>{l()});var ime=b(()=>{l()});var ame=b(()=>{l()});var cme=b(()=>{l()});var lme=b(()=>{l()});var ume=b(()=>{l()});var dme=b(()=>{l()});var fme=b(()=>{l()});var pme=b(()=>{l()});var hme=b(()=>{l()});var mme=b(()=>{l()});var gme=b(()=>{l()});var yme=b(()=>{l()});var wme=b(()=>{l()});var bme=b(()=>{l()});var xme=b(()=>{l()});var pur,vme=b(()=>{l();pur=Uint8Array.from([105,171,180,181,160,222,75,198,42,42,32,31,141,37,186,233])});var Eme=b(()=>{l()});var Ame=b(()=>{l()});var Cme=b(()=>{l();Bpe();Fhe();zhe();Vhe();jhe();Dhe();$he();qhe();Whe();i7();Khe();C0e();S0e();I0e();T0e();R0e();k0e();U0e();D0e();L0e();M0e();Am();n$();H0e();$0e();F0e();xm();z0e();V0e();r$();J0e();bp();F6();Q0e();_0e();X0e();eme();tme();rme();ome();o7();Zhe();sme();nme();ime();ame();Y0e();A0e();cme();a7();lme();O0e();dme();fme();pme();hme();mme();gme();yme();wme();bme();xme();ume();vme();Eme();B0e();Ame()});function Sme(e){let t=e.length,r=0,n=0;for(;n=55296&&o<=56319&&n>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}function yze(e,t,r){mze.encodeInto(e,t.subarray(r))}function Ime(e,t,r){e.length>gze?yze(e,t,r):hze(e,t,r)}function uF(e,t,r){let n=t,o=n+r,s=[],i="";for(;n65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=wze&&(i+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(i+=String.fromCharCode(...s)),i}function vze(e,t,r){let n=e.subarray(t,t+r);return bze.decode(n)}function Tme(e,t,r){return r>xze?vze(e,t,r):uF(e,t,r)}var mze,gze,wze,bze,xze,b7=b(()=>{l();mze=new TextEncoder,gze=50;wze=4096;bze=new TextDecoder,xze=200});var vy,_me=b(()=>{l();vy=class{constructor(t,r){this.type=t,this.data=r}}});var Vi,dF=b(()=>{l();Vi=class e extends Error{constructor(t){super(t);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}}});function Pme(e,t,r){let n=r/4294967296,o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function x7(e,t,r){let n=Math.floor(r/4294967296),o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function v7(e,t){let r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function Nme(e,t){let r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}var E7=b(()=>{l()});function Sze({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=Cze)if(t===0&&e<=Aze){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|r&3),s.setUint32(4,n),o}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),x7(n,4,e),r}}function Ize(e){let t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,o=Math.floor(n/1e9);return{sec:r+o,nsec:n-o*1e9}}function Tze(e){if(e instanceof Date){let t=Ize(e);return Sze(t)}else return null}function _ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let r=t.getUint32(0),n=t.getUint32(4),o=(r&3)*4294967296+n,s=r>>>2;return{sec:o,nsec:s}}case 12:{let r=v7(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new Vi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Pze(e){let t=_ze(e);return new Date(t.sec*1e3+t.nsec/1e6)}var Eze,Aze,Cze,Rme,Ome=b(()=>{l();dF();E7();Eze=-1,Aze=4294967296-1,Cze=17179869184-1;Rme={type:Eze,encode:Tze,decode:Pze}});var Im,fF=b(()=>{l();_me();Ome();Im=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Rme)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{let o=-1-t;this.builtInEncoders[o]=r,this.builtInDecoders[o]=n}}tryToEncode(t,r){for(let n=0;n{l()});var Rze,Oze,A7,Bme=b(()=>{l();b7();fF();E7();pF();Rze=100,Oze=2048,A7=class e{constructor(t){this.entered=!1,this.extensionCodec=t?.extensionCodec??Im.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.maxDepth=t?.maxDepth??Rze,this.initialBufferSize=t?.initialBufferSize??Oze,this.sortKeys=t?.sortKeys??!1,this.forceFloat32=t?.forceFloat32??!1,this.ignoreUndefined=t?.ignoreUndefined??!1,this.forceIntegerToFloat=t?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){let r=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let n=Sme(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Ime(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){let n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let n=y5(t);this.writeU8a(n)}encodeArray(t,r){let n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let o of t)this.doEncode(o,r+1)}countWithoutUndefined(t,r){let n=0;for(let o of r)t[o]!==void 0&&n++;return n}encodeMap(t,r){let n=Object.keys(t);this.sortKeys&&n.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of n){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){let n=t.data(this.pos+6),o=n.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(n);return}let r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),Pme(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),x7(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}});function hF(e,t){return new A7(t).encodeSharedRef(e)}var kme=b(()=>{l();Bme()});function C7(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}var Ume=b(()=>{l()});var Bze,kze,S7,Dme=b(()=>{l();b7();Bze=16,kze=16,S7=class{constructor(t=Bze,r=kze){this.hit=0,this.miss=0,this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n0&&t<=this.maxKeyLength}find(t,r,n){let o=this.caches[n-1];e:for(let s of o){let i=s.bytes;for(let a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)}decode(t,r,n){let o=this.find(t,r,n);if(o!=null)return this.hit++,o;this.miss++;let s=uF(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,s),s}}});var mF,x5,Mme,Uze,gF,b5,yF,Dze,Lme,Lze,I7,Hme=b(()=>{l();Ume();fF();E7();b7();pF();Dme();dF();mF="array",x5="map_key",Mme="map_value",Uze=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new Vi("The type of key must be string or number but "+typeof e)},gF=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let r=this.getUninitializedStateFromPool();r.type=mF,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){let r=this.getUninitializedStateFromPool();r.type=x5,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===mF){let n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===x5||t.type===Mme){let n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},b5=-1,yF=new DataView(new ArrayBuffer(0)),Dze=new Uint8Array(yF.buffer);try{yF.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}Lme=new RangeError("Insufficient data"),Lze=new S7,I7=class e{constructor(t){this.totalPos=0,this.pos=0,this.view=yF,this.bytes=Dze,this.headByte=b5,this.stack=new gF,this.entered=!1,this.extensionCodec=t?.extensionCodec??Im.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??4294967295,this.maxBinLength=t?.maxBinLength??4294967295,this.maxArrayLength=t?.maxArrayLength??4294967295,this.maxMapLength=t?.maxMapLength??4294967295,this.maxExtLength=t?.maxExtLength??4294967295,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:Lze,this.mapKeyConverter=t?.mapKeyConverter??Uze}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=b5,this.stack.reset()}setBuffer(t){let r=y5(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===b5&&!this.hasRemaining(1))this.setBuffer(t);else{let r=this.bytes.subarray(this.pos),n=y5(t),o=new Uint8Array(r.length+n.length);o.set(r),o.set(n,r.length),this.setBuffer(o)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(let a of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:o,pos:s,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${C7(o)} at ${i} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,o=-1;for await(let s of t){if(r&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){let o=t-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t<160){let o=t-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else{let o=t-160;r=this.decodeString(o,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){let o=this.lookU8();r=this.decodeString(o,1)}else if(t===218){let o=this.lookU16();r=this.decodeString(o,2)}else if(t===219){let o=this.lookU32();r=this.decodeString(o,4)}else if(t===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===196){let o=this.lookU8();r=this.decodeBinary(o,1)}else if(t===197){let o=this.lookU16();r=this.decodeBinary(o,2)}else if(t===198){let o=this.lookU32();r=this.decodeBinary(o,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){let o=this.lookU8();r=this.decodeExtension(o,1)}else if(t===200){let o=this.lookU16();r=this.decodeExtension(o,2)}else if(t===201){let o=this.lookU32();r=this.decodeExtension(o,4)}else throw new Vi(`Unrecognized type byte: ${C7(t)}`);this.complete();let n=this.stack;for(;n.length>0;){let o=n.top();if(o.type===mF)if(o.array[o.position]=r,o.position++,o.position===o.size)r=o.array,n.release(o);else continue e;else if(o.type===x5){if(r==="__proto__")throw new Vi("The key __proto__ is not allowed");o.key=this.mapKeyConverter(r),o.type=Mme;continue e}else if(o.map[o.key]=r,o.readCount++,o.readCount===o.size)r=o.map,n.release(o);else{o.key=null,o.type=x5;continue e}}return r}}readHeadByte(){return this.headByte===b5&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=b5}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new Vi(`Unrecognized array type byte: ${C7(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new Vi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new Vi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new Vi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===x5:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new Vi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw Lme;let n=this.pos+r,o=this.bytes.subarray(n,n+t);return this.pos+=r+t,o}decodeExtension(t,r){if(t>this.maxExtLength)throw new Vi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+r),o=this.decodeBinary(t,r+1);return this.extensionCodec.decode(o,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){let t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){let t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){let t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){let t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){let t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){let t=Nme(this.view,this.pos);return this.pos+=8,t}readI64(){let t=v7(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){let t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){let t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){let t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){let t=this.view.getFloat64(this.pos);return this.pos+=8,t}}});function wF(e,t){return new I7(t).decode(e)}var $me=b(()=>{l();Hme()});var Fme=b(()=>{l();kme();$me()});function bl(e){let[t,r]=e.split(Mze);return{namespace:t,reference:r}}function C1e(e,t){return e.includes(":")?[e]:t.chains||[]}function P5(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function _p(){return!(0,yl.getDocument)()&&!!(0,yl.getNavigator)()&&navigator.product===qze}function S1e(){return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function I1e(){return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Ty(){return!P5()&&!!(0,yl.getNavigator)()&&!!(0,yl.getDocument)()}function N5(){return _p()?qi.reactNative:P5()?qi.node:Ty()?qi.browser:qi.unknown}function JF(){var e;try{return _p()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(e=global.Application)==null?void 0:e.applicationId:void 0}catch{return}}function Kze(e,t){let r=new URLSearchParams(e);return Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!=null&&r.set(n,String(o))}),r.toString()}function T1e(e){var t,r;let n=QF();try{return e!=null&&e.url&&n.url&&new URL(e.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),e.url=n.url),(t=e?.icons)!=null&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(o=>o!=="")),jze(Vme(Vme({},n),e),{url:e?.url||n.url,name:e?.name||n.name,description:e?.description||n.description,icons:(r=e?.icons)!=null&&r.length&&e.icons.length>0?e.icons:n.icons})}catch(o){return console.warn("Error populating app metadata",o),e||n}}function QF(){return(0,E1e.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function Zze(){if(N5()===qi.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let e=iA();if(e===null)return"unknown";let t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function Gze(){var e;let t=N5();return t===qi.browser?[t,((e=(0,yl.getLocation)())==null?void 0:e.host)||"unknown"].join(":"):t}function XF(e,t,r){let n=Zze(),o=Gze();return[[e,t].join("-"),[Wze,r].join("-"),n,o].join("/")}function _1e({protocol:e,version:t,relayUrl:r,sdkVersion:n,auth:o,projectId:s,useOnCloseEvent:i,bundleId:a,packageName:c}){let u=r.split("?"),d=XF(e,t,n),f={auth:o,ua:d,projectId:s,useOnCloseEvent:i||void 0,packageName:c||void 0,bundleId:a||void 0},p=Kze(u[1]||"",f);return u[0]+"?"+p}function Ey(e,t){return e.filter(r=>t.includes(r)).length===e.length}function $7(e){return Object.fromEntries(e.entries())}function F7(e){return new Map(Object.entries(e))}function Pp(e=Ip.FIVE_MINUTES,t){let r=(0,Ip.toMiliseconds)(e||Ip.FIVE_MINUTES),n,o,s,i;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),i=Promise.resolve(a))},reject:a=>{s&&o&&(clearTimeout(s),o(a))},done:()=>new Promise((a,c)=>{if(i)return a(i);s=setTimeout(()=>{let u=new Error(t);i=Promise.reject(u),c(u)},r),n=a,o=c})}}function xl(e,t,r){return new Promise(async(n,o)=>{let s=setTimeout(()=>o(new Error(r)),t);try{let i=await e;n(i)}catch(i){o(i)}clearTimeout(s)})}function P1e(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function N1e(e){return P1e("topic",e)}function R1e(e){return P1e("id",e)}function z7(e){let[t,r]=e.split(":"),n={id:void 0,topic:void 0};if(t==="topic"&&typeof r=="string")n.topic=r;else if(t==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);return n}function pn(e,t){return(0,Ip.fromMiliseconds)((t||Date.now())+(0,Ip.toMiliseconds)(e))}function ka(e){return Date.now()>=(0,Ip.toMiliseconds)(e)}function cr(e,t){return`${e}${t?`:${t}`:""}`}function ml(e=[],t=[]){return[...new Set([...e,...t])]}async function O1e({id:e,topic:t,wcDeepLink:r}){var n;try{if(!r)return;let o=typeof r=="string"?JSON.parse(r):r,s=o?.href;if(typeof s!="string")return;let i=Yze(s,e,t),a=N5();if(a===qi.browser){if(!((n=(0,yl.getDocument)())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Jze(i)}else a===qi.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(i)}catch(o){console.error(o)}}function Yze(e,t,r){let n=`requestId=${t}&sessionTopic=${r}`;e.endsWith("/")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith("https://t.me")){let s=e.includes("?")?"&startapp=":"?startapp=";o=`${o}${s}${eVe(n,!0)}`}else o=`${o}/wc?${n}`;return o}function Jze(e){let t="_self";Xze()?t="_top":(Qze()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function B1e(e,t){let r="";try{if(Ty()&&(r=localStorage.getItem(t),r))return r;r=await e.getItem(t)}catch(n){console.error(n)}return r}function ez(e,t){if(!e.includes(t))return null;let r=e.split(/([&,?,=])/),n=r.indexOf(t);return r[n+2]}function tz(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function R5(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function Qze(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Xze(){try{return window.self!==window.top}catch{return!1}}function eVe(e,t=!1){let r=Buffer.from(e).toString("base64");return t?r.replace(/[=]/g,""):r}function k1e(e){return Buffer.from(e,"base64").toString("utf-8")}function U1e(e){return new Promise(t=>setTimeout(t,e))}function D1e(e,t=!1){return t?{h:Number(e&T7),l:Number(e>>qme&T7)}:{h:Number(e>>qme&T7)|0,l:Number(e&T7)|0}}function L1e(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}function V7(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Tp(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wl(e,...t){if(!V7(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function j7(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Tp(e.outputLen),Tp(e.blockLen)}function Mm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function oz(e,t){wl(e);let r=t.outputLen;if(e.length>>t}function H1e(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function dVe(e){for(let t=0;t=Ep._0&&e<=Ep._9)return e-Ep._0;if(e>=Ep.A&&e<=Ep.F)return e-(Ep.A-10);if(e>=Ep.a&&e<=Ep.f)return e-(Ep.a-10)}function B7(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if($1e)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oe().update(gl(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function pVe(e){let t=(n,o)=>e(o).update(gl(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function _y(e=32){if(W6&&typeof W6.getRandomValues=="function")return W6.getRandomValues(new Uint8Array(e));if(W6&&typeof W6.randomBytes=="function")return Uint8Array.from(W6.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function vVe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=Gme(u,d,1)^r[a],p=Yme(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=V1e[i],c=Gme(o,s,a),u=Yme(o,s,a),d=z1e[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=bVe[n],e[1]^=xVe[n]}bc(r)}function CVe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function SVe(e,t,r){return e&t^~e&r}function IVe(e,t,r){return e&t^e&r^t&r}function Rm(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=ke[2*e],u=ke[2*e+1],d=ke[2*t],f=ke[2*t+1],p=ke[2*r],h=ke[2*r+1],y=ke[2*n],w=ke[2*n+1],x=rz(c,d,i);u=nz(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:tVe(w,y),Dl:rVe(w)},{h,l:p}=hl(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:Bm(f,d,24),Bl:km(f,d,24)},ke[2*e]=c,ke[2*e+1]=u,ke[2*t]=d,ke[2*t+1]=f,ke[2*r]=p,ke[2*r+1]=h,ke[2*n]=y,ke[2*n+1]=w}function Om(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=ke[2*e],u=ke[2*e+1],d=ke[2*t],f=ke[2*t+1],p=ke[2*r],h=ke[2*r+1],y=ke[2*n],w=ke[2*n+1],x=rz(c,d,i);u=nz(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:Bm(w,y,16),Dl:km(w,y,16)},{h,l:p}=hl(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:A5(f,d,63),Bl:C5(f,d,63)},ke[2*e]=c,ke[2*e+1]=u,ke[2*t]=d,ke[2*t+1]=f,ke[2*r]=p,ke[2*r+1]=h,ke[2*n]=y,ke[2*n+1]=w}function kVe(e,t={},r,n,o){if(Tp(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");let{key:s,salt:i,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(i!==void 0&&i.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==o)throw new Error("personalization must be undefined or "+o)}function K1e(e){let t=`Ethereum Signed Message: +${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toString("hex")}async function LVe(e,t,r,n,o,s){switch(r.t){case"eip191":return await MVe(e,t,r.s);case"eip1271":return await HVe(e,t,r.s,n,o,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function MVe(e,t,r){let n=y7.fromHex(r);return w7.recoverAddress({payload:K1e(t),signature:n}).toLowerCase()===e.toLowerCase()}async function HVe(e,t,r,n,o,s){let i=bl(n);if(!i.namespace||!i.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{let a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),d=(u.length/2).toString(16).padStart(64,"0"),f=(t.startsWith("0x")?t:K1e(t)).substring(2),p=a+f+c+d+u,h=await fetch(`${s||DVe}/?chainId=${n}&projectId=${o}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:$Ve(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:p},"latest"]})}),{result:y}=await h.json();return y?y.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function $Ve(){return Date.now()+Math.floor(Math.random()*1e3)}function Z1e(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;is.charCodeAt(0)),n=new Uint8Array(r.length+t.length);n.set(r),n.set(t,r.length);let o=UVe(n,{dkLen:32});return wm.encode(o)}function sz(e){let t=new Uint8Array(q7(FVe(e)));return wm.encode(t)}function FVe(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if(typeof e=="object"&&e!=null&&e.data)return new Uint8Array(Object.values(e.data));if(typeof e=="object"&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function iz(e){let t=Buffer.from(e,"base64"),r=wF(t).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");let n=hF(r),o=Buffer.from("TX"),s=Buffer.concat([o,Buffer.from(n)]),i=OVe(s);return KA.encode(i).replace(/=+$/,"")}function xF(e){let t=[],r=BigInt(e);for(;r>=BigInt(128);)t.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return t.push(Number(r)),Buffer.from(t)}function Y1e(e){let t=Buffer.from(e.signed.bodyBytes,"base64"),r=Buffer.from(e.signed.authInfoBytes,"base64"),n=Buffer.from(e.signature.signature,"base64"),o=[];o.push(Buffer.from([10])),o.push(xF(t.length)),o.push(t),o.push(Buffer.from([18])),o.push(xF(r.length)),o.push(r),o.push(Buffer.from([26])),o.push(xF(n.length)),o.push(n);let s=Buffer.concat(o),i=q7(s);return Buffer.from(i).toString("hex").toUpperCase()}function J1e(e){var t,r;let n=[];try{if(typeof e=="string")return n.push(e),n;if(typeof e!="object")return n;e!=null&&e.id&&n.push(e.id);let o=(r=(t=e?.capabilities)==null?void 0:t.caip345)==null?void 0:r.transactionHashes;o&&n.push(...o)}catch(o){console.warn("getWalletSendCallsHashes failed: ",o)}return n}async function az(e){let{cacao:t,projectId:r}=e,{s:n,p:o}=t,s=cz(o,o.iss),i=B5(o.iss);return await LVe(i,s,n,K7(o.iss),r)}function XVe(e){return Buffer.from(JSON.stringify(e)).toString("base64")}function eje(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}function Iy(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");let t=Object.keys(e.att);if(!(t!=null&&t.length))throw new Error("No resources found in `att` property");t.forEach(r=>{let n=e.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(o=>{let s=n[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!="object")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function tje(e,t,r,n={}){return r?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:rje(t,r,n)}}}function rje(e,t,r={}){t=t?.sort((o,s)=>o.localeCompare(s));let n=t.map(o=>({[`${e}/${o}`]:[r]}));return Object.assign({},...n)}function X1e(e){return Iy(e),`urn:recap:${XVe(e).replace(/=/g,"")}`}function _5(e){let t=eje(e.replace("urn:recap:",""));return Iy(t),t}function ege(e,t,r){let n=tje(e,t,r);return X1e(n)}function nje(e){return e&&e.includes("urn:recap:")}function tge(e,t){let r=_5(e),n=_5(t),o=oje(r,n);return X1e(o)}function oje(e,t){Iy(e),Iy(t);let r=Object.keys(e.att).concat(Object.keys(t.att)).sort((o,s)=>o.localeCompare(s)),n={att:{}};return r.forEach(o=>{var s,i;Object.keys(((s=e.att)==null?void 0:s[o])||{}).concat(Object.keys(((i=t.att)==null?void 0:i[o])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;n.att[o]=ZVe(KVe({},n.att[o]),{[a]:((c=e.att[o])==null?void 0:c[a])||((u=t.att[o])==null?void 0:u[a])})})}),n}function sje(e="",t){Iy(t);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(r))return e;let n=[],o=0;Object.keys(t.att).forEach(a=>{let c=Object.keys(t.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,p)=>f.action.localeCompare(p.action));let u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});let d=Object.keys(u).map(f=>(o++,`(${o}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});let s=n.join(" "),i=`${r}${s}`;return`${e?e+" ":""}${i}`}function lz(e){var t;let r=_5(e);Iy(r);let n=(t=r.att)==null?void 0:t.eip155;return n?Object.keys(n).map(o=>o.split("/")[1]):[]}function uz(e){let t=_5(e);Iy(t);let r=[];return Object.values(t.att).forEach(n=>{Object.values(n).forEach(o=>{var s;(s=o?.[0])!=null&&s.chains&&r.push(o[0].chains)})}),[...new Set(r.flat())]}function k5(e){if(!e)return;let t=e?.[e.length-1];return nje(t)?t:void 0}function rge(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function MF(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function vF(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ji(e,...t){if(!rge(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Xme(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ije(e,t){ji(e);let r=t.outputLen;if(e.length>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function pje(e,t,r){MF(r);let n=new Uint8Array(16),o=aje(n);return t1e(o,0,BigInt(t),r),t1e(o,8,BigInt(e),r),n}function hje(e){return e.byteOffset%4===0}function $F(e){return Uint8Array.from(e)}function tr(e,t){return e<>>32-t}function FF(e){return e.byteOffset%4===0}function xje(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(_7),d=Lm(u),f=FF(o)&&FF(s),p=f?Lm(o):r1e,h=f?Lm(s):r1e;for(let y=0;y=oge)throw new Error("arx: counter overflow");let w=Math.min(_7,c-y);if(f&&w===_7){let x=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,T;v{ji(a),ji(c),ji(u);let p=u.length;if(d===void 0&&(d=new Uint8Array(p)),ji(d),vF(f),f<0||f>=oge)throw new Error("arx: counter overflow");if(d.lengthe(o).update(HF(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Cje(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],p=t[2],h=t[3],y=t[4],w=t[5],x=t[6],v=t[7],T=o,E=r[0],S=r[1],_=r[2],O=i,D=a,M=c,N=u,L=d,P=f,R=p,I=h,B=y,C=w,A=x,U=v,H=T,k=E,F=S,j=_;for(let ae=0;ae255*o)throw new Error("Length should be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0&&(r=s1e);let i=new Uint8Array(s*o),a=Z7.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;ddz;e>>=VF,t+=1);return t}function Bje(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),o=p=>Uint8Array.of(p),s=n(e),i=n(e),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...p)=>r(i,s,...p),d=(p=n(0))=>{i=u(o(0),p),s=u(),p.length!==0&&(i=u(o(1),p),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,h=[];for(;p{c(),d(p);let y;for(;!(y=h(f()));)d();return c(),y}}function J7(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function i1e(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}function Ba(e,t){let r=e%t;return r>=Wi?r:t+r}function pl(e,t,r){let n=e;for(;t-- >Wi;)n*=n,n%=r;return n}function a1e(e,t){if(e===Wi)throw new Error("invert: expected non-zero number");if(t<=Wi)throw new Error("invert: expected positive modulus, got "+t);let r=Ba(e,t),n=t,o=Wi,s=pi;for(;r!==Wi;){let i=n/r,a=n%r,c=o-s*i;n=r,r=a,o=s,s=c}if(n!==pi)throw new Error("invert: does not exist");return Ba(o,t)}function hz(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function pge(e,t){let r=(e.ORDER+pi)/lge,n=e.pow(t,r);return hz(e,n,t),n}function Dje(e,t){let r=(e.ORDER-uge)/dge,n=e.mul(t,Cy),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,Cy),o),a=e.mul(s,e.sub(i,e.ONE));return hz(e,a,t),a}function Lje(e){let t=Fm(e),r=hge(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+kje)/fge;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),h=a.eql(a.sqr(d),c),y=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(p,f,y);let w=a.eql(a.sqr(d),c),x=a.cmov(u,d,w);return hz(a,x,c),x}}function hge(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return pge;let s=o.pow(n,t),i=(t+pi)/Cy;return function(a,c){if(a.is0(c))return c;if(c1e(a,c)!==1)throw new Error("Cannot find square root");let u=r,d=a.mul(a.ONE,s),f=a.pow(c,t),p=a.pow(c,i);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let h=1,y=a.sqr(f);for(;!a.eql(y,a.ONE);)if(h++,y=a.sqr(y),h===u)throw new Error("Cannot find square root");let w=pi<(n[o]="function",n),t);return J7(e,r),e}function Fje(e,t,r){if(rWi;)r&pi&&(n=e.mul(n,o)),o=e.sqr(o),r>>=pi;return n}function mge(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function c1e(e,t){let r=(e.ORDER-pi)/Cy,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function gge(e,t){t!==void 0&&Tp(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Fm(e,t,r=!1,n={}){if(e<=Wi)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(r=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=gge(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:U5(c),ZERO:Wi,ONE:pi,allowedLengths:a,create:p=>Ba(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return Wi<=p&&pp===Wi,isValidNot0:p=>!f.is0(p)&&f.isValid(p),isOdd:p=>(p&pi)===pi,neg:p=>Ba(-p,e),eql:(p,h)=>p===h,sqr:p=>Ba(p*p,e),add:(p,h)=>Ba(p+h,e),sub:(p,h)=>Ba(p-h,e),mul:(p,h)=>Ba(p*h,e),pow:(p,h)=>Fje(f,p,h),div:(p,h)=>Ba(p*a1e(h,e),e),sqrN:p=>p*p,addN:(p,h)=>p+h,subN:(p,h)=>p-h,mulN:(p,h)=>p*h,inv:p=>a1e(p,e),sqrt:s||(p=>(d||(d=Mje(e)),d(f,p))),toBytes:p=>r?pz(p,u):fz(p,u),fromBytes:(p,h=!0)=>{if(a){if(!a.includes(p.length)||p.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let w=new Uint8Array(u);w.set(p,r?0:w.length-p.length),p=w}if(p.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+p.length);let y=r?L7(p):Y7(p);if(i&&(y=Ba(y,e)),!h&&!f.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:p=>mge(f,p),cmov:(p,h,y)=>y?h:p});return Object.freeze(f)}function yge(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function wge(e){let t=yge(e);return t+Math.ceil(t/2)}function zje(e,t,r=!1){let n=e.length,o=yge(t),s=wge(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?L7(e):Y7(e),a=Ba(i,t-pi)+pi;return r?pz(a,o):fz(a,o)}function M7(e,t){let r=t.negate();return e?r:t}function CF(e,t){let r=mge(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function bge(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function SF(e,t){bge(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=U5(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function l1e(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=Sy);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function Vje(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function jje(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function TF(e){return xge.get(e)||1}function u1e(e){if(e!==X6)throw new Error("invalid wNAF")}function qje(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>X6||n>X6;)r&Sy&&(s=s.add(o)),n&Sy&&(i=i.add(o)),o=o.double(),r>>=Sy,n>>=Sy;return{p1:s,p2:i}}function Wje(e,t,r,n){Vje(r,e),jje(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=age(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=U5(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;wX6))throw new Error(`CURVE.${a} must be positive bigint`)}let o=d1e(t.p,r.Fp,n),s=d1e(t.n,r.Fn,n),i=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let a of i)if(!o.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Zje(e){return J7(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Gje(e){let t=Zje(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||_y,u=a?255:448,d=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),h=a?N7**BigInt(254):N7**BigInt(447),y=a?BigInt(8)*N7**BigInt(251)-K6:BigInt(4)*N7**BigInt(445)-K6,w=h+y+K6,x=R=>Ba(R,r),v=T(f);function T(R){return pz(x(R),d)}function E(R){let I=Ss("u coordinate",R,d);return a&&(I[31]&=127),x(L7(I))}function S(R){return L7(o(Ss("scalar",R,d)))}function _(R,I){let B=M(E(I),S(R));if(B===E5)throw new Error("invalid private or public key received");return T(B)}function O(R){return _(R,v)}function D(R,I,B){let C=x(R*(I-B));return I=x(I-C),B=x(B+C),{x_2:I,x_3:B}}function M(R,I){jF("u",R,E5,r),jF("scalar",I,h,w);let B=I,C=R,A=K6,U=E5,H=R,k=K6,F=E5;for(let W=BigInt(u-1);W>=E5;W--){let ae=B>>W&K6;F^=ae,{x_2:A,x_3:H}=D(F,A,H),{x_2:U,x_3:k}=D(F,U,k),F=ae;let te=A+U,X=x(te*te),pe=A-U,me=x(pe*pe),Ne=X-me,ye=H+k,Re=H-k,Et=x(Re*te),kt=x(ye*pe),At=Et+kt,ur=Et-kt;H=x(At*At),k=x(C*x(ur*ur)),A=x(X*me),U=x(Ne*(X+x(p*Ne)))}({x_2:A,x_3:H}=D(F,A,H)),{x_2:U,x_3:k}=D(F,U,k);let j=s(U);return x(A*j)}let N={secretKey:d,publicKey:d,seed:d},L=(R=c(d))=>(wl(R,N.seed),R);function P(R){let I=L(R);return{secretKey:I,publicKey:O(I)}}return{keygen:P,getSharedSecret:(R,I)=>_(R,I),getPublicKey:R=>O(R),scalarMult:_,scalarMultBase:O,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:v.slice(),lengths:N}}function tqe(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=vge,i=e*e%s*e%s,a=pl(i,f1e,s)*i%s,c=pl(a,Yje,s)*e%s,u=pl(c,Qje,s)*c%s,d=pl(u,t,s)*u%s,f=pl(d,r,s)*d%s,p=pl(f,n,s)*f%s,h=pl(p,o,s)*p%s,y=pl(h,o,s)*p%s,w=pl(y,t,s)*u%s;return{pow_p_5_8:pl(w,f1e,s)*e%s,b2:i}}function rqe(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function oqe(e,t,r){let[[n,o],[s,i]]=t,a=p1e(i*e,r),c=p1e(-o*e,r),u=e-a*n-c*s,d=-a*o-c*i,f=u=h||d=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function KF(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function _F(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return D7(r.lowS,"lowS"),D7(r.prehash,"prehash"),r.format!==void 0&&KF(r.format),r}function Z6(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=Ss("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function iqe(e,t={}){let r=Kje("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;J7(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Cge(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(R,I,B){let{x:C,y:A}=I.toAffine(),U=n.toBytes(C);if(D7(B,"isCompressed"),B){d();let H=!n.isOdd(A);return Dm(Age(H),U)}else return Dm(Uint8Array.of(4),U,n.toBytes(A))}function p(R){Ay(R,void 0,"Point");let{publicKey:I,publicKeyUncompressed:B}=u,C=R.length,A=R[0],U=R.subarray(1);if(C===I&&(A===2||A===3)){let H=n.fromBytes(U);if(!n.isValid(H))throw new Error("bad point: is not on curve, wrong x");let k=w(H),F;try{F=n.sqrt(k)}catch(W){let ae=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}d();let j=n.isOdd(F);return(A&1)===1!==j&&(F=n.neg(F)),{x:H,y:F}}else if(C===B&&A===4){let H=n.BYTES,k=n.fromBytes(U.subarray(0,H)),F=n.fromBytes(U.subarray(H,H*2));if(!x(k,F))throw new Error("bad point: is not on curve");return{x:k,y:F}}else throw new Error(`bad point: got length ${C}, expected compressed=${I} or uncompressed=${B}`)}let h=t.toBytes||f,y=t.fromBytes||p;function w(R){let I=n.sqr(R),B=n.mul(I,R);return n.add(n.add(B,n.mul(R,s.a)),s.b)}function x(R,I){let B=n.sqr(I),C=w(R);return n.eql(B,C)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,R7),sqe),T=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,T)))throw new Error("bad curve params: a or b");function E(R,I,B=!1){if(!n.isValid(I)||B&&n.is0(I))throw new Error(`bad point coordinate ${R}`);return I}function S(R){if(!(R instanceof N))throw new Error("ProjectivePoint expected")}function _(R){if(!c||!c.basises)throw new Error("no endo");return oqe(R,c.basises,o.ORDER)}let O=i1e((R,I)=>{let{X:B,Y:C,Z:A}=R;if(n.eql(A,n.ONE))return{x:B,y:C};let U=R.is0();I==null&&(I=U?n.ONE:n.inv(A));let H=n.mul(B,I),k=n.mul(C,I),F=n.mul(A,I);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:k}}),D=i1e(R=>{if(R.is0()){if(t.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:B}=R.toAffine();if(!n.isValid(I)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!x(I,B))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,I,B,C,A){return B=new N(n.mul(B.X,R),B.Y,B.Z),I=M7(C,I),B=M7(A,B),I.add(B)}class N{constructor(I,B,C){this.X=E("x",I),this.Y=E("y",B,!0),this.Z=E("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){let{x:B,y:C}=I||{};if(!I||!n.isValid(B)||!n.isValid(C))throw new Error("invalid affine point");if(I instanceof N)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(C)?N.ZERO:new N(B,C,n.ONE)}static fromBytes(I){let B=N.fromAffine(y(Ay(I,void 0,"point")));return B.assertValidity(),B}static fromHex(I){return N.fromBytes(Ss("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,B=!0){return P.createCache(this,I),B||this.multiply(R7),this}assertValidity(){D(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.eql(n.mul(B,k),n.mul(U,A)),j=n.eql(n.mul(C,k),n.mul(H,A));return F&&j}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:B}=s,C=n.mul(B,R7),{X:A,Y:U,Z:H}=this,k=n.ZERO,F=n.ZERO,j=n.ZERO,W=n.mul(A,A),ae=n.mul(U,U),te=n.mul(H,H),X=n.mul(A,U);return X=n.add(X,X),j=n.mul(A,H),j=n.add(j,j),k=n.mul(I,j),F=n.mul(C,te),F=n.add(k,F),k=n.sub(ae,F),F=n.add(ae,F),F=n.mul(k,F),k=n.mul(X,k),j=n.mul(C,j),te=n.mul(I,te),X=n.sub(W,te),X=n.mul(I,X),X=n.add(X,j),j=n.add(W,W),W=n.add(j,W),W=n.add(W,te),W=n.mul(W,X),F=n.add(F,W),te=n.mul(U,H),te=n.add(te,te),W=n.mul(te,X),k=n.sub(k,W),j=n.mul(te,ae),j=n.add(j,j),j=n.add(j,j),new N(k,F,j)}add(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.ZERO,j=n.ZERO,W=n.ZERO,ae=s.a,te=n.mul(s.b,R7),X=n.mul(B,U),pe=n.mul(C,H),me=n.mul(A,k),Ne=n.add(B,C),ye=n.add(U,H);Ne=n.mul(Ne,ye),ye=n.add(X,pe),Ne=n.sub(Ne,ye),ye=n.add(B,A);let Re=n.add(U,k);return ye=n.mul(ye,Re),Re=n.add(X,me),ye=n.sub(ye,Re),Re=n.add(C,A),F=n.add(H,k),Re=n.mul(Re,F),F=n.add(pe,me),Re=n.sub(Re,F),W=n.mul(ae,ye),F=n.mul(te,me),W=n.add(F,W),F=n.sub(pe,W),W=n.add(pe,W),j=n.mul(F,W),pe=n.add(X,X),pe=n.add(pe,X),me=n.mul(ae,me),ye=n.mul(te,ye),pe=n.add(pe,me),me=n.sub(X,me),me=n.mul(ae,me),ye=n.add(ye,me),X=n.mul(pe,ye),j=n.add(j,X),X=n.mul(Re,ye),F=n.mul(Ne,F),F=n.sub(F,X),X=n.mul(Ne,pe),W=n.mul(Re,W),W=n.add(W,X),new N(F,j,W)}subtract(I){return this.add(I.negate())}is0(){return this.equals(N.ZERO)}multiply(I){let{endo:B}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let C,A,U=H=>P.cached(this,H,k=>CF(N,k));if(B){let{k1neg:H,k1:k,k2neg:F,k2:j}=_(I),{p:W,f:ae}=U(k),{p:te,f:X}=U(j);A=ae.add(X),C=M(B.beta,W,te,H,F)}else{let{p:H,f:k}=U(I);C=H,A=k}return CF(N,[C,A])[0]}multiplyUnsafe(I){let{endo:B}=t,C=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===Sp||C.is0())return N.ZERO;if(I===Y6)return C;if(P.hasCache(this))return this.multiply(I);if(B){let{k1neg:A,k1:U,k2neg:H,k2:k}=_(I),{p1:F,p2:j}=qje(N,C,U,k);return M(B.beta,F,j,A,H)}else return P.unsafe(C,I)}multiplyAndAddUnsafe(I,B,C){let A=this.multiplyUnsafe(B).add(I.multiplyUnsafe(C));return A.is0()?void 0:A}toAffine(I){return O(this,I)}isTorsionFree(){let{isTorsionFree:I}=t;return i===Y6?!0:I?I(N,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=t;return i===Y6?this:I?I(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return D7(I,"isCompressed"),this.assertValidity(),h(N,this,I)}toHex(I=!0){return G6(this.toBytes(I))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return CF(N,I)}static msm(I,B){return Wje(N,o,I,B)}static fromPrivateKey(I){return N.BASE.multiply(Z6(o,I))}}N.BASE=new N(s.Gx,s.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=o;let L=o.BITS,P=new qF(N,t.endo?Math.ceil(L/2):L);return N.BASE.precompute(8),N}function Age(e){return Uint8Array.of(e?2:3)}function Cge(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function aqe(e,t={}){let{Fn:r}=e,n=t.randomBytes||_y,o=Object.assign(Cge(e.Fp,r),{seed:wge(r.ORDER)});function s(p){try{return!!Z6(r,p)}catch{return!1}}function i(p,h){let{publicKey:y,publicKeyUncompressed:w}=o;try{let x=p.length;return h===!0&&x!==y||h===!1&&x!==w?!1:!!e.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return zje(Ay(p,o.seed,"seed"),r.ORDER)}function c(p,h=!0){return e.BASE.multiply(Z6(r,p)).toBytes(h)}function u(p){let h=a(p);return{secretKey:h,publicKey:c(h)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof e)return!0;let{secretKey:h,publicKey:y,publicKeyUncompressed:w}=o;if(r.allowedLengths||h===y)return;let x=Ss("key",p).length;return x===y||x===w}function f(p,h,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(h)===!1)throw new Error("second arg must be public key");let w=Z6(r,p);return e.fromHex(h).multiply(w).toBytes(y)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:p=>Z6(r,p),precompute(p=8,h=e.BASE){return h.precompute(p,!1)}},lengths:o})}function cqe(e,t,r={}){j7(t),J7(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||_y,o=r.hmac||((B,...C)=>Z7(t,B,Dm(...C))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h}=aqe(e,r),y={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function x(B){let C=a>>Y6;return B>C}function v(B,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${B}: out of range 1..Point.Fn.ORDER`);return C}function T(B,C){KF(C);let A=h.signature,U=C==="compact"?A:C==="recovered"?A+1:void 0;return Ay(B,U,`${C} signature`)}class E{constructor(C,A,U){this.r=v("r",C),this.s=v("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(C,A=w){T(C,A);let U;if(A==="der"){let{r:j,s:W}=Cp.toSig(Ay(C));return new E(j,W)}A==="recovered"&&(U=C[0],A="compact",C=C.subarray(1));let H=i.BYTES,k=C.subarray(0,H),F=C.subarray(H,H*2);return new E(i.fromBytes(k),i.fromBytes(F),U)}static fromHex(C,A){return this.fromBytes(B7(C),A)}addRecoveryBit(C){return new E(this.r,this.s,C)}recoverPublicKey(C){let A=s.ORDER,{r:U,s:H,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*Ege1)throw new Error("recovery id is ambiguous for h>1 curve");let F=k===2||k===3?U+a:U;if(!s.isValid(F))throw new Error("recovery id 2 or 3 invalid");let j=s.toBytes(F),W=e.fromBytes(Dm(Age((k&1)===0),j)),ae=i.inv(F),te=_(Ss("msgHash",C)),X=i.create(-te*ae),pe=i.create(H*ae),me=e.BASE.multiplyUnsafe(X).add(W.multiplyUnsafe(pe));if(me.is0())throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return x(this.s)}toBytes(C=w){if(KF(C),C==="der")return B7(Cp.hexFromSig(this));let A=i.toBytes(this.r),U=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Dm(Uint8Array.of(this.recovery),A,U)}return Dm(A,U)}toHex(C){return G6(this.toBytes(C))}assertValidity(){}static fromCompact(C){return E.fromBytes(Ss("sig",C),"compact")}static fromDER(C){return E.fromBytes(Ss("sig",C),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return G6(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return G6(this.toBytes("compact"))}}let S=r.bits2int||function(B){if(B.length>8192)throw new Error("input is too large");let C=Y7(B),A=B.length*8-c;return A>0?C>>BigInt(A):C},_=r.bits2int_modN||function(B){return i.create(S(B))},O=U5(c);function D(B){return jF("num < 2^"+c,B,Sp,O),i.toBytes(B)}function M(B,C){return Ay(B,void 0,"message"),C?Ay(t(B),void 0,"prehashed message"):B}function N(B,C,A){if(["recovered","canonical"].some(pe=>pe in A))throw new Error("sign() legacy options not supported");let{lowS:U,prehash:H,extraEntropy:k}=_F(A,y);B=M(B,H);let F=_(B),j=Z6(i,C),W=[D(j),D(F)];if(k!=null&&k!==!1){let pe=k===!0?n(h.secretKey):k;W.push(Ss("extraEntropy",pe))}let ae=Dm(...W),te=F;function X(pe){let me=S(pe);if(!i.isValidNot0(me))return;let Ne=i.inv(me),ye=e.BASE.multiply(me).toAffine(),Re=i.create(ye.x);if(Re===Sp)return;let Et=i.create(Ne*i.create(te+Re*j));if(Et===Sp)return;let kt=(ye.x===Re?0:2)|Number(ye.y&Y6),At=Et;return U&&x(Et)&&(At=i.neg(Et),kt^=1),new E(Re,At,kt)}return{seed:ae,k2sig:X}}function L(B,C,A={}){B=Ss("message",B);let{seed:U,k2sig:H}=N(B,C,A);return Bje(t.outputLen,i.BYTES,o)(U,H)}function P(B){let C,A=typeof B=="string"||V7(B),U=!A&&B!==null&&typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)C=new E(B.r,B.s);else if(A){try{C=E.fromBytes(Ss("sig",B),"der")}catch(H){if(!(H instanceof Cp.Err))throw H}if(!C)try{C=E.fromBytes(Ss("sig",B),"compact")}catch{return!1}}return C||!1}function R(B,C,A,U={}){let{lowS:H,prehash:k,format:F}=_F(U,y);if(A=Ss("publicKey",A),C=M(Ss("message",C),k),"strict"in U)throw new Error("options.strict was renamed to lowS");let j=F===void 0?P(B):E.fromBytes(Ss("sig",B),F);if(j===!1)return!1;try{let W=e.fromBytes(A);if(H&&j.hasHighS())return!1;let{r:ae,s:te}=j,X=_(C),pe=i.inv(te),me=i.create(X*pe),Ne=i.create(ae*pe),ye=e.BASE.multiplyUnsafe(me).add(W.multiplyUnsafe(Ne));return ye.is0()?!1:i.create(ye.x)===ae}catch{return!1}}function I(B,C,A={}){let{prehash:U}=_F(A,y);return C=M(C,U),E.fromBytes(B,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h,Point:e,sign:L,verify:R,recoverPublicKey:I,Signature:E,hash:t})}function lqe(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=Fm(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function uqe(e){let{CURVE:t,curveOpts:r}=lqe(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function dqe(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,gge(r.Fn.ORDER,r.Fn.BITS))})}function fqe(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:o}=uqe(e),s=iqe(t,r),i=cqe(s,n,o);return dqe(e,i)}function GF(e,t){let r=n=>fqe({...e,hash:n});return{...r(t),create:r}}function Nge(){let e=WF.utils.randomPrivateKey(),t=WF.getPublicKey(e);return{privateKey:Ut(e,Is),publicKey:Ut(t,Is)}}function Q7(){let e=_y(mz);return Ut(e,Is)}function Rge(e,t){let r=WF.getSharedSecret(Qt(e,Is),Qt(t,Is)),n=Rje(G7,r,void 0,void 0,mz);return Ut(n,Is)}function tx(e){let t=G7(Qt(e,Is));return Ut(t,Is)}function Ki(e){let t=G7(Qt(e,D5));return Ut(t,Is)}function Oge(e){return Qt(`${e}`,_ge)}function Hm(e){return Number(Ut(e,_ge))}function Bge(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kge(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}function Uge(e){let t=Oge(typeof e.type<"u"?e.type:Pge);if(Hm(t)===vl&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof e.senderPublicKey<"u"?Qt(e.senderPublicKey,Is):void 0,n=typeof e.iv<"u"?Qt(e.iv,Is):_y(S5),o=Qt(e.symKey,Is),s=sge(o,n).encrypt(Qt(e.message,D5)),i=Hge({type:t,sealed:s,iv:n,senderPublicKey:r});return e.encoding===Np?Bge(i):i}function Dge(e){let t=Qt(e.symKey,Is),{sealed:r,iv:n}=rx({encoded:e.encoded,encoding:e.encoding}),o=sge(t,n).decrypt(r);if(o===null)throw new Error("Failed to decrypt");return Ut(o,D5)}function Lge(e,t){let r=Oge(ex),n=_y(S5),o=Qt(e,D5),s=Hge({type:r,sealed:o,iv:n});return t===Np?Bge(s):s}function Mge(e,t){let{sealed:r}=rx({encoded:e,encoding:t});return Ut(r,D5)}function Hge(e){if(Hm(e.type)===ex)return Ut(Ms([e.type,e.sealed]),Ts);if(Hm(e.type)===vl){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ut(Ms([e.type,e.senderPublicKey,e.iv,e.sealed]),Ts)}return Ut(Ms([e.type,e.iv,e.sealed]),Ts)}function rx(e){let t=(e.encoding||Ts)===Np?kge(e.encoded):e.encoded,r=Qt(t,Ts),n=r.slice(wqe,h1e),o=h1e;if(Hm(n)===vl){let c=o+mz,u=c+S5,d=r.slice(o,c),f=r.slice(c,u),p=r.slice(u);return{type:n,sealed:p,iv:f,senderPublicKey:d}}if(Hm(n)===ex){let c=r.slice(o),u=_y(S5);return{type:n,sealed:c,iv:u}}let s=o+S5,i=r.slice(o,s),a=r.slice(s);return{type:n,sealed:a,iv:i}}function $ge(e,t){let r=rx({encoded:e,encoding:t?.encoding});return gz({type:Hm(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ut(r.senderPublicKey,Is):void 0,receiverPublicKey:t?.receiverPublicKey})}function gz(e){let t=e?.type||Pge;if(t===vl){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function yz(e){return e.type===vl&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function wz(e){return e.type===ex}function bqe(e){let t=Buffer.from(e.x,"base64"),r=Buffer.from(e.y,"base64");return Ms([new Uint8Array([4]),t,r])}function Fge(e,t){let[r,n,o]=e.split("."),s=Buffer.from(kge(o),"base64");if(s.length!==64)throw new Error("Invalid signature length");let i=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=G7(c),d=bqe(t);if(!yqe.verify(Ms([i,a]),u,d))throw new Error("Invalid signature");return Hl(e).payload}function L5(e){return e?.relay||{protocol:xqe}}function Py(e){let t=kC[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Tqe(e,t="-"){let r={},n="relay"+t;return Object.keys(e).forEach(o=>{if(o.startsWith(n)){let s=o.replace(n,""),i=e[o];r[s]=i}}),r}function bz(e){if(!e.includes("wc:")){let u=k1e(e);u!=null&&u.includes("wc:")&&(e=u)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;let t=e.indexOf(":"),r=e.indexOf("?")!==-1?e.indexOf("?"):void 0,n=e.substring(0,t),o=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",i=new URLSearchParams(s),a=Object.fromEntries(i.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:_qe(o[0]),version:parseInt(o[1],10),symKey:a.symKey,relay:Tqe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function _qe(e){return e.startsWith("//")?e.substring(2):e}function Pqe(e,t="-"){let r="relay",n={};return Object.keys(e).forEach(o=>{let s=o,i=r+t+s;e[s]&&(n[i]=e[s])}),n}function xz(e){let t=new URLSearchParams,r=PF(PF(Iqe(PF({},Pqe(e.relay)),{symKey:e.symKey}),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")});return Object.entries(r).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!==void 0&&t.append(n,String(o))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function M5(e,t,r){return`${e}?wc_ev=${r}&topic=${t}`}function nx(e){let t=[];return e.forEach(r=>{let[n,o]=r.split(":");t.push(`${n}:${o}`)}),t}function vz(e){let t=[];return Object.values(e).forEach(r=>{t.push(...nx(r.accounts))}),[...new Set(t)]}function zge(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.methods)}),[...new Set(t)]}function Vge(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.events)}),[...new Set(t)]}function Lqe(e,t){let r=[];return Object.values(e).forEach(n=>{nx(n.accounts).includes(t)&&r.push(...n.methods)}),r}function Mqe(e,t){let r=[];return Object.values(e).forEach(n=>{nx(n.accounts).includes(t)&&r.push(...n.events)}),r}function H5(e){return e.includes(":")}function Ny(e){return H5(e)?e.split(":")[0]:e}function b1e(e){var t,r,n;let o={};if(!xc(e))return o;for(let[s,i]of Object.entries(e)){let a=H5(s)?[s]:i.chains,c=i.methods||[],u=i.events||[],d=Ny(s);o[d]=Dqe(Uqe({},o[d]),{chains:ml(a,(t=o[d])==null?void 0:t.chains),methods:ml(c,(r=o[d])==null?void 0:r.methods),events:ml(u,(n=o[d])==null?void 0:n.events)})}return o}function Hqe(e){let t={};return e?.forEach(r=>{var n;let[o,s]=r.split(":");t[o]||(t[o]={accounts:[],chains:[],events:[],methods:[]}),t[o].accounts.push(r),(n=t[o].chains)==null||n.push(`${o}:${s}`)}),t}function Ez(e,t){t=t.map(n=>n.replace("did:pkh:",""));let r=Hqe(t);for(let[n,o]of Object.entries(r))o.methods?o.methods=ml(o.methods,e):o.methods=e,o.events=["chainChanged","accountsChanged"];return r}function jge(e,t){var r,n,o,s,i,a;let c=b1e(e),u=b1e(t),d={},f=Object.keys(c).concat(Object.keys(u));for(let p of f)d[p]={chains:ml((r=c[p])==null?void 0:r.chains,(n=u[p])==null?void 0:n.chains),methods:ml((o=c[p])==null?void 0:o.methods,(s=u[p])==null?void 0:s.methods),events:ml((i=c[p])==null?void 0:i.events,(a=u[p])==null?void 0:a.events)};return d}function Ie(e,t){let{message:r,code:n}=Fqe[e];return{message:t?`${r} ${t}`:r,code:n}}function Rr(e,t){let{message:r,code:n}=$qe[e];return{message:t?`${r} ${t}`:r,code:n}}function El(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function xc(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Ln(e){return typeof e>"u"}function An(e,t){return t&&Ln(e)?!0:typeof e=="string"&&!!e.trim().length}function Az(e,t){return t&&Ln(e)?!0:typeof e=="number"&&!isNaN(e)}function qge(e,t){let{requiredNamespaces:r}=t,n=Object.keys(e.namespaces),o=Object.keys(r),s=!0;return Ey(o,n)?(n.forEach(i=>{let{accounts:a,methods:c,events:u}=e.namespaces[i],d=nx(a),f=r[i];(!Ey(C1e(i,f),d)||!Ey(f.methods,c)||!Ey(f.events,u))&&(s=!1)}),s):!1}function H7(e){return An(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function zqe(e){if(An(e,!1)&&e.includes(":")){let t=e.split(":");if(t.length===3){let r=t[0]+":"+t[1];return!!t[2]&&H7(r)}}return!1}function Wge(e){function t(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(An(e,!1)){if(t(e))return!0;let r=k1e(e);return t(r)}}catch{}return!1}function Kge(e){var t;return(t=e?.proposer)==null?void 0:t.publicKey}function Zge(e){return e?.topic}function Gge(e,t){let r=null;return An(e?.publicKey,!1)||(r=Ie("MISSING_OR_INVALID",`${t} controller public key should be a string`)),r}function x1e(e){let t=!0;return El(e)?e.length&&(t=e.every(r=>An(r,!1))):t=!1,t}function Vqe(e,t,r){let n=null;return El(t)&&t.length?t.forEach(o=>{n||H7(o)||(n=Rr("UNSUPPORTED_CHAINS",`${r}, chain ${o} should be a string and conform to "namespace:chainId" format`))}):H7(e)||(n=Rr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function jqe(e,t,r){let n=null;return Object.entries(e).forEach(([o,s])=>{if(n)return;let i=Vqe(o,C1e(o,s),`${t} ${r}`);i&&(n=i)}),n}function qqe(e,t){let r=null;return El(e)?e.forEach(n=>{r||zqe(n)||(r=Rr("UNSUPPORTED_ACCOUNTS",`${t}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=Rr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function Wqe(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=qqe(n?.accounts,`${t} namespace`);o&&(r=o)}),r}function Kqe(e,t){let r=null;return x1e(e?.methods)?x1e(e?.events)||(r=Rr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Rr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}function Yge(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=Kqe(n,`${t}, namespace`);o&&(r=o)}),r}function Jge(e,t,r){let n=null;if(e&&xc(e)){let o=Yge(e,t);o&&(n=o);let s=jqe(e,t,r);s&&(n=s)}else n=Ie("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return n}function X7(e,t){let r=null;if(e&&xc(e)){let n=Yge(e,t);n&&(r=n);let o=Wqe(e,t);o&&(r=o)}else r=Ie("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function Cz(e){return An(e.protocol,!0)}function Qge(e,t){let r=!1;return t&&!e?r=!0:e&&El(e)&&e.length&&e.forEach(n=>{r=Cz(n)}),r}function Xge(e){return typeof e=="number"}function _s(e){return typeof e<"u"&&typeof e!==null}function eye(e){return!(!e||typeof e!="object"||!e.code||!Az(e.code,!1)||!e.message||!An(e.message,!1))}function tye(e){return!(Ln(e)||!An(e.method,!1))}function rye(e){return!(Ln(e)||Ln(e.result)&&Ln(e.error)||!Az(e.id,!1)||!An(e.jsonrpc,!1))}function nye(e){return!(Ln(e)||!An(e.name,!1))}function Sz(e,t){return!(!H7(t)||!vz(e).includes(t))}function oye(e,t,r){return An(r,!1)?Lqe(e,t).includes(r):!1}function sye(e,t,r){return An(r,!1)?Mqe(e,t).includes(r):!1}function Iz(e,t,r){let n=null,o=Zqe(e),s=Gqe(t),i=Object.keys(o),a=Object.keys(s),c=v1e(Object.keys(e)),u=v1e(Object.keys(t)),d=c.filter(f=>!u.includes(f));return d.length&&(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. Required: ${d.toString()} Received: ${Object.keys(t).toString()}`)),Ey(i,a)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. Required: ${i.toString()} Approved: ${a.toString()}`)),Object.keys(t).forEach(f=>{if(!f.includes(":")||n)return;let p=nx(t[f].accounts);p.includes(f)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${f} Required: ${f} - Approved: ${p.toString()}`))}),i.forEach(f=>{n||(Ey(o[f].methods,s[f].methods)?Ey(o[f].events,s[f].events)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function Zqe(e){let t={};return Object.keys(e).forEach(r=>{var n;r.includes(":")?t[r]=e[r]:(n=e[r].chains)==null||n.forEach(o=>{t[o]={methods:e[r].methods,events:e[r].events}})}),t}function v1e(e){return[...new Set(e.map(t=>t.includes(":")?t.split(":")[0]:t))]}function Gqe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:nx(e[r].accounts)?.forEach(o=>{t[o]={accounts:e[r].accounts.filter(s=>s.includes(`${o}:`)),methods:e[r].methods,events:e[r].events}})}),t}function iye(e,t){return Az(e,!1)&&e<=t.max&&e>=t.min}function Tz(){let e=N5();return new Promise(t=>{switch(e){case ji.browser:t(Yqe());break;case ji.reactNative:t(Jqe());break;case ji.node:t(Qqe());break;default:t(!0)}})}function Yqe(){return Ty()&&navigator?.onLine}async function Jqe(){return _p()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function Qqe(){return!0}function aye(e){switch(N5()){case ji.browser:Xqe(e);break;case ji.reactNative:eWe(e);break;case ji.node:break}}function Xqe(e){!_p()&&Ty()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}function eWe(e){_p()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(t=>e(t?.isConnected))}function cye(){var e;return Ty()&&(0,yl.getDocument)()?((e=(0,yl.getDocument)())==null?void 0:e.visibilityState)==="visible":!0}function tWe(e){let t=wm.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}function rWe({publicKey:e,signature:t,payload:r}){var n;let o=YF(r.method),s=128|parseInt(((n=r.version)==null?void 0:n.toString())||"4"),i=sWe(r.address),a=r.era==="00"?new Uint8Array([0]):YF(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");let c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${oWe(r.tip)}`),f=aWe(d),p=new Uint8Array([0,...e,i,...t,...a,...u,...f,...o]),h=iWe(p.length+1);return new Uint8Array([...h,s,...p])}function nWe(e){let t=YF(e),r=(0,A1e.blake2b)(t,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function YF(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(t=>parseInt(t,16)))}function oWe(e){return e.startsWith("0x")?e.slice(2):e}function sWe(e){let t=wm.decode(e)[0];return t===42?0:t===60?2:1}function iWe(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([t&255,t>>8&255])}else if(e<1<<30){let t=e<<2|2;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function aWe(e){if(e>BigInt(8)&BigInt(255))])}else if(e>BigInt(8)&BigInt(255)),Number(t>>BigInt(16)&BigInt(255)),Number(t>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function lye(e){let t=Uint8Array.from(Buffer.from(e.signature,"hex")),r=tWe(e.transaction.address),n=rWe({publicKey:r,signature:t,payload:e.transaction}),o=Buffer.from(n).toString("hex");return nWe(o)}function ox({logger:e,name:t}){let r=typeof e=="string"?Fl({opts:{level:e,name:t}}).logger:e;return r.level=typeof e=="string"?e:e.level,r}var Ip,yl,E1e,A1e,Mze,Hze,$ze,Fze,zme,zze,Vze,RF,Vme,jze,jme,qze,ji,Wze,O7,T7,qme,Wme,Kme,Bm,km,A5,C5,tVe,rVe,nVe,oVe,sVe,iVe,rz,nz,aVe,cVe,lVe,uVe,W6,M1e,Ap,Um,$1e,fVe,Ep,J6,hVe,v5,mVe,gVe,yVe,wVe,z1e,V1e,j1e,q1e,bVe,xVe,Gme,Yme,OF,EVe,AVe,k7,Tm,Es,As,TVe,_m,BF,W1e,_Ve,PVe,Pm,Nm,T5,kF,Cs,UF,q7,NVe,RVe,OVe,BVe,co,ke,DF,LF,UVe,DVe,zVe,VVe,jVe,Jme,qVe,WVe,Qme,KVe,ZVe,Q1e,GVe,YVe,W7,JVe,QVe,K7,B5,cz,cje,fje,nge,mje,gje,yje,wje,_7,bje,oge,r1e,qo,zF,Aje,Sje,Ije,n1e,Tje,_je,sge,U7,Z7,EF,s1e,Rje,G7,dz,VF,AF,U5,qi,pi,Cy,cge,lge,uge,kje,dge,Uje,fge,Hje,X6,Sy,IF,xge,qF,E5,K6,N7,Yje,f1e,Jje,Qje,Xje,vge,eqe,nqe,WF,p1e,ZF,Cp,Sp,Y6,Ege,R7,sqe,Sge,Ige,Tge,pqe,hqe,mqe,gqe,yqe,_ge,Is,Ts,Np,D5,Pge,vl,ex,wqe,h1e,S5,mz,xqe,vqe,Eqe,Aqe,m1e,Cqe,Sqe,g1e,PF,Iqe,Nqe,Rqe,Oqe,y1e,Bqe,kqe,w1e,Uqe,Dqe,$qe,Fqe,NF,$m,eP=b(()=>{l();jN();Ip=Ht(jd(),1),yl=Ht(C2(),1),E1e=Ht(JN(),1);Cme();RH();Fme();JR();B1();I8();BB();A1e=Ht(LB(),1);gh();Mze=":";Hze=Object.defineProperty,$ze=Object.defineProperties,Fze=Object.getOwnPropertyDescriptors,zme=Object.getOwnPropertySymbols,zze=Object.prototype.hasOwnProperty,Vze=Object.prototype.propertyIsEnumerable,RF=(e,t,r)=>t in e?Hze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vme=(e,t)=>{for(var r in t||(t={}))zze.call(t,r)&&RF(e,r,t[r]);if(zme)for(var r of zme(t))Vze.call(t,r)&&RF(e,r,t[r]);return e},jze=(e,t)=>$ze(e,Fze(t)),jme=(e,t,r)=>RF(e,typeof t!="symbol"?t+"":t,r),qze="ReactNative",ji={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wze="js";O7=class{constructor({limit:t}){jme(this,"limit"),jme(this,"set"),this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){let r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(t)}}has(t){return this.set.has(t)}},T7=BigInt(2**32-1),qme=BigInt(32);Wme=(e,t,r)=>e>>>r,Kme=(e,t,r)=>e<<32-r|t>>>r,Bm=(e,t,r)=>e>>>r|t<<32-r,km=(e,t,r)=>e<<32-r|t>>>r,A5=(e,t,r)=>e<<64-r|t>>>r-32,C5=(e,t,r)=>e>>>r-32|t<<64-r,tVe=(e,t)=>t,rVe=(e,t)=>e,nVe=(e,t,r)=>e<>>32-r,oVe=(e,t,r)=>t<>>32-r,sVe=(e,t,r)=>t<>>64-r,iVe=(e,t,r)=>e<>>64-r;rz=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),nz=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,aVe=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),cVe=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,lVe=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),uVe=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,W6=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;M1e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Ap=M1e?e=>e:e=>H1e(e);Um=M1e?e=>e:dVe,$1e=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fVe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Ep={_0:48,_9:57,A:65,F:70,a:97,f:102};J6=class{};hVe=BigInt(0),v5=BigInt(1),mVe=BigInt(2),gVe=BigInt(7),yVe=BigInt(256),wVe=BigInt(113),z1e=[],V1e=[],j1e=[];for(let e=0,t=v5,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],z1e.push(2*(5*n+r)),V1e.push((e+1)*(e+2)/2%64);let o=hVe;for(let s=0;s<7;s++)t=(t<>gVe)*wVe)%yVe,t&mVe&&(o^=v5<<(v5<r>32?sVe(e,t,r):nVe(e,t,r),Yme=(e,t,r)=>r>32?iVe(e,t,r):oVe(e,t,r);OF=class e extends J6{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Tp(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Tp(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(oz(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,bc(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},EVe=(e,t,r)=>O5(()=>new OF(t,e,r)),AVe=EVe(1,136,256/8);k7=class extends J6{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=bF(this.buffer)}update(t){Mm(this),t=gl(t),wl(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>>3,w=_u(h,17)^_u(h,19)^h>>>10;_m[f]=w+_m[f-7]+y+_m[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=_u(a,6)^_u(a,11)^_u(a,25),h=d+p+SVe(a,c,u)+TVe[f]+_m[f]|0,y=(_u(n,2)^_u(n,13)^_u(n,22))+IVe(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){bc(_m)}destroy(){this.set(0,0,0,0,0,0,0,0),bc(this.buffer)}},W1e=L1e(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),_Ve=W1e[0],PVe=W1e[1],Pm=new Uint32Array(80),Nm=new Uint32Array(80),T5=class extends k7{constructor(t=64){super(128,t,16,!1),this.Ah=As[0]|0,this.Al=As[1]|0,this.Bh=As[2]|0,this.Bl=As[3]|0,this.Ch=As[4]|0,this.Cl=As[5]|0,this.Dh=As[6]|0,this.Dl=As[7]|0,this.Eh=As[8]|0,this.El=As[9]|0,this.Fh=As[10]|0,this.Fl=As[11]|0,this.Gh=As[12]|0,this.Gl=As[13]|0,this.Hh=As[14]|0,this.Hl=As[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)Pm[E]=t.getUint32(r),Nm[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Pm[E-15]|0,_=Nm[E-15]|0,O=Bm(S,_,1)^Bm(S,_,8)^Wme(S,_,7),D=km(S,_,1)^km(S,_,8)^Kme(S,_,7),M=Pm[E-2]|0,N=Nm[E-2]|0,L=Bm(M,N,19)^A5(M,N,61)^Wme(M,N,6),P=km(M,N,19)^C5(M,N,61)^Kme(M,N,6),R=aVe(D,P,Nm[E-7],Nm[E-16]),I=cVe(R,O,L,Pm[E-7],Pm[E-16]);Pm[E]=I|0,Nm[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Bm(f,p,14)^Bm(f,p,18)^A5(f,p,41),_=km(f,p,14)^km(f,p,18)^C5(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=lVe(T,_,D,PVe[E],Nm[E]),N=uVe(M,v,S,O,_Ve[E],Pm[E]),L=M|0,P=Bm(n,o,28)^A5(n,o,34)^A5(n,o,39),R=km(n,o,28)^C5(n,o,34)^C5(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=hl(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=rz(L,R,B);n=nz(C,N,P,I),o=C|0}({h:n,l:o}=hl(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=hl(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=hl(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=hl(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=hl(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=hl(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=hl(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=hl(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){bc(Pm,Nm)}destroy(){bc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},kF=class extends T5{constructor(){super(48),this.Ah=Es[0]|0,this.Al=Es[1]|0,this.Bh=Es[2]|0,this.Bl=Es[3]|0,this.Ch=Es[4]|0,this.Cl=Es[5]|0,this.Dh=Es[6]|0,this.Dl=Es[7]|0,this.Eh=Es[8]|0,this.El=Es[9]|0,this.Fh=Es[10]|0,this.Fl=Es[11]|0,this.Gh=Es[12]|0,this.Gl=Es[13]|0,this.Hh=Es[14]|0,this.Hl=Es[15]|0}},Cs=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),UF=class extends T5{constructor(){super(32),this.Ah=Cs[0]|0,this.Al=Cs[1]|0,this.Bh=Cs[2]|0,this.Bl=Cs[3]|0,this.Ch=Cs[4]|0,this.Cl=Cs[5]|0,this.Dh=Cs[6]|0,this.Dl=Cs[7]|0,this.Eh=Cs[8]|0,this.El=Cs[9]|0,this.Fh=Cs[10]|0,this.Fl=Cs[11]|0,this.Gh=Cs[12]|0,this.Gl=Cs[13]|0,this.Hh=Cs[14]|0,this.Hl=Cs[15]|0}},q7=O5(()=>new BF),NVe=O5(()=>new T5),RVe=O5(()=>new kF),OVe=O5(()=>new UF),BVe=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),co=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ke=new Uint32Array(32);DF=class extends J6{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Tp(t),Tp(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=I5(this.buffer)}update(t){Mm(this),t=gl(t),wl(t);let{blockLen:r,buffer:n,buffer32:o}=this,s=t.length,i=t.byteOffset,a=t.buffer;for(let c=0;co[i]=Ap(s))}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){let{buffer:r,length:n,finished:o,destroyed:s,outputLen:i,pos:a}=this;return t||(t=new this.constructor({dkLen:i})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=o,t.length=n,t.pos=a,t.outputLen=i,t}clone(){return this._cloneInto()}},LF=class extends DF{constructor(t={}){let r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=co[0]|0,this.v0h=co[1]|0,this.v1l=co[2]|0,this.v1h=co[3]|0,this.v2l=co[4]|0,this.v2h=co[5]|0,this.v3l=co[6]|0,this.v3h=co[7]|0,this.v4l=co[8]|0,this.v4h=co[9]|0,this.v5l=co[10]|0,this.v5h=co[11]|0,this.v6l=co[12]|0,this.v6h=co[13]|0,this.v7l=co[14]|0,this.v7h=co[15]|0,kVe(r,t,64,16,16);let{key:n,personalization:o,salt:s}=t,i=0;if(n!==void 0&&(n=gl(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){s=gl(s);let a=I5(s);this.v4l^=Ap(a[0]),this.v4h^=Ap(a[1]),this.v5l^=Ap(a[2]),this.v5h^=Ap(a[3])}if(o!==void 0){o=gl(o);let a=I5(o);this.v6l^=Ap(a[0]),this.v6h^=Ap(a[1]),this.v7l^=Ap(a[2]),this.v7h^=Ap(a[3])}if(n!==void 0){let a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:u,v4h:d,v5l:f,v5h:p,v6l:h,v6h:y,v7l:w,v7h:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=d|0,this.v5l=f|0,this.v5h=p|0,this.v6l=h|0,this.v6h=y|0,this.v7l=w|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>ke[u]=c),ke.set(co,16);let{h:o,l:s}=D1e(BigInt(this.length));ke[24]=co[8]^s,ke[25]=co[9]^o,n&&(ke[28]=~ke[28],ke[29]=~ke[29]);let i=0,a=BVe;for(let c=0;c<12;c++)Rm(0,4,8,12,t,r+2*a[i++]),Om(0,4,8,12,t,r+2*a[i++]),Rm(1,5,9,13,t,r+2*a[i++]),Om(1,5,9,13,t,r+2*a[i++]),Rm(2,6,10,14,t,r+2*a[i++]),Om(2,6,10,14,t,r+2*a[i++]),Rm(3,7,11,15,t,r+2*a[i++]),Om(3,7,11,15,t,r+2*a[i++]),Rm(0,5,10,15,t,r+2*a[i++]),Om(0,5,10,15,t,r+2*a[i++]),Rm(1,6,11,12,t,r+2*a[i++]),Om(1,6,11,12,t,r+2*a[i++]),Rm(2,7,8,13,t,r+2*a[i++]),Om(2,7,8,13,t,r+2*a[i++]),Rm(3,4,9,14,t,r+2*a[i++]),Om(3,4,9,14,t,r+2*a[i++]);this.v0l^=ke[0]^ke[16],this.v0h^=ke[1]^ke[17],this.v1l^=ke[2]^ke[18],this.v1h^=ke[3]^ke[19],this.v2l^=ke[4]^ke[20],this.v2h^=ke[5]^ke[21],this.v3l^=ke[6]^ke[22],this.v3h^=ke[7]^ke[23],this.v4l^=ke[8]^ke[24],this.v4h^=ke[9]^ke[25],this.v5l^=ke[10]^ke[26],this.v5h^=ke[11]^ke[27],this.v6l^=ke[12]^ke[28],this.v6h^=ke[13]^ke[29],this.v7l^=ke[14]^ke[30],this.v7h^=ke[15]^ke[31],bc(ke)}destroy(){this.destroyed=!0,bc(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},UVe=pVe(e=>new LF(e)),DVe="https://rpc.walletconnect.org/v1";zVe=Object.defineProperty,VVe=Object.defineProperties,jVe=Object.getOwnPropertyDescriptors,Jme=Object.getOwnPropertySymbols,qVe=Object.prototype.hasOwnProperty,WVe=Object.prototype.propertyIsEnumerable,Qme=(e,t,r)=>t in e?zVe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,KVe=(e,t)=>{for(var r in t||(t={}))qVe.call(t,r)&&Qme(e,r,t[r]);if(Jme)for(var r of Jme(t))WVe.call(t,r)&&Qme(e,r,t[r]);return e},ZVe=(e,t)=>VVe(e,jVe(t)),Q1e="did:pkh:",GVe={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},YVe=e=>e?GVe[e]||e:"",W7=e=>e?.split(":"),JVe=e=>{let t=e&&W7(e);if(t)return e.includes(Q1e)?t[3]:t[1]},QVe=e=>{let t=e&&W7(e);if(t)return e.includes(Q1e)?t[2]:t[0]},K7=e=>{let t=e&&W7(e);if(t)return t[2]+":"+t[3]},B5=e=>{let t=e&&W7(e);if(t)return t.pop()};cz=(e,t)=>{let r=QVe(t);if(!r)throw new Error("Invalid issuer: "+t);let n=`${e.domain} wants you to sign in with your ${YVe(r)} account:`,o=B5(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0,i=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${JVe(t)}`,u=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,f=e.exp?`Expiration Time: ${e.exp}`:void 0,p=e.nbf?`Not Before: ${e.nbf}`:void 0,h=e.requestId?`Request ID: ${e.requestId}`:void 0,y=e.resources?`Resources:${e.resources.map(x=>` + Approved: ${p.toString()}`))}),i.forEach(f=>{n||(Ey(o[f].methods,s[f].methods)?Ey(o[f].events,s[f].events)||(n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=Ie("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function Zqe(e){let t={};return Object.keys(e).forEach(r=>{var n;r.includes(":")?t[r]=e[r]:(n=e[r].chains)==null||n.forEach(o=>{t[o]={methods:e[r].methods,events:e[r].events}})}),t}function v1e(e){return[...new Set(e.map(t=>t.includes(":")?t.split(":")[0]:t))]}function Gqe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:nx(e[r].accounts)?.forEach(o=>{t[o]={accounts:e[r].accounts.filter(s=>s.includes(`${o}:`)),methods:e[r].methods,events:e[r].events}})}),t}function iye(e,t){return Az(e,!1)&&e<=t.max&&e>=t.min}function Tz(){let e=N5();return new Promise(t=>{switch(e){case qi.browser:t(Yqe());break;case qi.reactNative:t(Jqe());break;case qi.node:t(Qqe());break;default:t(!0)}})}function Yqe(){return Ty()&&navigator?.onLine}async function Jqe(){return _p()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function Qqe(){return!0}function aye(e){switch(N5()){case qi.browser:Xqe(e);break;case qi.reactNative:eWe(e);break;case qi.node:break}}function Xqe(e){!_p()&&Ty()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}function eWe(e){_p()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(t=>e(t?.isConnected))}function cye(){var e;return Ty()&&(0,yl.getDocument)()?((e=(0,yl.getDocument)())==null?void 0:e.visibilityState)==="visible":!0}function tWe(e){let t=wm.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}function rWe({publicKey:e,signature:t,payload:r}){var n;let o=YF(r.method),s=128|parseInt(((n=r.version)==null?void 0:n.toString())||"4"),i=sWe(r.address),a=r.era==="00"?new Uint8Array([0]):YF(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");let c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${oWe(r.tip)}`),f=aWe(d),p=new Uint8Array([0,...e,i,...t,...a,...u,...f,...o]),h=iWe(p.length+1);return new Uint8Array([...h,s,...p])}function nWe(e){let t=YF(e),r=(0,A1e.blake2b)(t,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function YF(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(t=>parseInt(t,16)))}function oWe(e){return e.startsWith("0x")?e.slice(2):e}function sWe(e){let t=wm.decode(e)[0];return t===42?0:t===60?2:1}function iWe(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([t&255,t>>8&255])}else if(e<1<<30){let t=e<<2|2;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function aWe(e){if(e>BigInt(8)&BigInt(255))])}else if(e>BigInt(8)&BigInt(255)),Number(t>>BigInt(16)&BigInt(255)),Number(t>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function lye(e){let t=Uint8Array.from(Buffer.from(e.signature,"hex")),r=tWe(e.transaction.address),n=rWe({publicKey:r,signature:t,payload:e.transaction}),o=Buffer.from(n).toString("hex");return nWe(o)}function ox({logger:e,name:t}){let r=typeof e=="string"?Fl({opts:{level:e,name:t}}).logger:e;return r.level=typeof e=="string"?e:e.level,r}var Ip,yl,E1e,A1e,Mze,Hze,$ze,Fze,zme,zze,Vze,RF,Vme,jze,jme,qze,qi,Wze,O7,T7,qme,Wme,Kme,Bm,km,A5,C5,tVe,rVe,nVe,oVe,sVe,iVe,rz,nz,aVe,cVe,lVe,uVe,W6,M1e,Ap,Um,$1e,fVe,Ep,J6,hVe,v5,mVe,gVe,yVe,wVe,z1e,V1e,j1e,q1e,bVe,xVe,Gme,Yme,OF,EVe,AVe,k7,Tm,Es,As,TVe,_m,BF,W1e,_Ve,PVe,Pm,Nm,T5,kF,Cs,UF,q7,NVe,RVe,OVe,BVe,co,ke,DF,LF,UVe,DVe,zVe,VVe,jVe,Jme,qVe,WVe,Qme,KVe,ZVe,Q1e,GVe,YVe,W7,JVe,QVe,K7,B5,cz,cje,fje,nge,mje,gje,yje,wje,_7,bje,oge,r1e,qo,zF,Aje,Sje,Ije,n1e,Tje,_je,sge,U7,Z7,EF,s1e,Rje,G7,dz,VF,AF,U5,Wi,pi,Cy,cge,lge,uge,kje,dge,Uje,fge,Hje,X6,Sy,IF,xge,qF,E5,K6,N7,Yje,f1e,Jje,Qje,Xje,vge,eqe,nqe,WF,p1e,ZF,Cp,Sp,Y6,Ege,R7,sqe,Sge,Ige,Tge,pqe,hqe,mqe,gqe,yqe,_ge,Is,Ts,Np,D5,Pge,vl,ex,wqe,h1e,S5,mz,xqe,vqe,Eqe,Aqe,m1e,Cqe,Sqe,g1e,PF,Iqe,Nqe,Rqe,Oqe,y1e,Bqe,kqe,w1e,Uqe,Dqe,$qe,Fqe,NF,$m,eP=b(()=>{l();jN();Ip=Ht(jd(),1),yl=Ht(C2(),1),E1e=Ht(JN(),1);Cme();RH();Fme();JR();B1();I8();BB();A1e=Ht(LB(),1);gh();Mze=":";Hze=Object.defineProperty,$ze=Object.defineProperties,Fze=Object.getOwnPropertyDescriptors,zme=Object.getOwnPropertySymbols,zze=Object.prototype.hasOwnProperty,Vze=Object.prototype.propertyIsEnumerable,RF=(e,t,r)=>t in e?Hze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vme=(e,t)=>{for(var r in t||(t={}))zze.call(t,r)&&RF(e,r,t[r]);if(zme)for(var r of zme(t))Vze.call(t,r)&&RF(e,r,t[r]);return e},jze=(e,t)=>$ze(e,Fze(t)),jme=(e,t,r)=>RF(e,typeof t!="symbol"?t+"":t,r),qze="ReactNative",qi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wze="js";O7=class{constructor({limit:t}){jme(this,"limit"),jme(this,"set"),this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){let r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(t)}}has(t){return this.set.has(t)}},T7=BigInt(2**32-1),qme=BigInt(32);Wme=(e,t,r)=>e>>>r,Kme=(e,t,r)=>e<<32-r|t>>>r,Bm=(e,t,r)=>e>>>r|t<<32-r,km=(e,t,r)=>e<<32-r|t>>>r,A5=(e,t,r)=>e<<64-r|t>>>r-32,C5=(e,t,r)=>e>>>r-32|t<<64-r,tVe=(e,t)=>t,rVe=(e,t)=>e,nVe=(e,t,r)=>e<>>32-r,oVe=(e,t,r)=>t<>>32-r,sVe=(e,t,r)=>t<>>64-r,iVe=(e,t,r)=>e<>>64-r;rz=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),nz=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,aVe=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),cVe=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,lVe=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),uVe=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,W6=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;M1e=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Ap=M1e?e=>e:e=>H1e(e);Um=M1e?e=>e:dVe,$1e=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fVe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Ep={_0:48,_9:57,A:65,F:70,a:97,f:102};J6=class{};hVe=BigInt(0),v5=BigInt(1),mVe=BigInt(2),gVe=BigInt(7),yVe=BigInt(256),wVe=BigInt(113),z1e=[],V1e=[],j1e=[];for(let e=0,t=v5,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],z1e.push(2*(5*n+r)),V1e.push((e+1)*(e+2)/2%64);let o=hVe;for(let s=0;s<7;s++)t=(t<>gVe)*wVe)%yVe,t&mVe&&(o^=v5<<(v5<r>32?sVe(e,t,r):nVe(e,t,r),Yme=(e,t,r)=>r>32?iVe(e,t,r):oVe(e,t,r);OF=class e extends J6{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Tp(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Tp(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(oz(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,bc(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},EVe=(e,t,r)=>O5(()=>new OF(t,e,r)),AVe=EVe(1,136,256/8);k7=class extends J6{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=bF(this.buffer)}update(t){Mm(this),t=gl(t),wl(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>>3,w=_u(h,17)^_u(h,19)^h>>>10;_m[f]=w+_m[f-7]+y+_m[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=_u(a,6)^_u(a,11)^_u(a,25),h=d+p+SVe(a,c,u)+TVe[f]+_m[f]|0,y=(_u(n,2)^_u(n,13)^_u(n,22))+IVe(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){bc(_m)}destroy(){this.set(0,0,0,0,0,0,0,0),bc(this.buffer)}},W1e=L1e(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),_Ve=W1e[0],PVe=W1e[1],Pm=new Uint32Array(80),Nm=new Uint32Array(80),T5=class extends k7{constructor(t=64){super(128,t,16,!1),this.Ah=As[0]|0,this.Al=As[1]|0,this.Bh=As[2]|0,this.Bl=As[3]|0,this.Ch=As[4]|0,this.Cl=As[5]|0,this.Dh=As[6]|0,this.Dl=As[7]|0,this.Eh=As[8]|0,this.El=As[9]|0,this.Fh=As[10]|0,this.Fl=As[11]|0,this.Gh=As[12]|0,this.Gl=As[13]|0,this.Hh=As[14]|0,this.Hl=As[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)Pm[E]=t.getUint32(r),Nm[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Pm[E-15]|0,_=Nm[E-15]|0,O=Bm(S,_,1)^Bm(S,_,8)^Wme(S,_,7),D=km(S,_,1)^km(S,_,8)^Kme(S,_,7),M=Pm[E-2]|0,N=Nm[E-2]|0,L=Bm(M,N,19)^A5(M,N,61)^Wme(M,N,6),P=km(M,N,19)^C5(M,N,61)^Kme(M,N,6),R=aVe(D,P,Nm[E-7],Nm[E-16]),I=cVe(R,O,L,Pm[E-7],Pm[E-16]);Pm[E]=I|0,Nm[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Bm(f,p,14)^Bm(f,p,18)^A5(f,p,41),_=km(f,p,14)^km(f,p,18)^C5(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=lVe(T,_,D,PVe[E],Nm[E]),N=uVe(M,v,S,O,_Ve[E],Pm[E]),L=M|0,P=Bm(n,o,28)^A5(n,o,34)^A5(n,o,39),R=km(n,o,28)^C5(n,o,34)^C5(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=hl(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=rz(L,R,B);n=nz(C,N,P,I),o=C|0}({h:n,l:o}=hl(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=hl(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=hl(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=hl(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=hl(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=hl(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=hl(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=hl(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){bc(Pm,Nm)}destroy(){bc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},kF=class extends T5{constructor(){super(48),this.Ah=Es[0]|0,this.Al=Es[1]|0,this.Bh=Es[2]|0,this.Bl=Es[3]|0,this.Ch=Es[4]|0,this.Cl=Es[5]|0,this.Dh=Es[6]|0,this.Dl=Es[7]|0,this.Eh=Es[8]|0,this.El=Es[9]|0,this.Fh=Es[10]|0,this.Fl=Es[11]|0,this.Gh=Es[12]|0,this.Gl=Es[13]|0,this.Hh=Es[14]|0,this.Hl=Es[15]|0}},Cs=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),UF=class extends T5{constructor(){super(32),this.Ah=Cs[0]|0,this.Al=Cs[1]|0,this.Bh=Cs[2]|0,this.Bl=Cs[3]|0,this.Ch=Cs[4]|0,this.Cl=Cs[5]|0,this.Dh=Cs[6]|0,this.Dl=Cs[7]|0,this.Eh=Cs[8]|0,this.El=Cs[9]|0,this.Fh=Cs[10]|0,this.Fl=Cs[11]|0,this.Gh=Cs[12]|0,this.Gl=Cs[13]|0,this.Hh=Cs[14]|0,this.Hl=Cs[15]|0}},q7=O5(()=>new BF),NVe=O5(()=>new T5),RVe=O5(()=>new kF),OVe=O5(()=>new UF),BVe=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),co=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ke=new Uint32Array(32);DF=class extends J6{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Tp(t),Tp(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=I5(this.buffer)}update(t){Mm(this),t=gl(t),wl(t);let{blockLen:r,buffer:n,buffer32:o}=this,s=t.length,i=t.byteOffset,a=t.buffer;for(let c=0;co[i]=Ap(s))}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){let{buffer:r,length:n,finished:o,destroyed:s,outputLen:i,pos:a}=this;return t||(t=new this.constructor({dkLen:i})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=o,t.length=n,t.pos=a,t.outputLen=i,t}clone(){return this._cloneInto()}},LF=class extends DF{constructor(t={}){let r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=co[0]|0,this.v0h=co[1]|0,this.v1l=co[2]|0,this.v1h=co[3]|0,this.v2l=co[4]|0,this.v2h=co[5]|0,this.v3l=co[6]|0,this.v3h=co[7]|0,this.v4l=co[8]|0,this.v4h=co[9]|0,this.v5l=co[10]|0,this.v5h=co[11]|0,this.v6l=co[12]|0,this.v6h=co[13]|0,this.v7l=co[14]|0,this.v7h=co[15]|0,kVe(r,t,64,16,16);let{key:n,personalization:o,salt:s}=t,i=0;if(n!==void 0&&(n=gl(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){s=gl(s);let a=I5(s);this.v4l^=Ap(a[0]),this.v4h^=Ap(a[1]),this.v5l^=Ap(a[2]),this.v5h^=Ap(a[3])}if(o!==void 0){o=gl(o);let a=I5(o);this.v6l^=Ap(a[0]),this.v6h^=Ap(a[1]),this.v7l^=Ap(a[2]),this.v7h^=Ap(a[3])}if(n!==void 0){let a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:u,v4h:d,v5l:f,v5h:p,v6l:h,v6h:y,v7l:w,v7h:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=d|0,this.v5l=f|0,this.v5h=p|0,this.v6l=h|0,this.v6h=y|0,this.v7l=w|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>ke[u]=c),ke.set(co,16);let{h:o,l:s}=D1e(BigInt(this.length));ke[24]=co[8]^s,ke[25]=co[9]^o,n&&(ke[28]=~ke[28],ke[29]=~ke[29]);let i=0,a=BVe;for(let c=0;c<12;c++)Rm(0,4,8,12,t,r+2*a[i++]),Om(0,4,8,12,t,r+2*a[i++]),Rm(1,5,9,13,t,r+2*a[i++]),Om(1,5,9,13,t,r+2*a[i++]),Rm(2,6,10,14,t,r+2*a[i++]),Om(2,6,10,14,t,r+2*a[i++]),Rm(3,7,11,15,t,r+2*a[i++]),Om(3,7,11,15,t,r+2*a[i++]),Rm(0,5,10,15,t,r+2*a[i++]),Om(0,5,10,15,t,r+2*a[i++]),Rm(1,6,11,12,t,r+2*a[i++]),Om(1,6,11,12,t,r+2*a[i++]),Rm(2,7,8,13,t,r+2*a[i++]),Om(2,7,8,13,t,r+2*a[i++]),Rm(3,4,9,14,t,r+2*a[i++]),Om(3,4,9,14,t,r+2*a[i++]);this.v0l^=ke[0]^ke[16],this.v0h^=ke[1]^ke[17],this.v1l^=ke[2]^ke[18],this.v1h^=ke[3]^ke[19],this.v2l^=ke[4]^ke[20],this.v2h^=ke[5]^ke[21],this.v3l^=ke[6]^ke[22],this.v3h^=ke[7]^ke[23],this.v4l^=ke[8]^ke[24],this.v4h^=ke[9]^ke[25],this.v5l^=ke[10]^ke[26],this.v5h^=ke[11]^ke[27],this.v6l^=ke[12]^ke[28],this.v6h^=ke[13]^ke[29],this.v7l^=ke[14]^ke[30],this.v7h^=ke[15]^ke[31],bc(ke)}destroy(){this.destroyed=!0,bc(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},UVe=pVe(e=>new LF(e)),DVe="https://rpc.walletconnect.org/v1";zVe=Object.defineProperty,VVe=Object.defineProperties,jVe=Object.getOwnPropertyDescriptors,Jme=Object.getOwnPropertySymbols,qVe=Object.prototype.hasOwnProperty,WVe=Object.prototype.propertyIsEnumerable,Qme=(e,t,r)=>t in e?zVe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,KVe=(e,t)=>{for(var r in t||(t={}))qVe.call(t,r)&&Qme(e,r,t[r]);if(Jme)for(var r of Jme(t))WVe.call(t,r)&&Qme(e,r,t[r]);return e},ZVe=(e,t)=>VVe(e,jVe(t)),Q1e="did:pkh:",GVe={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},YVe=e=>e?GVe[e]||e:"",W7=e=>e?.split(":"),JVe=e=>{let t=e&&W7(e);if(t)return e.includes(Q1e)?t[3]:t[1]},QVe=e=>{let t=e&&W7(e);if(t)return e.includes(Q1e)?t[2]:t[0]},K7=e=>{let t=e&&W7(e);if(t)return t[2]+":"+t[3]},B5=e=>{let t=e&&W7(e);if(t)return t.pop()};cz=(e,t)=>{let r=QVe(t);if(!r)throw new Error("Invalid issuer: "+t);let n=`${e.domain} wants you to sign in with your ${YVe(r)} account:`,o=B5(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0,i=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${JVe(t)}`,u=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,f=e.exp?`Expiration Time: ${e.exp}`:void 0,p=e.nbf?`Not Before: ${e.nbf}`:void 0,h=e.requestId?`Request ID: ${e.requestId}`:void 0,y=e.resources?`Resources:${e.resources.map(x=>` - ${x}`).join("")}`:void 0,w=k5(e.resources);if(w){let x=_5(w);s=sje(s,x)}return[n,o,"",s,"",i,a,c,u,d,f,p,h,y].filter(x=>x!=null).join(` -`)};cje=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;fje=(e,t)=>{function r(n,...o){if(Vi(n),!cje)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");e.varSizeNonce?Vi(u):Vi(u,e.nonceLength)}let s=e.tagLength;s&&o[1]!==void 0&&Vi(o[1]);let i=t(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Vi(d)}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Vi(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(Vi(u),s&&u.lengtht.charCodeAt(0))),mje=nge("expand 16-byte k"),gje=nge("expand 32-byte k"),yje=Lm(mje),wje=Lm(gje);_7=64,bje=16,oge=2**32-1,r1e=new Uint32Array;qo=(e,t)=>e[t++]&255|(e[t++]&255)<<8,zF=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=HF(t),Vi(t,32);let r=qo(t,0),n=qo(t,2),o=qo(t,4),s=qo(t,6),i=qo(t,8),a=qo(t,10),c=qo(t,12),u=qo(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=qo(t,16+2*d)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],d=i[3],f=i[4],p=i[5],h=i[6],y=i[7],w=i[8],x=i[9],v=qo(t,r+0),T=qo(t,r+2),E=qo(t,r+4),S=qo(t,r+6),_=qo(t,r+8),O=qo(t,r+10),D=qo(t,r+12),M=qo(t,r+14),N=s[0]+(v&8191),L=s[1]+((v>>>13|T<<3)&8191),P=s[2]+((T>>>10|E<<6)&8191),R=s[3]+((E>>>7|S<<9)&8191),I=s[4]+((S>>>4|_<<12)&8191),B=s[5]+(_>>>1&8191),C=s[6]+((_>>>14|O<<2)&8191),A=s[7]+((O>>>11|D<<5)&8191),U=s[8]+((D>>>8|M<<8)&8191),H=s[9]+(M>>>5|o),k=0,F=k+N*a+L*(5*x)+P*(5*w)+R*(5*y)+I*(5*h);k=F>>>13,F&=8191,F+=B*(5*p)+C*(5*f)+A*(5*d)+U*(5*u)+H*(5*c),k+=F>>>13,F&=8191;let j=k+N*c+L*a+P*(5*x)+R*(5*w)+I*(5*y);k=j>>>13,j&=8191,j+=B*(5*h)+C*(5*p)+A*(5*f)+U*(5*d)+H*(5*u),k+=j>>>13,j&=8191;let W=k+N*u+L*c+P*a+R*(5*x)+I*(5*w);k=W>>>13,W&=8191,W+=B*(5*y)+C*(5*h)+A*(5*p)+U*(5*f)+H*(5*d),k+=W>>>13,W&=8191;let ae=k+N*d+L*u+P*c+R*a+I*(5*x);k=ae>>>13,ae&=8191,ae+=B*(5*w)+C*(5*y)+A*(5*h)+U*(5*p)+H*(5*f),k+=ae>>>13,ae&=8191;let te=k+N*f+L*d+P*u+R*c+I*a;k=te>>>13,te&=8191,te+=B*(5*x)+C*(5*w)+A*(5*y)+U*(5*h)+H*(5*p),k+=te>>>13,te&=8191;let X=k+N*p+L*f+P*d+R*u+I*c;k=X>>>13,X&=8191,X+=B*a+C*(5*x)+A*(5*w)+U*(5*y)+H*(5*h),k+=X>>>13,X&=8191;let pe=k+N*h+L*p+P*f+R*d+I*u;k=pe>>>13,pe&=8191,pe+=B*c+C*a+A*(5*x)+U*(5*w)+H*(5*y),k+=pe>>>13,pe&=8191;let me=k+N*y+L*h+P*p+R*f+I*d;k=me>>>13,me&=8191,me+=B*u+C*c+A*a+U*(5*x)+H*(5*w),k+=me>>>13,me&=8191;let Ne=k+N*w+L*y+P*h+R*p+I*f;k=Ne>>>13,Ne&=8191,Ne+=B*d+C*u+A*c+U*a+H*(5*x),k+=Ne>>>13,Ne&=8191;let ye=k+N*x+L*w+P*y+R*h+I*p;k=ye>>>13,ye&=8191,ye+=B*f+C*d+A*u+U*c+H*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+F|0,F=k&8191,k=k>>>13,j+=k,s[0]=F,s[1]=j,s[2]=W,s[3]=ae,s[4]=te,s[5]=X,s[6]=pe,s[7]=me,s[8]=Ne,s[9]=ye}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;Q6(n)}update(t){Xme(this),t=HF(t),Vi(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};Aje=Eje(e=>new zF(e));Sje=vje(Cje,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ije=new Uint8Array(16),n1e=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ije.subarray(r))},Tje=new Uint8Array(32);_je=e=>(t,r,n)=>({encrypt(o,s){let i=o.length;s=e1e(i+16,s,!1),s.set(o);let a=s.subarray(0,-16);e(t,r,a,a,1);let c=o1e(e,t,r,a,n);return s.set(c,i),Q6(c),s},decrypt(o,s){s=e1e(o.length-16,s,!1);let i=o.subarray(0,-16),a=o.subarray(-16),c=o1e(e,t,r,i,n);if(!dje(a,c))throw new Error("invalid tag");return s.set(o.subarray(0,-16)),e(t,r,s,s,1),Q6(c),s}}),sge=fje({blockSize:64,nonceLength:12,tagLength:16},_je(Sje)),U7=class extends J6{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,j7(t);let n=gl(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew U7(e,t).update(r).digest();Z7.create=(e,t)=>new U7(e,t);EF=Uint8Array.from([0]),s1e=Uint8Array.of();Rje=(e,t,r,n,o)=>Nje(e,Pje(e,t,r),n,o),G7=q7,dz=BigInt(0),VF=BigInt(1);AF=e=>typeof e=="bigint"&&dz<=e;U5=e=>(VF<X6;)r&Sy&&(n=n.add(o)),o=o.double(),r>>=Sy;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=SF(r,this.bits),s=[],i=t,a=i;for(let c=0;c{let e=nqe.ORDER;return Gje({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=tqe(t);return Ba(pl(r,Jje,e)*n,e)},adjustScalarBytes:rqe})})(),p1e=(e,t)=>(e+(e>=0?t:-t)/Ege)/t;ZF=class extends Error{constructor(t=""){super(t)}},Cp={Err:ZF,_tlv:{encode:(e,t)=>{let{Err:r}=Cp;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=P7(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?P7(o.length/2|128):"";return P7(e)+s+o+t},decode(e,t){let{Err:r}=Cp,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Cp;if(et in e?vqe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,PF=(e,t)=>{for(var r in t||(t={}))Cqe.call(t,r)&&g1e(e,r,t[r]);if(m1e)for(var r of m1e(t))Sqe.call(t,r)&&g1e(e,r,t[r]);return e},Iqe=(e,t)=>Eqe(e,Aqe(t));Nqe=Object.defineProperty,Rqe=Object.defineProperties,Oqe=Object.getOwnPropertyDescriptors,y1e=Object.getOwnPropertySymbols,Bqe=Object.prototype.hasOwnProperty,kqe=Object.prototype.propertyIsEnumerable,w1e=(e,t,r)=>t in e?Nqe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Uqe=(e,t)=>{for(var r in t||(t={}))Bqe.call(t,r)&&w1e(e,r,t[r]);if(y1e)for(var r of y1e(t))kqe.call(t,r)&&w1e(e,r,t[r]);return e},Dqe=(e,t)=>Rqe(e,Oqe(t));$qe={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Fqe={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};NF={},$m=class{static get(t){return NF[t]}static set(t,r){NF[t]=r}static delete(t){delete NF[t]}}});function zWe(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}function PKe(e){return e.reduce((t,r)=>(t+=TKe[r],t),"")}function NKe(e){let t=[];for(let r of e){let n=_Ke[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}function zye(e,t,r){t=t||[],r=r||0;for(var n=r;e>=DKe;)t[r++]=e&255|fye,e/=128;for(;e&UKe;)t[r++]=e&255|fye,e>>>=7;return t[r]=e|0,zye.bytes=r-n+1,t}function Dz(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Dz.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&pye)<=MKe);return Dz.bytes=s-n,r}function Zye(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function nZe(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zye(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Gye(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}function sZe(e,t="utf8"){let r=oZe[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zye(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function OZe(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Cye(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function Sye(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}function nGe(){}function Tye(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function oGe(e,t,r){return V5(e,t,void 0,void 0,void 0,void 0,r)}function V5(e,t,r,n,o,s,i){let a=i(e,t,r,n,o,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return j5(e,t,s,i)}return j5(e,t,s,i)}function j5(e,t,r,n){if(Object.is(e,t))return!0;let o=Sye(e),s=Sye(t);if(o===Iye&&(o=Nz),s===Iye&&(s=Nz),o!==s)return!1;switch(o){case kZe:return e.toString()===t.toString();case UZe:{let c=e.valueOf(),u=t.valueOf();return OZe(c,u)}case DZe:case MZe:case LZe:return Object.is(e.valueOf(),t.valueOf());case BZe:return e.source===t.source&&e.flags===t.flags;case zZe:return e===t}r=r??new Map;let i=r.get(e),a=r.get(t);if(i!=null&&a!=null)return i===t;r.set(e,t),r.set(t,e);try{switch(o){case HZe:{if(e.size!==t.size)return!1;for(let[c,u]of e.entries())if(!t.has(c)||!V5(u,t.get(c),c,e,t,r,n))return!1;return!0}case $Ze:{if(e.size!==t.size)return!1;let c=Array.from(e.values()),u=Array.from(t.values());for(let d=0;dV5(f,h,void 0,e,t,r,n));if(p===-1)return!1;u.splice(p,1)}return!0}case FZe:case WZe:case KZe:case ZZe:case GZe:case YZe:case JZe:case QZe:case XZe:case eGe:case tGe:case rGe:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c{l();Rp=Ht(ks(),1);vk();Rk();gh();DH();Xe=Ht(jd(),1);R1();B1();B1();eP();I8();cw();$c();Hk();kye=Ht(C2(),1),Uye="wc",Dye=2,rP="core",Ru=`${Uye}@2:${rP}:`,cWe={name:rP,logger:"error"},lWe={database:":memory:"},uWe="crypto",uye="client_ed25519_seed",dWe=Xe.ONE_DAY,fWe="keychain",pWe="0.3",hWe="messages",mWe="0.3",gWe=Xe.SIX_HOURS,yWe="publisher",aV="irn",wWe="error",Lye="wss://relay.walletconnect.org",bWe="relayer",Mn={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},xWe="_subscription",vc={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},vWe=.1,Rz="2.23.2",Vr={link_mode:"link_mode",relay:"relay"},tP={inbound:"inbound",outbound:"outbound"},EWe="0.3",AWe="WALLETCONNECT_CLIENT_ID",dye="WALLETCONNECT_LINK_MODE_APPS",Da={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},CWe="subscription",SWe="0.3",Mdr=Xe.FIVE_SECONDS*1e3,IWe="pairing",TWe="0.3",$5={wc_pairingDelete:{req:{ttl:Xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:Xe.ONE_DAY,prompt:!1,tag:0}}},zm={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Al={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},_We="history",PWe="0.3",NWe="expirer",La={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},RWe="0.3",OWe="verify-api",BWe="https://verify.walletconnect.com",Mye="https://verify.walletconnect.org",ax=Mye,kWe=`${ax}/v3`,UWe=[BWe,Mye],DWe="echo",LWe="https://echo.walletconnect.com",Cl={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Nu={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Ac={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Vm={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},jm={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},cx={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},MWe=.1,HWe="event-client",$We=86400,FWe="https://pulse.walletconnect.org/batch";VWe=zWe,jWe=VWe,Hye=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},qWe=e=>new TextEncoder().encode(e),WWe=e=>new TextDecoder().decode(e),Oz=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Bz=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $ye(this,t)}},kz=class{constructor(t){this.decoders=t}or(t){return $ye(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},$ye=(e,t)=>new kz({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),Uz=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Oz(t,r,n),this.decoder=new Bz(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},nP=({name:e,prefix:t,encode:r,decode:n})=>new Uz(e,t,r,n),q5=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=jWe(r,t);return nP({prefix:e,name:t,encode:n,decode:s=>Hye(o(s))})},KWe=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},ZWe=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<nP({prefix:t,name:e,encode(o){return ZWe(o,n,r)},decode(o){return KWe(o,n,r,e)}}),GWe=nP({prefix:"\0",name:"identity",encode:e=>WWe(e),decode:e=>qWe(e)}),YWe=Object.freeze({__proto__:null,identity:GWe}),JWe=Ko({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),QWe=Object.freeze({__proto__:null,base2:JWe}),XWe=Ko({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),eKe=Object.freeze({__proto__:null,base8:XWe}),tKe=q5({prefix:"9",name:"base10",alphabet:"0123456789"}),rKe=Object.freeze({__proto__:null,base10:tKe}),nKe=Ko({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oKe=Ko({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),sKe=Object.freeze({__proto__:null,base16:nKe,base16upper:oKe}),iKe=Ko({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aKe=Ko({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cKe=Ko({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lKe=Ko({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uKe=Ko({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dKe=Ko({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fKe=Ko({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pKe=Ko({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hKe=Ko({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),mKe=Object.freeze({__proto__:null,base32:iKe,base32upper:aKe,base32pad:cKe,base32padupper:lKe,base32hex:uKe,base32hexupper:dKe,base32hexpad:fKe,base32hexpadupper:pKe,base32z:hKe}),gKe=q5({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yKe=q5({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),wKe=Object.freeze({__proto__:null,base36:gKe,base36upper:yKe}),bKe=q5({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xKe=q5({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),vKe=Object.freeze({__proto__:null,base58btc:bKe,base58flickr:xKe}),EKe=Ko({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),AKe=Ko({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CKe=Ko({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),SKe=Ko({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),IKe=Object.freeze({__proto__:null,base64:EKe,base64pad:AKe,base64url:CKe,base64urlpad:SKe}),Fye=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),TKe=Fye.reduce((e,t,r)=>(e[r]=t,e),[]),_Ke=Fye.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);RKe=nP({prefix:"\u{1F680}",name:"base256emoji",encode:PKe,decode:NKe}),OKe=Object.freeze({__proto__:null,base256emoji:RKe}),BKe=zye,fye=128,kKe=127,UKe=~kKe,DKe=Math.pow(2,31);LKe=Dz,MKe=128,pye=127;HKe=Math.pow(2,7),$Ke=Math.pow(2,14),FKe=Math.pow(2,21),zKe=Math.pow(2,28),VKe=Math.pow(2,35),jKe=Math.pow(2,42),qKe=Math.pow(2,49),WKe=Math.pow(2,56),KKe=Math.pow(2,63),ZKe=function(e){return e(Vye.encode(e,t,r),t),mye=e=>Vye.encodingLength(e),Lz=(e,t)=>{let r=t.byteLength,n=mye(e),o=n+mye(r),s=new Uint8Array(o+r);return hye(e,s,0),hye(r,s,n),s.set(t,o),new Mz(e,r,t,s)},Mz=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}},jye=({name:e,code:t,encode:r})=>new Hz(e,t,r),Hz=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?Lz(this.code,r):r.then(n=>Lz(this.code,n))}else throw Error("Unknown type, must be binary type")}},qye=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),YKe=jye({name:"sha2-256",code:18,encode:qye("SHA-256")}),JKe=jye({name:"sha2-512",code:19,encode:qye("SHA-512")}),QKe=Object.freeze({__proto__:null,sha256:YKe,sha512:JKe}),Wye=0,XKe="identity",Kye=Hye,eZe=e=>Lz(Wye,Kye(e)),tZe={code:Wye,name:XKe,encode:Kye,digest:eZe},rZe=Object.freeze({__proto__:null,identity:tZe});new TextEncoder,new TextDecoder;gye={...YWe,...QWe,...eKe,...rKe,...sKe,...mKe,...wKe,...vKe,...IKe,...OKe};({...QKe,...rZe});yye=Gye("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),_z=Gye("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=nZe(e.length);for(let r=0;rt in e?iZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pu=(e,t,r)=>aZe(e,typeof t!="symbol"?t+"":t,r),$z=class{constructor(t,r){this.core=t,this.logger=r,Pu(this,"keychain",new Map),Pu(this,"name",fWe),Pu(this,"version",pWe),Pu(this,"initialized",!1),Pu(this,"storagePrefix",Ru),Pu(this,"init",async()=>{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Pu(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Pu(this,"set",async(n,o)=>{this.isInitialized(),this.keychain.set(n,o),await this.persist()}),Pu(this,"get",n=>{this.isInitialized();let o=this.keychain.get(n);if(typeof o>"u"){let{message:s}=Ie("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return o}),Pu(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=t,this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,$7(t))}async getKeyChain(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?F7(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},cZe=Object.defineProperty,lZe=(e,t,r)=>t in e?cZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,No=(e,t,r)=>lZe(e,typeof t!="symbol"?t+"":t,r),Fz=class{constructor(t,r,n){this.core=t,this.logger=r,No(this,"name",uWe),No(this,"keychain"),No(this,"randomSessionIdentifier",Q7()),No(this,"initialized",!1),No(this,"clientId"),No(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),No(this,"hasKeys",o=>(this.isInitialized(),this.keychain.has(o))),No(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;let o=await this.getClientSeed(),s=J2(o),i=U8(s.publicKey);return this.clientId=i,i}),No(this,"generateKeyPair",()=>{this.isInitialized();let o=Nge();return this.setPrivateKey(o.publicKey,o.privateKey)}),No(this,"signJWT",async o=>{this.isInitialized();let s=await this.getClientSeed(),i=J2(s),a=this.randomSessionIdentifier;return await BC(a,o,dWe,i)}),No(this,"generateSharedKey",(o,s,i)=>{this.isInitialized();let a=this.getPrivateKey(o),c=Rge(a,s);return this.setSymKey(c,i)}),No(this,"setSymKey",async(o,s)=>{this.isInitialized();let i=s||tx(o);return await this.keychain.set(i,o),i}),No(this,"deleteKeyPair",async o=>{this.isInitialized(),await this.keychain.del(o)}),No(this,"deleteSymKey",async o=>{this.isInitialized(),await this.keychain.del(o)}),No(this,"encode",async(o,s,i)=>{this.isInitialized();let a=gz(i),c=yi(s);if(wz(a))return Lge(c,i?.encoding);if(yz(a)){let p=a.senderPublicKey,h=a.receiverPublicKey;o=await this.generateSharedKey(p,h)}let u=this.getSymKey(o),{type:d,senderPublicKey:f}=a;return Uge({type:d,symKey:u,message:c,senderPublicKey:f,encoding:i?.encoding})}),No(this,"decode",async(o,s,i)=>{this.isInitialized();let a=$ge(s,i);if(wz(a)){let c=Mge(s,i?.encoding);return Fs(c)}if(yz(a)){let c=a.receiverPublicKey,u=a.senderPublicKey;o=await this.generateSharedKey(c,u)}try{let c=this.getSymKey(o),u=Dge({symKey:c,encoded:s,encoding:i?.encoding});return Fs(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),No(this,"getPayloadType",(o,s=Ts)=>{let i=rx({encoded:o,encoding:s});return Hm(i.type)}),No(this,"getPayloadSenderPublicKey",(o,s=Ts)=>{let i=rx({encoded:o,encoding:s});return i.senderPublicKey?Ut(i.senderPublicKey,Is):void 0}),this.core=t,this.logger=Cr(r,this.name),this.keychain=n||new $z(this.core,this.logger)}get context(){return sr(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(uye)}catch{t=Q7(),await this.keychain.set(uye,t)}return sZe(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},uZe=Object.defineProperty,dZe=Object.defineProperties,fZe=Object.getOwnPropertyDescriptors,wye=Object.getOwnPropertySymbols,pZe=Object.prototype.hasOwnProperty,hZe=Object.prototype.propertyIsEnumerable,zz=(e,t,r)=>t in e?uZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,mZe=(e,t)=>{for(var r in t||(t={}))pZe.call(t,r)&&zz(e,r,t[r]);if(wye)for(var r of wye(t))hZe.call(t,r)&&zz(e,r,t[r]);return e},gZe=(e,t)=>dZe(e,fZe(t)),Ua=(e,t,r)=>zz(e,typeof t!="symbol"?t+"":t,r),Vz=class extends R_{constructor(t,r){super(t,r),this.logger=t,this.core=r,Ua(this,"messages",new Map),Ua(this,"messagesWithoutClientAck",new Map),Ua(this,"name",hWe),Ua(this,"version",mWe),Ua(this,"initialized",!1),Ua(this,"storagePrefix",Ru),Ua(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);let o=await this.getRelayerMessagesWithoutClientAck();typeof o<"u"&&(this.messagesWithoutClientAck=o),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Ua(this,"set",async(n,o,s)=>{this.isInitialized();let i=Wi(o),a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[i]<"u")return i;if(a[i]=o,this.messages.set(n,a),s===tP.inbound){let c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,gZe(mZe({},c),{[i]:o}))}return await this.persist(),i}),Ua(this,"get",n=>{this.isInitialized();let o=this.messages.get(n);return typeof o>"u"&&(o={}),o}),Ua(this,"getWithoutAck",n=>{this.isInitialized();let o={};for(let s of n){let i=this.messagesWithoutClientAck.get(s)||{};o[s]=Object.values(i)}return o}),Ua(this,"has",(n,o)=>{this.isInitialized();let s=this.get(n),i=Wi(o);return typeof s[i]<"u"}),Ua(this,"ack",async(n,o)=>{this.isInitialized();let s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;let i=Wi(o);delete s[i],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),Ua(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Cr(t,this.name),this.core=r}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,$7(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,$7(t))}async getRelayerMessages(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?F7(t):void 0}async getRelayerMessagesWithoutClientAck(){let t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?F7(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},yZe=Object.defineProperty,wZe=Object.defineProperties,bZe=Object.getOwnPropertyDescriptors,bye=Object.getOwnPropertySymbols,xZe=Object.prototype.hasOwnProperty,vZe=Object.prototype.propertyIsEnumerable,jz=(e,t,r)=>t in e?yZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,sx=(e,t)=>{for(var r in t||(t={}))xZe.call(t,r)&&jz(e,r,t[r]);if(bye)for(var r of bye(t))vZe.call(t,r)&&jz(e,r,t[r]);return e},xye=(e,t)=>wZe(e,bZe(t)),Ec=(e,t,r)=>jz(e,typeof t!="symbol"?t+"":t,r),qz=class extends O_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,Ec(this,"events",new Rp.EventEmitter),Ec(this,"name",yWe),Ec(this,"queue",new Map),Ec(this,"publishTimeout",(0,Xe.toMiliseconds)(Xe.ONE_MINUTE)),Ec(this,"initialPublishTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),Ec(this,"needsTransportRestart",!1),Ec(this,"publish",async(n,o,s)=>{var i,a,c,u,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:o,opts:s}});let f=s?.ttl||gWe,p=s?.prompt||!1,h=s?.tag||0,y=s?.id||_n().toString(),w=Py(L5().protocol),x={id:y,method:s?.publishMethod||w.publish,params:sx({topic:n,message:o,ttl:f,prompt:p,tag:h,attestation:s?.attestation},s?.tvf)},v=`Failed to publish payload, please try again. id:${y} tag:${h}`;try{Ln((i=x.params)==null?void 0:i.prompt)&&((a=x.params)==null||delete a.prompt),Ln((c=x.params)==null?void 0:c.tag)&&((u=x.params)==null||delete u.tag);let T=new Promise(async E=>{let S=({id:O})=>{var D;((D=x.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(Mn.publish,S),E())};this.relayer.events.on(Mn.publish,S);let _=xl(new Promise((O,D)=>{this.rpcPublish(x,s).then(O).catch(M=>{this.logger.warn(M,M?.message),D(M)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${y} tag:${h}`);try{await _,this.events.removeListener(Mn.publish,S)}catch(O){this.queue.set(y,{request:x,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:y,topic:n,message:o,opts:s}}),await xl(T,this.publishTimeout,v)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(d=s?.internal)!=null&&d.throwOnFailedPublish)throw T}finally{this.queue.delete(y)}}),Ec(this,"publishCustom",async n=>{var o,s,i,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});let{payload:u,opts:d={}}=n,{attestation:f,tvf:p,publishMethod:h,prompt:y,tag:w,ttl:x=Xe.FIVE_MINUTES}=d,v=d.id||_n().toString(),T=Py(L5().protocol),E=h||T.publish,S={id:v,method:E,params:sx(xye(sx({},u),{ttl:x,prompt:y,tag:w,attestation:f}),p)},_=`Failed to publish custom payload, please try again. id:${v} tag:${w}`;try{Ln((o=S.params)==null?void 0:o.prompt)&&((s=S.params)==null||delete s.prompt),Ln((i=S.params)==null?void 0:i.tag)&&((a=S.params)==null||delete a.tag);let O=new Promise(async D=>{let M=({id:L})=>{var P;((P=S.id)==null?void 0:P.toString())===L.toString()&&(this.removeRequestFromQueue(L),this.relayer.events.removeListener(Mn.publish,M),D())};this.relayer.events.on(Mn.publish,M);let N=xl(new Promise((L,P)=>{this.rpcPublish(S,d).then(L).catch(R=>{this.logger.warn(R,R?.message),P(R)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${E} id:${v} tag:${w}`);try{await N,this.events.removeListener(Mn.publish,M)}catch(L){this.queue.set(v,{request:S,opts:d,attempt:1}),this.logger.warn(L,L?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:v,payload:u,opts:d}}),await xl(O,this.publishTimeout,_)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=d?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(v)}}),Ec(this,"on",(n,o)=>{this.events.on(n,o)}),Ec(this,"once",(n,o)=>{this.events.once(n,o)}),Ec(this,"off",(n,o)=>{this.events.off(n,o)}),Ec(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.relayer=t,this.logger=Cr(r,this.name),this.registerEventListeners()}get context(){return sr(this.logger)}async rpcPublish(t,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});let n=await this.relayer.request(t);return this.relayer.events.emit(Mn.publish,sx(sx({},t),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,r)=>{var n;let o=t.attempt+1;this.queue.set(r,xye(sx({},t),{attempt:o})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(n=t.request.params)==null?void 0:n.tag}, attempt: ${o}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Mn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Mn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}},EZe=Object.defineProperty,AZe=(e,t,r)=>t in e?EZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ix=(e,t,r)=>AZe(e,typeof t!="symbol"?t+"":t,r),Wz=class{constructor(){ix(this,"map",new Map),ix(this,"set",(t,r)=>{let n=this.get(t);this.exists(t,r)||this.map.set(t,[...n,r])}),ix(this,"get",t=>this.map.get(t)||[]),ix(this,"exists",(t,r)=>this.get(t).includes(r)),ix(this,"delete",(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;let n=this.get(t);if(!this.exists(t,r))return;let o=n.filter(s=>s!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)}),ix(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}},CZe=Object.defineProperty,SZe=Object.defineProperties,IZe=Object.getOwnPropertyDescriptors,vye=Object.getOwnPropertySymbols,TZe=Object.prototype.hasOwnProperty,_Ze=Object.prototype.propertyIsEnumerable,Kz=(e,t,r)=>t in e?CZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,F5=(e,t)=>{for(var r in t||(t={}))TZe.call(t,r)&&Kz(e,r,t[r]);if(vye)for(var r of vye(t))_Ze.call(t,r)&&Kz(e,r,t[r]);return e},Pz=(e,t)=>SZe(e,IZe(t)),Or=(e,t,r)=>Kz(e,typeof t!="symbol"?t+"":t,r),Zz=class extends U_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,Or(this,"subscriptions",new Map),Or(this,"topicMap",new Wz),Or(this,"events",new Rp.EventEmitter),Or(this,"name",CWe),Or(this,"version",SWe),Or(this,"pending",new Map),Or(this,"cached",[]),Or(this,"initialized",!1),Or(this,"storagePrefix",Ru),Or(this,"subscribeTimeout",(0,Xe.toMiliseconds)(Xe.ONE_MINUTE)),Or(this,"initialSubscribeTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),Or(this,"clientId"),Or(this,"batchSubscribeTopicsLimit",500),Or(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Or(this,"subscribe",async(n,o)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}});try{let i=L5(o),a={topic:n,relay:i,transportType:o?.transportType};(s=o?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);let c=await this.rpcSubscribe(n,i,o);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}})),c}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}}),Or(this,"unsubscribe",async(n,o)=>{this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(n,o.id,o):await this.unsubscribeByTopic(n,o)}),Or(this,"isSubscribed",n=>new Promise(o=>{o(this.topicMap.topics.includes(n))})),Or(this,"isKnownTopic",n=>new Promise(o=>{o(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),Or(this,"on",(n,o)=>{this.events.on(n,o)}),Or(this,"once",(n,o)=>{this.events.once(n,o)}),Or(this,"off",(n,o)=>{this.events.off(n,o)}),Or(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),Or(this,"start",async()=>{await this.onConnect()}),Or(this,"stop",async()=>{await this.onDisconnect()}),Or(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Or(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;let n=[];this.pending.forEach(o=>{n.push(o)}),await this.batchSubscribe(n)}),Or(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Vs.pulse,async()=>{await this.checkPending()}),this.events.on(Da.created,async n=>{let o=Da.created;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()}),this.events.on(Da.deleted,async n=>{let o=Da.deleted;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()})}),this.relayer=t,this.logger=Cr(r,this.name),this.clientId=""}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,r){let n=!1;try{n=this.getSubscription(t).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){let n=this.topicMap.get(t);await Promise.all(n.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}});try{let o=L5(n);await this.restartToComplete({topic:t,id:r,relay:o}),await this.rpcUnsubscribe(t,r,o);let s=Rr("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r,n){var o,s;let i=await this.getSubscriptionId(t);if((o=n?.internal)!=null&&o.skipSubscribe)return i;(!n||n?.transportType===Vr.relay)&&await this.restartToComplete({topic:t,id:t,relay:r});let a={method:Py(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});let c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===Vr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},(0,Xe.toMiliseconds)(Xe.ONE_SECOND)),i;let u=new Promise(async f=>{let p=h=>{h.topic===t&&(this.events.removeListener(Da.created,p),f(h.id))};this.events.on(Da.created,p);try{let h=await xl(new Promise((y,w)=>{this.relayer.request(a).catch(x=>{this.logger.warn(x,x?.message),w(x)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(Da.created,p),f(h)}catch{}}),d=await xl(u,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return d?i:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Mn.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(t){if(!t.length)return;let r=t[0].relay,n={method:Py(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await xl(new Promise(o=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(o)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Mn.connection_stalled)}}async rpcBatchFetchMessages(t){if(!t.length)return;let r=t[0].relay,n={method:Py(r.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let o;try{o=await await xl(new Promise((s,i)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),i(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Mn.connection_stalled)}return o}rpcUnsubscribe(t,r,n){let o={method:Py(n.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,Pz(F5({},r),{id:t})),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,F5({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,n),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r)}addSubscription(t,r){this.subscriptions.set(t,F5({},r)),this.topicMap.set(r.topic,t),this.events.emit(Da.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});let r=this.subscriptions.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});let n=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(n.topic,t),this.events.emit(Da.deleted,Pz(F5({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Da.sync)}async onRestart(){if(this.cached.length){let t=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n"u"||!t.length)return;if(this.subscriptions.size&&!t.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){t.length&&(await this.rpcBatchSubscribe(t),this.onBatchSubscribe(await Promise.all(t.map(async r=>Pz(F5({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);let r=await this.rpcBatchFetchMessages(t);r&&r.messages&&(await U1e((0,Xe.toMiliseconds)(Xe.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Wi(t+await this.getClientId())}},PZe=Object.defineProperty,Eye=Object.getOwnPropertySymbols,NZe=Object.prototype.hasOwnProperty,RZe=Object.prototype.propertyIsEnumerable,Gz=(e,t,r)=>t in e?PZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Aye=(e,t)=>{for(var r in t||(t={}))NZe.call(t,r)&&Gz(e,r,t[r]);if(Eye)for(var r of Eye(t))RZe.call(t,r)&&Gz(e,r,t[r]);return e},rr=(e,t,r)=>Gz(e,typeof t!="symbol"?t+"":t,r),Yz=class extends B_{constructor(t){var r;super(t),rr(this,"protocol","wc"),rr(this,"version",2),rr(this,"core"),rr(this,"logger"),rr(this,"events",new Rp.EventEmitter),rr(this,"provider"),rr(this,"messages"),rr(this,"subscriber"),rr(this,"publisher"),rr(this,"name",bWe),rr(this,"transportExplicitlyClosed",!1),rr(this,"initialized",!1),rr(this,"connectionAttemptInProgress",!1),rr(this,"relayUrl"),rr(this,"projectId"),rr(this,"packageName"),rr(this,"bundleId"),rr(this,"hasExperiencedNetworkDisruption",!1),rr(this,"pingTimeout"),rr(this,"heartBeatTimeout",(0,Xe.toMiliseconds)(Xe.THIRTY_SECONDS+Xe.FIVE_SECONDS)),rr(this,"reconnectTimeout"),rr(this,"connectPromise"),rr(this,"reconnectInProgress",!1),rr(this,"requestsInFlight",[]),rr(this,"connectTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),rr(this,"request",async n=>{var o,s;this.logger.debug("Publishing Request Payload");let i=n.id||_n().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:n.method,topic:(o=n.params)==null?void 0:o.topic},"relayer.request - publishing...");let a=`${i}:${((s=n.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);let c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${i}`),a}}),rr(this,"resetPingTimeout",()=>{P5()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,o,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(i=(s=(o=(n=this.provider)==null?void 0:n.connection)==null?void 0:o.socket)==null?void 0:s.terminate)==null||i.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),rr(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),rr(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Mn.connect)}),rr(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),rr(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Mn.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),rr(this,"registerProviderListeners",()=>{this.provider.on(vc.payload,this.onPayloadHandler),this.provider.on(vc.connect,this.onConnectHandler),this.provider.on(vc.disconnect,this.onDisconnectHandler),this.provider.on(vc.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=ox({logger:(r=t.logger)!=null?r:wWe,name:this.name}),this.messages=new Vz(this.logger,t.core),this.subscriber=new Zz(this,this.logger),this.publisher=new qz(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Lye,S1e()?this.packageName=JF():I1e()&&(this.bundleId=JF()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return sr(this.logger)}get connected(){var t,r,n;return((n=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var t,r,n;return((n=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,r,n){this.isInitialized(),await this.publisher.publish(t,r,n),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now(),transportType:Vr.relay},tP.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,r){var n,o,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();let i=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(o=r?.internal)==null?void 0:o.throwOnFailedPublish,a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c,u=d=>{d.topic===t&&(this.subscriber.off(Da.created,u),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Da.created,u)}),new Promise(async(d,f)=>{a=await this.subscriber.subscribe(t,Aye({internal:{throwOnFailedPublish:i}},r)).catch(p=>{i&&f(p)})||a,d()})]),a}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await xl(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(t).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tz())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}let r=t.sort((n,o)=>n.publishedAt-o.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(let n of r)try{await this.onMessageEvent(n)}catch(o){this.logger.warn(o,"Error while processing batch message event: "+o?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(t,r){let{topic:n}=t;if(!r.sessionExists){let o=pn(Xe.FIVE_MINUTES),s={topic:n,expiry:o,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Mn.message,t),await this.recordMessageEvent(t,tP.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to connect"))};this.provider.once(vc.disconnect,s),await xl(new Promise((i,a)=>{this.provider.connect().then(i).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(i=>{o(i)}).finally(()=>{this.provider.off(vc.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(i,a)=>{let c=()=>{o(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(vc.disconnect,c),await this.subscriber.start().then(i).catch(a).finally(()=>{this.provider.off(vc.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();let o=n;this.logger.warn({},o.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,(0,Xe.toMiliseconds)(r*1))),r++}}startPingTimeout(){var t,r,n,o,s;if(P5())try{(r=(t=this.provider)==null?void 0:t.connection)!=null&&r.socket&&((s=(o=(n=this.provider)==null?void 0:n.connection)==null?void 0:o.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(i){this.logger.warn(i,i?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new da(new lw(_1e({sdkVersion:Rz,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,r){let{topic:n,message:o}=t;await this.messages.set(n,o,r)}async shouldIgnoreMessageEvent(t){let{topic:r,message:n}=t;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;let o=this.messages.has(r,n);return o&&this.logger.warn(`Ignoring duplicate message: ${n}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Hc(t)){if(!t.method.endsWith(xWe))return;let r=t.params,{topic:n,message:o,publishedAt:s,attestation:i}=r.data,a={topic:n,message:o,publishedAt:s,transportType:Vr.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Aye({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else ua(t)&&this.events.emit(Mn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,tP.inbound),this.events.emit(Mn.message,t))}async acknowledgePayload(t){let r=bo(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(vc.payload,this.onPayloadHandler),this.provider.off(vc.connect,this.onConnectHandler),this.provider.off(vc.disconnect,this.onDisconnectHandler),this.provider.off(vc.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await Tz();aye(async r=>{t!==r&&(t=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vs.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&cye())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Mn.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,Xe.toMiliseconds)(vWe)))))}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}};BZe="[object RegExp]",kZe="[object String]",UZe="[object Number]",DZe="[object Boolean]",Iye="[object Arguments]",LZe="[object Symbol]",MZe="[object Date]",HZe="[object Map]",$Ze="[object Set]",FZe="[object Array]",zZe="[object Function]",VZe="[object ArrayBuffer]",Nz="[object Object]",jZe="[object Error]",qZe="[object DataView]",WZe="[object Uint8Array]",KZe="[object Uint8ClampedArray]",ZZe="[object Uint16Array]",GZe="[object Uint32Array]",YZe="[object BigUint64Array]",JZe="[object Int8Array]",QZe="[object Int16Array]",XZe="[object Int32Array]",eGe="[object BigInt64Array]",tGe="[object Float32Array]",rGe="[object Float64Array]";iGe=Object.defineProperty,_ye=Object.getOwnPropertySymbols,aGe=Object.prototype.hasOwnProperty,cGe=Object.prototype.propertyIsEnumerable,Jz=(e,t,r)=>t in e?iGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pye=(e,t)=>{for(var r in t||(t={}))aGe.call(t,r)&&Jz(e,r,t[r]);if(_ye)for(var r of _ye(t))cGe.call(t,r)&&Jz(e,r,t[r]);return e},Ki=(e,t,r)=>Jz(e,typeof t!="symbol"?t+"":t,r),Ou=class extends k_{constructor(t,r,n,o=Ru,s=void 0){super(t,r,n,o),this.core=t,this.logger=r,this.name=n,Ki(this,"map",new Map),Ki(this,"version",EWe),Ki(this,"cached",[]),Ki(this,"initialized",!1),Ki(this,"getKey"),Ki(this,"storagePrefix",Ru),Ki(this,"recentlyDeleted",[]),Ki(this,"recentlyDeletedLimit",200),Ki(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>{this.getKey&&i!==null&&!Ln(i)?this.map.set(this.getKey(i),i):Kge(i)?this.map.set(i.id,i):Zge(i)&&this.map.set(i.topic,i)}),this.cached=[],this.initialized=!0)}),Ki(this,"set",async(i,a)=>{this.isInitialized(),this.map.has(i)?await this.update(i,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:i,value:a}),this.map.set(i,a),await this.persist())}),Ki(this,"get",i=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:i}),this.getData(i))),Ki(this,"getAll",i=>(this.isInitialized(),i?this.values.filter(a=>Object.keys(i).every(c=>sGe(a[c],i[c]))):this.values)),Ki(this,"update",async(i,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:i,update:a});let c=Pye(Pye({},this.getData(i)),a);this.map.set(i,c),await this.persist()}),Ki(this,"delete",async(i,a)=>{this.isInitialized(),this.map.has(i)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:i,reason:a}),this.map.delete(i),this.addToRecentlyDeleted(i),await this.persist())}),this.logger=Cr(r,this.name),this.storagePrefix=o,this.getKey=s}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){let r=this.map.get(t);if(!r){if(this.recentlyDeleted.includes(t)){let{message:o}=Ie("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(o),new Error(o)}let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},lGe=Object.defineProperty,uGe=(e,t,r)=>t in e?lGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vt=(e,t,r)=>uGe(e,typeof t!="symbol"?t+"":t,r),Qz=class{constructor(t,r){this.core=t,this.logger=r,Vt(this,"name",IWe),Vt(this,"version",TWe),Vt(this,"events",new Rp.default),Vt(this,"pairings"),Vt(this,"initialized",!1),Vt(this,"storagePrefix",Ru),Vt(this,"ignoredPayloadTypes",[vl]),Vt(this,"registeredMethods",[]),Vt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Vt(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Vt(this,"create",async n=>{this.isInitialized();let o=Q7(),s=await this.core.crypto.setSymKey(o),i=pn(Xe.FIVE_MINUTES),a={protocol:aV},c={topic:s,expiry:i,relay:a,active:!1,methods:n?.methods},u=xz({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:o,relay:a,expiryTimestamp:i,methods:n?.methods});return this.events.emit(zm.create,c),this.core.expirer.set(s,i),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}}),Vt(this,"pair",async n=>{this.isInitialized();let o=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Cl.pairing_started]}});this.isValidPair(n,o);let{topic:s,symKey:i,relay:a,expiryTimestamp:c,methods:u}=bz(n.uri);o.props.properties.topic=s,o.addTrace(Cl.pairing_uri_validation_success),o.addTrace(Cl.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(s)){if(d=this.pairings.get(s),o.addTrace(Cl.existing_pairing),d.active)throw o.setError(Nu.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);o.addTrace(Cl.pairing_not_expired)}let f=c||pn(Xe.FIVE_MINUTES),p={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,p),o.addTrace(Cl.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(zm.create,p),o.addTrace(Cl.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),o.addTrace(Cl.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{o.setError(Nu.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw o.setError(Nu.subscribe_pairing_topic_failure),h}return o.addTrace(Cl.subscribe_pairing_topic_success),p}),Vt(this,"activate",async({topic:n})=>{this.isInitialized();let o=pn(Xe.FIVE_MINUTES);this.core.expirer.set(n,o),await this.pairings.update(n,{active:!0,expiry:o})}),Vt(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:o}=n;if(this.pairings.keys.includes(o)){let s=await this.sendRequest(o,"wc_pairingPing",{}),{done:i,resolve:a,reject:c}=Pp();this.events.once(cr("pairing_ping",s),({error:u})=>{u?c(u):a()}),await i()}}),Vt(this,"updateExpiry",async({topic:n,expiry:o})=>{this.isInitialized(),await this.pairings.update(n,{expiry:o})}),Vt(this,"updateMetadata",async({topic:n,metadata:o})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:o})}),Vt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Vt(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:o}=n;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",Rr("USER_DISCONNECTED")),await this.deletePairing(o))}),Vt(this,"formatUriFromPairing",n=>{this.isInitialized();let{topic:o,relay:s,expiry:i,methods:a}=n,c=this.core.crypto.keychain.get(o);return xz({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:c,relay:s,expiryTimestamp:i,methods:a})}),Vt(this,"sendRequest",async(n,o,s)=>{let i=dr(o,s),a=await this.core.crypto.encode(n,i),c=$5[o].req;return this.core.history.set(n,i),this.core.relayer.publish(n,a,c),i.id}),Vt(this,"sendResult",async(n,o,s)=>{let i=bo(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=$5[c].res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)}),Vt(this,"sendError",async(n,o,s)=>{let i=la(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=$5[c]?$5[c].res:$5.unregistered_method.res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)}),Vt(this,"deletePairing",async(n,o)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Rr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),o?Promise.resolve():this.core.expirer.del(n)])}),Vt(this,"cleanup",async()=>{let n=this.pairings.getAll().filter(o=>ka(o.expiry));await Promise.all(n.map(o=>this.deletePairing(o.topic)))}),Vt(this,"onRelayEventRequest",async n=>{let{topic:o,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(o,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(o,s);default:return await this.onUnknownRpcMethodRequest(o,s)}}),Vt(this,"onRelayEventResponse",async n=>{let{topic:o,payload:s}=n,i=(await this.core.history.get(o,s.id)).request.method;return i==="wc_pairingPing"?this.onPairingPingResponse(o,s):this.onUnknownRpcMethodResponse(i)}),Vt(this,"onPairingPingRequest",async(n,o)=>{let{id:s}=o;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(zm.ping,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}}),Vt(this,"onPairingPingResponse",(n,o)=>{let{id:s}=o;setTimeout(()=>{Jr(o)?this.events.emit(cr("pairing_ping",s),{}):Ir(o)&&this.events.emit(cr("pairing_ping",s),{error:o.error})},500)}),Vt(this,"onPairingDeleteRequest",async(n,o)=>{let{id:s}=o;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(zm.delete,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}}),Vt(this,"onUnknownRpcMethodRequest",async(n,o)=>{let{id:s,method:i}=o;try{if(this.registeredMethods.includes(i))return;let a=Rr("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Vt(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Rr("WC_METHOD_UNSUPPORTED",n))}),Vt(this,"isValidPair",(n,o)=>{var s;if(!_s(n)){let{message:a}=Ie("MISSING_OR_INVALID",`pair() params: ${n}`);throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(!Wge(n.uri)){let{message:a}=Ie("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw o.setError(Nu.malformed_pairing_uri),new Error(a)}let i=bz(n?.uri);if(!((s=i?.relay)!=null&&s.protocol)){let{message:a}=Ie("MISSING_OR_INVALID","pair() uri#relay-protocol");throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(!(i!=null&&i.symKey)){let{message:a}=Ie("MISSING_OR_INVALID","pair() uri#symKey");throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(i!=null&&i.expiryTimestamp&&(0,Xe.toMiliseconds)(i?.expiryTimestamp){if(!_s(n)){let{message:s}=Ie("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)}),Vt(this,"isValidDisconnect",async n=>{if(!_s(n)){let{message:s}=Ie("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)}),Vt(this,"isValidPairingTopic",async n=>{if(!An(n,!1)){let{message:o}=Ie("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(o)}if(!this.pairings.keys.includes(n)){let{message:o}=Ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(o)}if(ka(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:o}=Ie("EXPIRED",`pairing topic: ${n}`);throw new Error(o)}}),this.core=t,this.logger=Cr(r,this.name),this.pairings=new Ou(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sr(this.logger)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(Mn.message,async t=>{let{topic:r,message:n,transportType:o}=t;if(this.pairings.keys.includes(r)&&o!==Vr.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{let s=await this.core.crypto.decode(r,n);Hc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ua(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(La.expired,async t=>{let{topic:r}=z7(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(zm.expire,{topic:r}))})}},dGe=Object.defineProperty,fGe=(e,t,r)=>t in e?dGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Wo=(e,t,r)=>fGe(e,typeof t!="symbol"?t+"":t,r),Xz=class extends N_{constructor(t,r){super(t,r),this.core=t,this.logger=r,Wo(this,"records",new Map),Wo(this,"events",new Rp.EventEmitter),Wo(this,"name",_We),Wo(this,"version",PWe),Wo(this,"cached",[]),Wo(this,"initialized",!1),Wo(this,"storagePrefix",Ru),Wo(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Wo(this,"set",(n,o,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:o,chainId:s}),this.records.has(o.id))return;let i={id:o.id,topic:n,request:{method:o.method,params:o.params||null},chainId:s,expiry:pn(Xe.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Al.created,i)}),Wo(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let o=await this.getRecord(n.id);typeof o.response>"u"&&(o.response=Ir(n)?{error:n.error}:{result:n.result},this.records.set(o.id,o),this.persist(),this.events.emit(Al.updated,o))}),Wo(this,"get",async(n,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:o}),await this.getRecord(o))),Wo(this,"delete",(n,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(s=>{if(s.topic===n){if(typeof o<"u"&&s.id!==o)return;this.records.delete(s.id),this.events.emit(Al.deleted,s)}}),this.persist()}),Wo(this,"exists",async(n,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===n:!1)),Wo(this,"on",(n,o)=>{this.events.on(n,o)}),Wo(this,"once",(n,o)=>{this.events.once(n,o)}),Wo(this,"off",(n,o)=>{this.events.off(n,o)}),Wo(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(n)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();let r=this.records.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Al.sync)}async restore(){try{let t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(Al.created,t=>{let r=Al.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Al.updated,t=>{let r=Al.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Al.deleted,t=>{let r=Al.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.core.heartbeat.on(Vs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(r=>{(0,Xe.toMiliseconds)(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Al.deleted,r,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},pGe=Object.defineProperty,hGe=(e,t,r)=>t in e?pGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ps=(e,t,r)=>hGe(e,typeof t!="symbol"?t+"":t,r),eV=class extends D_{constructor(t,r){super(t,r),this.core=t,this.logger=r,Ps(this,"expirations",new Map),Ps(this,"events",new Rp.EventEmitter),Ps(this,"name",NWe),Ps(this,"version",RWe),Ps(this,"cached",[]),Ps(this,"initialized",!1),Ps(this,"storagePrefix",Ru),Ps(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ps(this,"has",n=>{try{let o=this.formatTarget(n);return typeof this.getExpiration(o)<"u"}catch{return!1}}),Ps(this,"set",(n,o)=>{this.isInitialized();let s=this.formatTarget(n),i={target:s,expiry:o};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(La.created,{target:s,expiration:i})}),Ps(this,"get",n=>{this.isInitialized();let o=this.formatTarget(n);return this.getExpiration(o)}),Ps(this,"del",n=>{if(this.isInitialized(),this.has(n)){let o=this.formatTarget(n),s=this.getExpiration(o);this.expirations.delete(o),this.events.emit(La.deleted,{target:o,expiration:s})}}),Ps(this,"on",(n,o)=>{this.events.on(n,o)}),Ps(this,"once",(n,o)=>{this.events.once(n,o)}),Ps(this,"off",(n,o)=>{this.events.off(n,o)}),Ps(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(t){if(typeof t=="string")return N1e(t);if(typeof t=="number")return R1e(t);let{message:r}=Ie("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(La.sync)}async restore(){try{let t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){let r=this.expirations.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(t,r){let{expiry:n}=r;(0,Xe.toMiliseconds)(n)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(La.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Vs.pulse,()=>this.checkExpirations()),this.events.on(La.created,t=>{let r=La.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(La.expired,t=>{let r=La.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(La.deleted,t=>{let r=La.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},mGe=Object.defineProperty,gGe=(e,t,r)=>t in e?mGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Kn=(e,t,r)=>gGe(e,typeof t!="symbol"?t+"":t,r),tV=class extends L_{constructor(t,r,n){super(t,r,n),this.core=t,this.logger=r,this.store=n,Kn(this,"name",OWe),Kn(this,"abortController"),Kn(this,"isDevEnv"),Kn(this,"verifyUrlV3",kWe),Kn(this,"storagePrefix",Ru),Kn(this,"version",Dye),Kn(this,"publicKey"),Kn(this,"fetchPromise"),Kn(this,"init",async()=>{var o;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,Xe.toMiliseconds)((o=this.publicKey)==null?void 0:o.expiresAt){if(!Ty()||this.isDevEnv)return;let s=window.location.origin,{id:i,decryptedId:a}=o,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${i}&decryptedId=${a}`;try{let u=(0,kye.getDocument)(),d=this.startAbortTimer(Xe.ONE_SECOND*5),f=await new Promise((p,h)=>{let y=()=>{window.removeEventListener("message",x),u.body.removeChild(w),h("attestation aborted")};this.abortController.signal.addEventListener("abort",y);let w=u.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});let x=v=>{if(v.data&&typeof v.data=="string")try{let T=JSON.parse(v.data);if(T.type==="verify_attestation"){if(Hl(T.attestation).payload.id!==i)return;clearInterval(d),u.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",x),p(T.attestation===null?"":T.attestation)}}catch(T){this.logger.warn(T)}};u.body.appendChild(w),window.addEventListener("message",x,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Kn(this,"resolve",async o=>{if(this.isDevEnv)return"";let{attestationId:s,hash:i,encryptedId:a}=o;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Hl(s).payload.id!==a)return;let u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!i)return;let c=this.getVerifyUrl(o?.verifyUrl);return this.fetchAttestation(i,c)}),Kn(this,"fetchAttestation",async(o,s)=>{this.logger.debug(`resolving attestation: ${o} from url: ${s}`);let i=this.startAbortTimer(Xe.ONE_SECOND*5),a=await fetch(`${s}/attestation/${o}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),a.status===200?await a.json():void 0}),Kn(this,"getVerifyUrl",o=>{let s=o||ax;return UWe.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${ax}`),s=ax),s}),Kn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let o=this.startAbortTimer(Xe.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(o),await s.json()}catch(o){this.logger.warn(o)}}),Kn(this,"persistPublicKey",async o=>{this.logger.debug(o,"persisting public key to local storage"),await this.store.setItem(this.storeKey,o),this.publicKey=o}),Kn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Kn(this,"isValidJwtAttestation",async o=>{let s=await this.getPublicKey();try{if(s)return this.validateAttestation(o,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(o,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Kn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Kn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{let i=await this.fetchPublicKey();i&&(await this.persistPublicKey(i),s(i))});let o=await this.fetchPromise;return this.fetchPromise=void 0,o}),Kn(this,"validateAttestation",(o,s)=>{let i=Fge(o,s.publicKey),a={hasExpired:(0,Xe.toMiliseconds)(i.exp)this.abortController.abort(),(0,Xe.toMiliseconds)(t))}},yGe=Object.defineProperty,wGe=(e,t,r)=>t in e?yGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Nye=(e,t,r)=>wGe(e,typeof t!="symbol"?t+"":t,r),rV=class extends M_{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,Nye(this,"context",DWe),Nye(this,"registerDeviceToken",async n=>{let{clientId:o,token:s,notificationType:i,enableEncrypted:a=!1}=n,c=`${LWe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:i,token:s,always_raw:a})})}),this.logger=Cr(r,this.context)}},bGe=Object.defineProperty,Rye=Object.getOwnPropertySymbols,xGe=Object.prototype.hasOwnProperty,vGe=Object.prototype.propertyIsEnumerable,nV=(e,t,r)=>t in e?bGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,z5=(e,t)=>{for(var r in t||(t={}))xGe.call(t,r)&&nV(e,r,t[r]);if(Rye)for(var r of Rye(t))vGe.call(t,r)&&nV(e,r,t[r]);return e},Ro=(e,t,r)=>nV(e,typeof t!="symbol"?t+"":t,r),oV=class extends H_{constructor(t,r,n=!0){super(t,r,n),this.core=t,this.logger=r,Ro(this,"context",HWe),Ro(this,"storagePrefix",Ru),Ro(this,"storageVersion",MWe),Ro(this,"events",new Map),Ro(this,"shouldPersist",!1),Ro(this,"init",async()=>{if(!R5())try{let o={eventId:tz(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:XF(this.core.relayer.protocol,this.core.relayer.version,Rz)}}};await this.sendEvent([o])}catch(o){this.logger.warn(o)}}),Ro(this,"createEvent",o=>{let{event:s="ERROR",type:i="",properties:{topic:a,trace:c}}=o,u=tz(),d=this.core.projectId||"",f=Date.now(),p=z5({eventId:u,timestamp:f,props:{event:s,type:i,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,p),this.shouldPersist=!0),p}),Ro(this,"getEvent",o=>{let{eventId:s,topic:i}=o;if(s)return this.events.get(s);let a=Array.from(this.events.values()).find(c=>c.props.properties.topic===i);if(a)return z5(z5({},a),this.setMethods(a.eventId))}),Ro(this,"deleteEvent",o=>{let{eventId:s}=o;this.events.delete(s),this.shouldPersist=!0}),Ro(this,"setEventListeners",()=>{this.core.heartbeat.on(Vs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(o=>{(0,Xe.fromMiliseconds)(Date.now())-(0,Xe.fromMiliseconds)(o.timestamp)>$We&&(this.events.delete(o.eventId),this.shouldPersist=!0)})})}),Ro(this,"setMethods",o=>({addTrace:s=>this.addTrace(o,s),setError:s=>this.setError(o,s)})),Ro(this,"addTrace",(o,s)=>{let i=this.events.get(o);i&&(i.props.properties.trace.push(s),this.events.set(o,i),this.shouldPersist=!0)}),Ro(this,"setError",(o,s)=>{let i=this.events.get(o);i&&(i.props.type=s,i.timestamp=Date.now(),this.events.set(o,i),this.shouldPersist=!0)}),Ro(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ro(this,"restore",async()=>{try{let o=await this.core.storage.getItem(this.storageKey)||[];if(!o.length)return;o.forEach(s=>{this.events.set(s.eventId,z5(z5({},s),this.setMethods(s.eventId)))})}catch(o){this.logger.warn(o)}}),Ro(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;let o=[];for(let[s,i]of this.events)i.props.type&&o.push(i);if(o.length!==0)try{if((await this.sendEvent(o)).ok)for(let s of o)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Ro(this,"sendEvent",async o=>{let s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${FWe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Rz}${s}`,{method:"POST",body:JSON.stringify(o)})}),Ro(this,"getAppDomain",()=>QF().url),this.logger=Cr(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},EGe=Object.defineProperty,Oye=Object.getOwnPropertySymbols,AGe=Object.prototype.hasOwnProperty,CGe=Object.prototype.propertyIsEnumerable,sV=(e,t,r)=>t in e?EGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Bye=(e,t)=>{for(var r in t||(t={}))AGe.call(t,r)&&sV(e,r,t[r]);if(Oye)for(var r of Oye(t))CGe.call(t,r)&&sV(e,r,t[r]);return e},zr=(e,t,r)=>sV(e,typeof t!="symbol"?t+"":t,r),iV=class e extends P_{constructor(t){var r;super(t),zr(this,"protocol",Uye),zr(this,"version",Dye),zr(this,"name",rP),zr(this,"relayUrl"),zr(this,"projectId"),zr(this,"customStoragePrefix"),zr(this,"events",new Rp.EventEmitter),zr(this,"logger"),zr(this,"heartbeat"),zr(this,"relayer"),zr(this,"crypto"),zr(this,"storage"),zr(this,"history"),zr(this,"expirer"),zr(this,"pairing"),zr(this,"verify"),zr(this,"echoClient"),zr(this,"linkModeSupportedApps"),zr(this,"eventClient"),zr(this,"initialized",!1),zr(this,"logChunkController"),zr(this,"on",(a,c)=>this.events.on(a,c)),zr(this,"once",(a,c)=>this.events.once(a,c)),zr(this,"off",(a,c)=>this.events.off(a,c)),zr(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),zr(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;let d={topic:a,message:c,publishedAt:Date.now(),transportType:Vr.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:u})});let n=this.getGlobalCore(t?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Lye,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";let o=X2({level:typeof t?.logger=="string"&&t.logger?t.logger:cWe.logger,name:rP}),{logger:s,chunkLoggerController:i}=Fl({opts:o,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=i,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Cr(s,this.name),this.heartbeat=new iw,this.crypto=new Fz(this,this.logger,t?.keychain),this.history=new Xz(this,this.logger),this.expirer=new eV(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new aw(Bye(Bye({},lWe),t?.storageOptions)),this.relayer=new Yz({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Qz(this,this.logger),this.verify=new tV(this,this.logger,this.storage),this.echoClient=new rV(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new oV(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){let r=new e(t);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(AWe,n),r}get context(){return sr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(dye,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(dye)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(t){var r;try{if(this.isGlobalCoreDisabled())return;let n=`_walletConnectCore_${((r=t.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=t}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},Yye=iV});var sP,Nt,t2e,r2e,n2e,vV,cV,Qye,SGe,Xye,IGe,lx,TGe,Zo,lV,Bu,_Ge,PGe,NGe,RGe,OGe,BGe,kGe,UGe,iP,oP,DGe,LGe,MGe,e2e,HGe,$Ge,dV,lr,Go,Ee,fV,pV,hV,mV,gV,yV,wV,FGe,zGe,uV,bV,VGe,jGe,jt,xV,o2e,s2e=b(()=>{l();sP=Ht(ks(),1);Jye();DH();eP();gh();Nt=Ht(jd(),1);$c();t2e="wc",r2e=2,n2e="client",vV=`${t2e}@${r2e}:${n2e}:`,cV={name:n2e,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Qye="WALLETCONNECT_DEEPLINK_CHOICE",SGe="proposal",Xye="Proposal expired",IGe="session",lx=Nt.SEVEN_DAYS,TGe="engine",Zo={wc_sessionPropose:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Nt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Nt.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1119}}},lV={min:Nt.FIVE_MINUTES,max:Nt.SEVEN_DAYS},Bu={idle:"IDLE",active:"ACTIVE"},_Ge={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},PGe="request",NGe=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],RGe="wc",OGe="auth",BGe="authKeys",kGe="pairingTopics",UGe="requests",iP=`${RGe}@${1.5}:${OGe}:`,oP=`${iP}:PUB_KEY`,DGe=Object.defineProperty,LGe=Object.defineProperties,MGe=Object.getOwnPropertyDescriptors,e2e=Object.getOwnPropertySymbols,HGe=Object.prototype.hasOwnProperty,$Ge=Object.prototype.propertyIsEnumerable,dV=(e,t,r)=>t in e?DGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,lr=(e,t)=>{for(var r in t||(t={}))HGe.call(t,r)&&dV(e,r,t[r]);if(e2e)for(var r of e2e(t))$Ge.call(t,r)&&dV(e,r,t[r]);return e},Go=(e,t)=>LGe(e,MGe(t)),Ee=(e,t,r)=>dV(e,typeof t!="symbol"?t+"":t,r),fV=class extends F_{constructor(t){super(t),Ee(this,"name",TGe),Ee(this,"events",new sP.default),Ee(this,"initialized",!1),Ee(this,"requestQueue",{state:Bu.idle,queue:[]}),Ee(this,"sessionRequestQueue",{state:Bu.idle,queue:[]}),Ee(this,"emittedSessionRequests",new O7({limit:500})),Ee(this,"requestQueueDelay",Nt.ONE_SECOND),Ee(this,"expectedPairingMethodMap",new Map),Ee(this,"recentlyDeletedMap",new Map),Ee(this,"recentlyDeletedLimit",200),Ee(this,"relayMessageCache",[]),Ee(this,"pendingSessions",new Map),Ee(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Zo)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,Nt.toMiliseconds)(this.requestQueueDelay)))}),Ee(this,"connect",async r=>{var n;this.isInitialized(),await this.confirmOnlineStateOrThrow();let o=Go(lr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(o),o.optionalNamespaces=jge(o.requiredNamespaces,o.optionalNamespaces),o.requiredNamespaces={};let{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:d,authentication:f,walletPay:p}=o,h=((n=f?.[0])==null?void 0:n.ttl)||Zo.wc_sessionPropose.req.ttl||Nt.FIVE_MINUTES;this.validateRequestExpiry(h);let y=s,w,x=!1;try{if(y){let N=this.client.core.pairing.pairings.get(y);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),x=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${y}) failed`),N}if(!y||!x){let{topic:N,uri:L}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});y=N,w=L}if(!y){let{message:N}=Ie("NO_MATCHING_KEY",`connect() pairing topic: ${y}`);throw new Error(N)}let v=await this.client.core.crypto.generateKeyPair(),T=pn(h),E=lr(Go(lr(lr({requiredNamespaces:i,optionalNamespaces:a,relays:d??[{protocol:aV}],proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:T,pairingTopic:y},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Tn()}),(f||p)&&{requests:{authentication:f?.map(N=>{let{domain:L,chains:P,nonce:R,uri:I,exp:B,nbf:C,type:A,statement:U,requestId:H,resources:k,signatureTypes:F}=N;return{domain:L,chains:P,nonce:R,type:A??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:B,nbf:C,statement:U,requestId:H,resources:k,signatureTypes:F}}),walletPay:p}}),S=cr("session_connect",E.id),{reject:_,resolve:O,done:D}=Pp(h,Xye),M=({id:N})=>{N===E.id&&(this.client.events.off("proposal_expire",M),this.pendingSessions.delete(E.id),this.events.emit(S,{error:{message:Xye,code:0}}))};return this.client.events.on("proposal_expire",M),this.events.once(S,({error:N,session:L})=>{this.client.events.off("proposal_expire",M),N?_(N):L&&O(L)}),await this.setProposal(E.id,E),await this.sendProposeSession({proposal:E,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:E.id}}}).catch(N=>{throw this.deleteProposal(E.id),N}),{uri:w,approval:D}}),Ee(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),Ee(this,"approve",async r=>{var n,o,s;let i=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[Ac.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(L){throw i.setError(Vm.no_internet_connection),L}try{await this.isValidProposalId(r?.id)}catch(L){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),i.setError(Vm.proposal_not_found),L}try{await this.isValidApprove(r)}catch(L){throw this.client.logger.error("approve() -> isValidApprove() failed"),i.setError(Vm.session_approve_namespace_validation_failure),L}let{id:a,relayProtocol:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=r,y=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:i.eventId});let{pairingTopic:w,proposer:x,requiredNamespaces:v,optionalNamespaces:T}=y,E=(o=this.client.core.eventClient)==null?void 0:o.getEvent({topic:w});E||(E=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ac.session_approve_started,properties:{topic:w,trace:[Ac.session_approve_started,Ac.session_namespaces_validation_success]}}));let S=await this.client.core.crypto.generateKeyPair(),_=x.publicKey,O=await this.client.core.crypto.generateSharedKey(S,_),D=Go(lr(lr(lr({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:S,metadata:this.client.metadata},expiry:pn(lx)},d&&{sessionProperties:d}),f&&{scopedProperties:f}),p&&{sessionConfig:p}),{proposalRequestsResponses:h}),M=Vr.relay;E.addTrace(Ac.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:M,internal:{skipSubscribe:!0}})}catch(L){throw E.setError(Vm.subscribe_session_topic_failure),L}E.addTrace(Ac.subscribe_session_topic_success);let N=Go(lr({},D),{topic:O,requiredNamespaces:v,optionalNamespaces:T,pairingTopic:w,acknowledged:!1,self:D.controller,peer:{publicKey:x.publicKey,metadata:x.metadata},controller:S,transportType:Vr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(O,N),E.addTrace(Ac.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:y,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:S},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:lr({correlationId:a},this.getTVFApproveParams(N))}}),E.addTrace(Ac.session_approve_publish_success)}catch(L){throw this.client.logger.error(L),this.client.session.delete(O,Rr("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),L}return this.client.core.eventClient.deleteEvent({eventId:E.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:x.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(O,pn(lx)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),Ee(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(i){throw this.client.logger.error("reject() -> isValidReject() failed"),i}let{id:n,reason:o}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(i){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),i}s&&await this.sendError({id:n,topic:s,error:o,rpcOpts:Zo.wc_sessionPropose.reject}),await this.deleteProposal(n)}),Ee(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}let{topic:n,namespaces:o}=r,{done:s,resolve:i,reject:a}=Pp(Nt.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tn(),u=_n().toString(),d=this.client.session.get(n).namespaces;return this.events.once(cr("session_update",c),({error:f})=>{f?a(f):i()}),await this.client.session.update(n,{namespaces:o}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:o},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:d}),a(f)}),{acknowledged:s}}),Ee(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}let{topic:n}=r,o=Tn(),{done:s,resolve:i,reject:a}=Pp(Nt.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(cr("session_extend",o),({error:c})=>{c?a(c):i()}),await this.setExpiry(n,pn(lx)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:o,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),Ee(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}let{chainId:n,request:o,topic:s,expiry:i=Zo.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let c=Tn(),u=_n().toString(),{done:d,resolve:f,reject:p}=Pp(i,"Request expired. Please try again.");this.events.once(cr("session_request",c),({error:x,result:v})=>{x?p(x):f(v)});let h="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:Go(lr({},o),{expiryTimestamp:pn(i)}),chainId:n},expiry:i,throwOnFailedPublish:!0,appLink:y}).catch(x=>p(x)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),await d();let w={request:Go(lr({},o),{expiryTimestamp:pn(i)}),chainId:n};return await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:w,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),x()}),new Promise(async x=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){let T=await B1e(this.client.core.storage,Qye);await O1e({id:c,topic:s,wcDeepLink:T})}x()}),d()]).then(x=>x[2])}),Ee(this,"respond",async r=>{var n,o;this.isInitialized();let s=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||((o=(n=r?.response)==null?void 0:n.id)==null?void 0:o.toString()),trace:[Ac.session_request_response_started]}});try{await this.isValidRespond(r)}catch(f){throw s.addTrace(f?.message),s.setError(Vm.session_request_response_validation_failure),f}s.addTrace(Ac.session_request_response_validation_success);let{topic:i,response:a}=r,{id:c}=a,u=this.client.session.get(i);u.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let d=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(Ac.session_request_response_publish_started),Jr(a)?await this.sendResult({id:c,topic:i,result:a.result,throwOnFailedPublish:!0,appLink:d}):Ir(a)&&await this.sendError({id:c,topic:i,error:a.error,appLink:d}),this.cleanupAfterResponse(r)}catch(f){throw s.addTrace(f?.message),s.setError(Vm.session_request_response_publish_failure),f}}),Ee(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(o){throw this.client.logger.error("ping() -> isValidPing() failed"),o}let{topic:n}=r;if(this.client.session.keys.includes(n)){let o=Tn(),s=_n().toString(),{done:i,resolve:a,reject:c}=Pp(Nt.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(cr("session_ping",o),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),Ee(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);let{topic:n,event:o,chainId:s}=r,i=_n().toString(),a=Tn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:o,chainId:s},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:a})}),Ee(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Rr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:o}=Ie("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(o)}}),Ee(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>qge(n,r)))),Ee(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),Ee(this,"authenticate",async(r,n)=>{var o;this.isInitialized(),this.isValidAuthenticate(r);let s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((o=this.client.metadata.redirect)==null?void 0:o.linkMode),i=s?Vr.link_mode:Vr.relay;i===Vr.relay&&await this.confirmOnlineStateOrThrow();let{chains:a,statement:c="",uri:u,domain:d,nonce:f,type:p,exp:h,nbf:y,methods:w=[],expiry:x}=r,v=[...r.resources||[]],{topic:T,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:i});this.client.logger.info({message:"Generated new pairing",pairing:{topic:T,uri:E}});let S=await this.client.core.crypto.generateKeyPair(),_=tx(S);if(await Promise.all([this.client.auth.authKeys.set(oP,{responseTopic:_,publicKey:S}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:T})]),await this.client.core.relayer.subscribe(_,{transportType:i}),this.client.logger.info(`sending request to new pairing topic: ${T}`),w.length>0){let{namespace:k}=bl(a[0]),F=ege(k,"request",w);k5(v)&&(F=tge(F,v.pop())),v.push(F)}let O=x&&x>Zo.wc_sessionAuthenticate.req.ttl?x:Zo.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:p??"caip122",chains:a,statement:c,aud:u,domain:d,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:y,resources:v},requester:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:pn(O)},M={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},N={requiredNamespaces:{},optionalNamespaces:M,relays:[{protocol:"irn"}],pairingTopic:T,proposer:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:pn(Zo.wc_sessionPropose.req.ttl),id:Tn()},{done:L,resolve:P,reject:R}=Pp(O,"Request expired"),I=Tn(),B=cr("session_connect",N.id),C=cr("session_request",I),A=async({error:k,session:F})=>{this.events.off(C,U),k?R(k):F&&P({session:F})},U=async k=>{var F,j,W;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),k.error){let ye=Rr("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return k.error.code===ye.code?void 0:(this.events.off(B,A),R(k.error.message))}await this.deleteProposal(N.id),this.events.off(B,A);let{cacaos:ae,responder:te}=k.result,X=[],pe=[];for(let ye of ae){await az({cacao:ye,projectId:this.client.core.projectId})||(this.client.logger.error(ye,"Signature verification failed"),R(Rr("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:Re}=ye,Et=k5(Re.resources),kt=[K7(Re.iss)],At=B5(Re.iss);if(Et){let ur=lz(Et),_r=uz(Et);X.push(...ur),kt.push(..._r)}for(let ur of kt)pe.push(`${ur}:${At}`)}let me=await this.client.core.crypto.generateSharedKey(S,te.publicKey),Ne;X.length>0&&(Ne={topic:me,acknowledged:!0,self:{publicKey:S,metadata:this.client.metadata},peer:te,controller:te.publicKey,expiry:pn(lx),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:T,namespaces:Ez([...new Set(X)],[...new Set(pe)]),transportType:i},await this.client.core.relayer.subscribe(me,{transportType:i}),await this.client.session.set(me,Ne),T&&await this.client.core.pairing.updateMetadata({topic:T,metadata:te.metadata}),Ne=this.client.session.get(me)),(F=this.client.metadata.redirect)!=null&&F.linkMode&&(j=te.metadata.redirect)!=null&&j.linkMode&&(W=te.metadata.redirect)!=null&&W.universal&&n&&(this.client.core.addLinkModeSupportedApp(te.metadata.redirect.universal),this.client.session.update(me,{transportType:Vr.link_mode})),P({auths:ae,session:Ne})};this.events.once(B,A),this.events.once(C,U);let H;try{if(s){let k=dr("wc_sessionAuthenticate",D,I);this.client.core.history.set(T,k);let F=await this.client.core.crypto.encode("",k,{type:ex,encoding:Np});H=M5(n,T,F)}else await Promise.all([this.sendRequest({topic:T,method:"wc_sessionAuthenticate",params:D,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:T,method:"wc_sessionPropose",params:N,expiry:Zo.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(k){throw this.events.off(B,A),this.events.off(C,U),k}return await this.setProposal(N.id,N),await this.setAuthRequest(I,{request:Go(lr({},D),{verifyContext:{}}),pairingTopic:T,transportType:i}),{uri:H??E,response:L}}),Ee(this,"approveSessionAuthenticate",async r=>{let{id:n,auths:o}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[jm.authenticated_session_approve_started]}});try{this.isInitialized()}catch(x){throw s.setError(cx.no_internet_connection),x}let i=this.getPendingAuthRequest(n);if(!i)throw s.setError(cx.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);let a=i.transportType||Vr.relay;a===Vr.relay&&await this.confirmOnlineStateOrThrow();let c=i.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=tx(c),f={type:vl,receiverPublicKey:c,senderPublicKey:u},p=[],h=[];for(let x of o){if(!await az({cacao:x,projectId:this.client.core.projectId})){s.setError(cx.invalid_cacao);let _=Rr("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:_,encodeOpts:f}),new Error(_.message)}s.addTrace(jm.cacaos_verified);let{p:v}=x,T=k5(v.resources),E=[K7(v.iss)],S=B5(v.iss);if(T){let _=lz(T),O=uz(T);p.push(..._),E.push(...O)}for(let _ of E)h.push(`${_}:${S}`)}let y=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(jm.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:i.requester.metadata},controller:c,expiry:pn(lx),authentication:o,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:Ez([...new Set(p)],[...new Set(h)]),transportType:a},s.addTrace(jm.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(x){throw s.setError(cx.subscribe_authenticated_session_topic_failure),x}s.addTrace(jm.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),s.addTrace(jm.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}s.addTrace(jm.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:o,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,a)})}catch(x){throw s.setError(cx.authenticated_session_approve_publish_failure),x}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}}),Ee(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();let{id:n,reason:o}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let i=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tx(i),u={type:vl,receiverPublicKey:i,senderPublicKey:a};await this.sendError({id:n,topic:c,error:o,encodeOpts:u,rpcOpts:Zo.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),Ee(this,"formatAuthMessage",r=>{this.isInitialized();let{request:n,iss:o}=r;return cz(n,o)}),Ee(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{let r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),Ee(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(s=>{var i,a;return((i=s.peerMetadata)==null?void 0:i.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),Ee(this,"deleteSession",async r=>{var n;let{topic:o,expirerHasDeleted:s=!1,emitEvent:i=!0,id:a=0}=r,{self:c}=this.client.session.get(o);await this.client.core.relayer.unsubscribe(o),await this.client.session.delete(o,Rr("USER_DISCONNECTED")),this.addToRecentlyDeleted(o,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(o)&&await this.client.core.crypto.deleteSymKey(o),s||this.client.core.expirer.del(o),this.client.core.storage.removeItem(Qye).catch(u=>this.client.logger.warn(u)),o===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Bu.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===o).map(u=>this.deletePendingSessionRequest(u.id,Rr("USER_DISCONNECTED")))),i&&this.client.events.emit("session_delete",{id:a,topic:o})}),Ee(this,"deleteProposal",async(r,n)=>{if(n)try{let o=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:o.pairingTopic})?.setError(Vm.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Rr("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),Ee(this,"deletePendingSessionRequest",async(r,n,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),o&&(this.sessionRequestQueue.state=Bu.idle,this.client.events.emit("session_request_expire",{id:r}))}),Ee(this,"deletePendingAuthRequest",async(r,n,o=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)])}),Ee(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),Ee(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,pn(Zo.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),Ee(this,"setAuthRequest",async(r,n)=>{let{request:o,pairingTopic:s,transportType:i=Vr.relay}=n;this.client.core.expirer.set(r,o.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:o.authPayload,requester:o.requester,expiryTimestamp:o.expiryTimestamp,id:r,pairingTopic:s,verifyContext:o.verifyContext,transportType:i})}),Ee(this,"setPendingSessionRequest",async r=>{let{id:n,topic:o,params:s,verifyContext:i}=r,a=s.request.expiryTimestamp||pn(Zo.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:o,params:s,verifyContext:i})}),Ee(this,"sendRequest",async r=>{let{topic:n,method:o,params:s,expiry:i,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:d,tvf:f,publishOpts:p={}}=r,h=dr(o,s,c),y,w=!!d;try{let T=w?Np:Ts;y=await this.client.core.crypto.encode(n,h,{encoding:T})}catch(T){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),T}let x;if(NGe.includes(o)){let T=Wi(JSON.stringify(h)),E=Wi(y);x=await this.client.core.verify.register({id:E,decryptedId:T})}let v=lr(lr({},Zo[o].req),p);if(v.attestation=x,i&&(v.ttl=i),a&&(v.id=a),this.client.core.history.set(n,h),w){let T=M5(d,n,y);await global.Linking.openURL(T,this.client.name)}else v.tvf=Go(lr({},f),{correlationId:h.id}),u?(v.internal=Go(lr({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,y,v)):this.client.core.relayer.publish(n,y,v).catch(T=>this.client.logger.error(T));return h.id}),Ee(this,"sendProposeSession",async r=>{let{proposal:n,publishOpts:o}=r,s=dr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);let i=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:Ts}),a=Wi(JSON.stringify(s)),c=Wi(i),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:i},opts:Go(lr({},o),{publishMethod:"wc_proposeSession",attestation:u})})}),Ee(this,"sendApproveSession",async r=>{let{sessionTopic:n,pairingProposalResponse:o,proposal:s,sessionSettleRequest:i,publishOpts:a}=r,c=bo(s.id,o),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Ts}),d=dr("wc_sessionSettle",i,a?.id),f=await this.client.core.crypto.encode(n,d,{encoding:Ts});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:Go(lr({},a),{publishMethod:"wc_approveSession"})})}),Ee(this,"sendResult",async r=>{let{id:n,topic:o,result:s,throwOnFailedPublish:i,encodeOpts:a,appLink:c}=r,u=bo(n,s),d,f=c&&typeof(global==null?void 0:global.Linking)<"u";try{let y=f?Np:Ts;d=await this.client.core.crypto.encode(o,u,Go(lr({},a||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${o} failed`),y}let p,h;try{p=await this.client.core.history.get(o,n);let y=p.request;try{h=this.getTVFParams(n,y.params,s)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${o}, ${n}) failed`),y}if(f){let y=M5(c,o,d);await global.Linking.openURL(y,this.client.name)}else{let y=p.request.method,w=Zo[y].res;w.tvf=Go(lr({},h),{correlationId:n}),i?(w.internal=Go(lr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(o,d,w)):this.client.core.relayer.publish(o,d,w).catch(x=>this.client.logger.error(x))}await this.client.core.history.resolve(u)}),Ee(this,"sendError",async r=>{let{id:n,topic:o,error:s,encodeOpts:i,rpcOpts:a,appLink:c}=r,u=la(n,s),d,f=c&&typeof(global==null?void 0:global.Linking)<"u";try{let h=f?Np:Ts;d=await this.client.core.crypto.encode(o,u,Go(lr({},i||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${o} failed`),h}let p;try{p=await this.client.core.history.get(o,n)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${o}, ${n}) failed`),h}if(f){let h=M5(c,o,d);await global.Linking.openURL(h,this.client.name)}else{let h=p.request.method,y=a||Zo[h].res;this.client.core.relayer.publish(o,d,y)}await this.client.core.history.resolve(u)}),Ee(this,"cleanup",async()=>{let r=[],n=[];this.client.session.getAll().forEach(o=>{let s=!1;ka(o.expiry)&&(s=!0),this.client.core.crypto.keychain.has(o.topic)||(s=!0),s&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{ka(o.expiryTimestamp)&&n.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession({topic:o})),...n.map(o=>this.deleteProposal(o))])}),Ee(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),Ee(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),Ee(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Bu.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Bu.active;let r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Bu.idle}),Ee(this,"processRequest",async r=>{let{topic:n,payload:o,attestation:s,transportType:i,encryptedId:a}=r,c=o.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:o,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,o);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,o);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,o);case"wc_sessionPing":return await this.onSessionPingRequest(n,o);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,o);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(n,o);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),Ee(this,"onRelayEventResponse",async r=>{let{topic:n,payload:o,transportType:s}=r,i=(await this.client.core.history.get(n,o.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(n,o,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,o);case"wc_sessionExtend":return this.onSessionExtendResponse(n,o);case"wc_sessionPing":return this.onSessionPingResponse(n,o);case"wc_sessionRequest":return this.onSessionRequestResponse(n,o);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,o);default:return this.client.logger.info(`Unsupported response method ${i}`)}}),Ee(this,"onRelayEventUnknownPayload",r=>{let{topic:n}=r,{message:o}=Ie("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)}),Ee(this,"shouldIgnorePairingRequest",r=>{let{topic:n,requestMethod:o}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(o)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),Ee(this,"onSessionProposeRequest",async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i}=r,{params:a,id:c}=o;try{let u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Nu.proposal_listener_not_found)),this.isValidConnect(lr({},o.params));let d=a.expiryTimestamp||pn(Zo.wc_sessionPropose.req.ttl),f=lr({id:c,pairingTopic:n,expiryTimestamp:d,attestation:s,encryptedId:i},a);await this.setProposal(c,f);let p=await this.getVerifyContext({attestationId:s,hash:Wi(JSON.stringify(o)),encryptedId:i,metadata:f.proposer.metadata});u?.addTrace(Cl.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:p})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Zo.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),Ee(this,"onSessionProposeResponse",async(r,n,o)=>{let{id:s}=n;if(Jr(n)){let{result:i}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});let a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});let c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});let u=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let d=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:d,pairingTopic:r,proposalId:s,publicKey:c});let f=await this.client.core.relayer.subscribe(d,{transportType:o});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(Ir(n)){await this.deleteProposal(s);let i=cr("session_connect",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners, 954`);this.events.emit(i,{error:n.error})}}),Ee(this,"onSessionSettleRequest",async(r,n)=>{let{id:o,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:i,controller:a,expiry:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=n.params,y=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!y)return this.client.logger.error(`Pending session not found for topic ${r}`);let w=this.client.proposal.get(y.proposalId),x=Go(lr(lr(lr({topic:r,relay:i,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),f&&{scopedProperties:f}),p&&{sessionConfig:p}),{transportType:Vr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(x.topic,x),await this.setExpiry(x.topic,x.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:x.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(x),await this.sendResult({id:n.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:x}),this.events.emit(cr("session_connect",y.proposalId),{session:x})}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"onSessionSettleResponse",async(r,n)=>{let{id:o}=n;Jr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(cr("session_approve",o),{})):Ir(n)&&(await this.client.session.delete(r,Rr("USER_DISCONNECTED")),this.events.emit(cr("session_approve",o),{error:n.error}))}),Ee(this,"onSessionUpdateRequest",async(r,n)=>{let{params:o,id:s}=n;try{let i=`${r}_session_update`,a=$m.get(i);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Rr("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(lr({topic:r},o));try{$m.set(i,s),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw $m.delete(i),c}this.client.events.emit("session_update",{id:s,topic:r,params:o})}catch(i){await this.sendError({id:s,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3){let{id:o}=n,s=cr("session_update",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_update",o),{}):Ir(n)&&this.events.emit(cr("session_update",o),{error:n.error})}),Ee(this,"onSessionExtendRequest",async(r,n)=>{let{id:o}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,pn(lx)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}}),Ee(this,"onSessionExtendResponse",(r,n)=>{let{id:o}=n,s=cr("session_extend",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_extend",o),{}):Ir(n)&&this.events.emit(cr("session_extend",o),{error:n.error})}),Ee(this,"onSessionPingRequest",async(r,n)=>{let{id:o}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}}),Ee(this,"onSessionPingResponse",(r,n)=>{let{id:o}=n,s=cr("session_ping",o);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Jr(n)?this.events.emit(cr("session_ping",o),{}):Ir(n)&&this.events.emit(cr("session_ping",o),{error:n.error})},500)}),Ee(this,"onSessionDeleteRequest",async(r,n)=>{let{id:o}=n;try{await this.isValidDisconnect({topic:r,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Rr("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:o})}catch(s){this.client.logger.error(s)}}),Ee(this,"onSessionRequest",async r=>{var n,o,s;let{topic:i,payload:a,attestation:c,encryptedId:u,transportType:d}=r,{id:f,params:p}=a;try{await this.isValidRequest(lr({topic:i},p));let h=this.client.session.get(i),y=await this.getVerifyContext({attestationId:c,hash:Wi(JSON.stringify(dr("wc_sessionRequest",p,f))),encryptedId:u,metadata:h.peer.metadata,transportType:d}),w={id:f,topic:i,params:p,verifyContext:y};await this.setPendingSessionRequest(w),d===Vr.link_mode&&(n=h.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((o=h.peer.metadata.redirect)==null?void 0:o.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:i,error:h}),this.client.logger.error(h)}}),Ee(this,"onSessionRequestResponse",(r,n)=>{let{id:o}=n,s=cr("session_request",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(cr("session_request",o),{error:n.error})}),Ee(this,"onSessionEventRequest",async(r,n)=>{let{id:o,params:s}=n;try{let i=`${r}_session_event_${s.event.name}`,a=$m.get(i);if(a&&this.isRequestOutOfSync(a,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit(lr({topic:r},s)),this.client.events.emit("session_event",{id:o,topic:r,params:s}),$m.set(i,o)}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"onSessionAuthenticateResponse",(r,n)=>{let{id:o}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Jr(n)?this.events.emit(cr("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(cr("session_request",o),{error:n.error})}),Ee(this,"onSessionAuthenticateRequest",async r=>{var n;let{topic:o,payload:s,attestation:i,encryptedId:a,transportType:c}=r;try{let{requester:u,authPayload:d,expiryTimestamp:f}=s.params,p=await this.getVerifyContext({attestationId:i,hash:Wi(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:o,id:s.id,authPayload:d,verifyContext:p,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:o,transportType:c}),c===Vr.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:o,params:s.params,id:s.id,verifyContext:p})}catch(u){this.client.logger.error(u);let d=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:vl,receiverPublicKey:d,senderPublicKey:f};await this.sendError({id:s.id,topic:o,error:u,encodeOpts:h,rpcOpts:Zo.wc_sessionAuthenticate.autoReject,appLink:p})}}),Ee(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),Ee(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bu.idle,this.processSessionRequestQueue()},(0,Nt.toMiliseconds)(this.requestQueueDelay))}),Ee(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{let o=this.client.core.history.pending;o.length>0&&o.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(cr("session_request",s.request.id),{error:n})})}),Ee(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Bu.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),Ee(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Bu.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),Ee(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:dr("wc_sessionPropose",Go(lr({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),Ee(this,"isValidConnect",async r=>{if(!_s(r)){let{message:u}=Ie("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:s,sessionProperties:i,scopedProperties:a,relays:c}=r;if(Ln(n)||await this.isValidPairingTopic(n),!Qge(c,!0)){let{message:u}=Ie("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(o&&!Ln(o)&&xc(o)!==0){let u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(o,"requiredNamespaces")}if(s&&!Ln(s)&&xc(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),i&&!Ln(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!Ln(a)){this.validateSessionProps(a,"scopedProperties");let u=Object.keys(o||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(d=>u.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),Ee(this,"validateNamespaces",(r,n)=>{let o=Jge(r,"connect()",n);if(o)throw new Error(o.message)}),Ee(this,"isValidApprove",async r=>{if(!_s(r))throw new Error(Ie("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:o,relayProtocol:s,sessionProperties:i,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let c=this.client.proposal.get(n),u=X7(o,"approve()");if(u)throw new Error(u.message);let d=Iz(c.requiredNamespaces,o,"approve()");if(d)throw new Error(d.message);if(!An(s,!0)){let{message:f}=Ie("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(i&&!Ln(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!Ln(a)){this.validateSessionProps(a,"scopedProperties");let f=new Set(Object.keys(o));if(!Object.keys(a).every(p=>f.has(p.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),Ee(this,"isValidReject",async r=>{if(!_s(r)){let{message:s}=Ie("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:o}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!eye(o)){let{message:s}=Ie("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(s)}}),Ee(this,"isValidSessionSettleRequest",r=>{if(!_s(r)){let{message:u}=Ie("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}let{relay:n,controller:o,namespaces:s,expiry:i}=r;if(!Cz(n)){let{message:u}=Ie("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}let a=Gge(o,"onSessionSettleRequest()");if(a)throw new Error(a.message);let c=X7(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ka(i)){let{message:u}=Ie("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),Ee(this,"isValidUpdate",async r=>{if(!_s(r)){let{message:c}=Ie("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}let{topic:n,namespaces:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),i=X7(o,"update()");if(i)throw new Error(i.message);let a=Iz(s.requiredNamespaces,o,"update()");if(a)throw new Error(a.message)}),Ee(this,"isValidExtend",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),Ee(this,"isValidRequest",async r=>{if(!_s(r)){let{message:c}=Ie("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}let{topic:n,request:o,chainId:s,expiry:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!Sz(a,s)){let{message:c}=Ie("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!tye(o)){let{message:c}=Ie("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(c)}if(!oye(a,s,o.method)){let{message:c}=Ie("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(c)}this.validateRequestExpiry(i)}),Ee(this,"isValidRespond",async r=>{var n;if(!_s(r)){let{message:a}=Ie("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}let{topic:o,response:s}=r;try{await this.isValidSessionTopic(o)}catch(a){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),a}if(!rye(s)){let{message:a}=Ie("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}let i=this.client.pendingRequest.get(s.id);if(i.topic!==o){let{message:a}=Ie("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${i.topic}, received topic: ${o}`);throw new Error(a)}}),Ee(this,"isValidPing",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),Ee(this,"isValidEmit",async r=>{if(!_s(r)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:o,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:i}=this.client.session.get(n);if(!Sz(i,s)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!nye(o)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}if(!sye(i,s,o.name)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}}),Ee(this,"isValidDisconnect",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),Ee(this,"isValidAuthenticate",r=>{let{chains:n,uri:o,domain:s,nonce:i}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!An(o,!1))throw new Error("uri is required parameter");if(!An(s,!1))throw new Error("domain is required parameter");if(!An(i,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>bl(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:a}=bl(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),Ee(this,"getVerifyContext",async r=>{let{attestationId:n,hash:o,encryptedId:s,metadata:i,transportType:a}=r,c={verified:{verifyUrl:i.verifyUrl||ax,validation:"UNKNOWN",origin:i.url||""}};try{if(a===Vr.link_mode){let d=this.getAppLinkIfEnabled(i,a);return c.verified.validation=d&&new URL(d).origin===new URL(i.url).origin?"VALID":"INVALID",c}let u=await this.client.core.verify.resolve({attestationId:n,hash:o,encryptedId:s,verifyUrl:i.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),Ee(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((o,s)=>{if(o==null){let{message:i}=Ie("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${o} for key ${Object.keys(r)[s]}`);throw new Error(i)}})}),Ee(this,"getPendingAuthRequest",r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),Ee(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let o=0,s=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(o++>=s)break;this.recentlyDeletedMap.delete(i)}}}),Ee(this,"checkRecentlyDeleted",r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:o}=Ie("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(o)}}),Ee(this,"isLinkModeEnabled",(r,n)=>{var o,s,i,a,c,u,d,f,p;return!r||n!==Vr.link_mode?!1:((s=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:s.linkMode)===!0&&((a=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((d=r?.redirect)==null?void 0:d.universal)!==void 0&&((f=r?.redirect)==null?void 0:f.universal)!==""&&((p=r?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),Ee(this,"getAppLinkIfEnabled",(r,n)=>{var o;return this.isLinkModeEnabled(r,n)?(o=r?.redirect)==null?void 0:o.universal:void 0}),Ee(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;let n=ez(r,"topic")||"",o=decodeURIComponent(ez(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:Vr.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:o,sessionExists:s})}),Ee(this,"registerLinkModeListeners",async()=>{var r;if(R5()||_p()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){let n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);let o=await n.getInitialURL();o&&setTimeout(()=>{this.handleLinkModeMessage({url:o})},50)}}}),Ee(this,"getTVFApproveParams",r=>{try{let n=vz(r.namespaces),o=zge(r.namespaces),s=Vge(r.namespaces),i=r.sessionProperties,a=r.scopedProperties;return{approvedChains:n,approvedMethods:o,approvedEvents:s,sessionProperties:i,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}}),Ee(this,"getTVFParams",(r,n,o)=>{var s,i,a;if(!((s=n.request)!=null&&s.method))return{};let c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{let u=this.extractTxHashesFromResult(n.request,o);c.txHashes=u,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(i=n.request.params)==null?void 0:i[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),Ee(this,"isValidContractData",r=>{var n;if(!r)return!1;try{let o=r?.data||((n=r?.[0])==null?void 0:n.data);if(!o.startsWith("0x"))return!1;let s=o.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),Ee(this,"extractTxHashesFromResult",(r,n)=>{var o;try{if(!n)return[];let s=r.method,i=_Ge[s];if(s==="sui_signTransaction")return[G1e(n.transactionBytes)];if(s==="near_signTransaction")return[sz(n)];if(s==="near_signTransactions")return n.map(c=>sz(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(o=n.tx_json)==null?void 0:o.hash];if(s==="polkadot_signTransaction")return[lye({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return El(n)?n.map(c=>iz(c)):[iz(n)];if(s==="cosmos_signDirect")return[Y1e(n)];if(s==="wallet_sendCalls")return J1e(n);if(typeof n=="string")return[n];let a=n[i.key];if(El(a))return s==="solana_signAllTransactions"?a.map(c=>Z1e(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{let t=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(t);for(let[n,o]of Object.entries(r))for(let s of o)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){let{topic:r,message:n,attestation:o,transportType:s}=t,{publicKey:i}=this.client.auth.authKeys.keys.includes(oP)?this.client.auth.authKeys.get(oP):{responseTopic:void 0,publicKey:void 0};try{let a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i,encoding:s===Vr.link_mode?Np:Ts});Hc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:o,transportType:s,encryptedId:Wi(n)})):ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(La.expired,async t=>{let{topic:r,id:n}=z7(t.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Ie("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Ie("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(zm.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(zm.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!An(t,!1)){let{message:r}=Ie("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.core.pairing.pairings.get(t).expiry)){let{message:r}=Ie("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!An(t,!1)){let{message:r}=Ie("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});let{message:r}=Ie("EXPIRED",`session topic: ${t}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(t)){let{message:r}=Ie("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(An(t,!1)){let{message:r}=Ie("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{let{message:r}=Ie("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!Xge(t)){let{message:r}=Ie("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);let{message:r}=Ie("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}validateRequestExpiry(t){if(t&&!iye(t,lV)){let{message:r}=Ie("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${lV.min} and ${lV.max}`);throw new Error(r)}}},pV=class extends Ou{constructor(t,r){super(t,r,SGe,vV),this.core=t,this.logger=r}},hV=class extends Ou{constructor(t,r){super(t,r,IGe,vV),this.core=t,this.logger=r}},mV=class extends Ou{constructor(t,r){super(t,r,PGe,vV,n=>n.id),this.core=t,this.logger=r}},gV=class extends Ou{constructor(t,r){super(t,r,BGe,iP,()=>oP),this.core=t,this.logger=r}},yV=class extends Ou{constructor(t,r){super(t,r,kGe,iP),this.core=t,this.logger=r}},wV=class extends Ou{constructor(t,r){super(t,r,UGe,iP,n=>n.id),this.core=t,this.logger=r}},FGe=Object.defineProperty,zGe=(e,t,r)=>t in e?FGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,uV=(e,t,r)=>zGe(e,typeof t!="symbol"?t+"":t,r),bV=class{constructor(t,r){this.core=t,this.logger=r,uV(this,"authKeys"),uV(this,"pairingTopics"),uV(this,"requests"),this.authKeys=new gV(this.core,this.logger),this.pairingTopics=new yV(this.core,this.logger),this.requests=new wV(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},VGe=Object.defineProperty,jGe=(e,t,r)=>t in e?VGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,jt=(e,t,r)=>jGe(e,typeof t!="symbol"?t+"":t,r),xV=class e extends $_{constructor(t){super(t),jt(this,"protocol",t2e),jt(this,"version",r2e),jt(this,"name",cV.name),jt(this,"metadata"),jt(this,"core"),jt(this,"logger"),jt(this,"events",new sP.EventEmitter),jt(this,"engine"),jt(this,"session"),jt(this,"proposal"),jt(this,"pendingRequest"),jt(this,"auth"),jt(this,"signConfig"),jt(this,"on",(n,o)=>this.events.on(n,o)),jt(this,"once",(n,o)=>this.events.once(n,o)),jt(this,"off",(n,o)=>this.events.off(n,o)),jt(this,"removeListener",(n,o)=>this.events.removeListener(n,o)),jt(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),jt(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"update",async n=>{try{return await this.engine.update(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"request",async n=>{try{return await this.engine.request(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"find",n=>{try{return this.engine.find(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),jt(this,"authenticate",async(n,o)=>{try{return await this.engine.authenticate(n,o)}catch(s){throw this.logger.error(s.message),s}}),jt(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}}),this.name=t?.name||cV.name,this.metadata=T1e(t?.metadata),this.signConfig=t?.signConfig;let r=ox({logger:t?.logger||cV.logger,name:this.name});this.logger=r,this.core=t?.core||new Yye(t),this.session=new hV(this.core,this.logger),this.proposal=new pV(this.core,this.logger),this.pendingRequest=new mV(this.core,this.logger),this.engine=new fV(this),this.auth=new bV(this.core,this.logger)}static async init(t){let r=new e(t);return await r.initialize(),r}get context(){return sr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}},o2e=xV});function kV(e){return e==null||typeof e!="object"&&typeof e!="function"}function I2e(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function T2e(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}function UV(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lYe(e,t){return dx(e,void 0,e,new Map,t)}function dx(e,t,r,n=new Map,o=void 0){let s=o?.(e,t,r,n);if(s!=null)return s;if(kV(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){let i=new Array(e.length);n.set(e,i);for(let a=0;a{let i=t?.(r,n,o,s);if(i!=null)return i;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case P2e:case _2e:case N2e:{let a=new e.constructor(e?.valueOf());return Oy(a,e),a}case R2e:{let a={};return Oy(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}})}function i2e(e){return dYe(e)}function a2e(e){return e!==null&&typeof e=="object"&&T2e(e)==="[object Arguments]"}function c2e(e){return typeof e=="object"&&e!==null}function fYe(){}function pYe(e){return UV(e)}function hYe(e){if(typeof e!="object"||e==null)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!=="[object Object]"){let r=e[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable?!1:e.toString()===`[object ${r}]`}let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function mYe(e){if(kV(e))return e;if(Array.isArray(e)||UV(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e),r=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new r(e);if(e instanceof RegExp){let n=new r(e);return n.lastIndex=e.lastIndex,n}if(e instanceof DataView)return new r(e.buffer.slice(0));if(e instanceof Error){let n=new r(e.message);return n.stack=e.stack,n.name=e.name,n.cause=e.cause,n}if(typeof File<"u"&&e instanceof File)return new r([e],e.name,{type:e.type,lastModified:e.lastModified});if(typeof e=="object"){let n=Object.create(t);return Object.assign(n,e)}return e}function gYe(e,...t){let r=t.slice(0,-1),n=t[t.length-1],o=e;for(let s=0;s`${t.split(":")[0]}:${t.split(":")[1]}`)}function PYe(e,t){let r=Object.keys(t.namespaces).filter(o=>o.includes(e));if(!r.length)return[];let n=[];return r.forEach(o=>{let s=t.namespaces[o].accounts;n.push(...s)}),n}function f2e(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>{var n,o;return((n=r?.chains)==null?void 0:n.length)&&((o=r?.chains)==null?void 0:o.length)>0}))}function lP(e={},t={}){let r=f2e(p2e(e)),n=f2e(p2e(t));return yYe(r,n)}function p2e(e){var t,r,n,o,s;let i={};if(!xc(e))return i;for(let[a,c]of Object.entries(e)){let u=H5(a)?[a]:c.chains,d=c.methods||[],f=c.events||[],p=c.rpcMap||{},h=Ny(a);i[h]=TYe(cP(cP({},i[h]),c),{chains:ml(u,(t=i[h])==null?void 0:t.chains),methods:ml(d,(r=i[h])==null?void 0:r.methods),events:ml(f,(n=i[h])==null?void 0:n.events)}),(xc(p)||xc(((o=i[h])==null?void 0:o.rpcMap)||{}))&&(i[h].rpcMap=cP(cP({},p),(s=i[h])==null?void 0:s.rpcMap))}return i}function h2e(e){return e.includes(":")?e.split(":")[2]:e}function m2e(e){let t={};for(let[r,n]of Object.entries(e)){let o=n.methods||[],s=n.events||[],i=n.accounts||[],a=H5(r)?[r]:n.chains?n.chains:D2e(n.accounts);t[r]={chains:a,methods:o,events:s,accounts:i}}return t}function EV(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function NYe(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}async function ZYe(e,t){let r=bl(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,o=await Promise.allSettled(n.map(f=>GYe(r.reference,f,t))),s=o.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);o.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));let i=!s.length||s.some(f=>!f),a=s.every(f=>f?.status==="0x1"),c=s.every(f=>f?.status==="0x0"),u=s.some(f=>f?.status==="0x0"),d;return i?d=100:a?d=200:c?d=500:u&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function GYe(e,t,r){return await r(parseInt(e)).request(dr("eth_getTransactionReceipt",[t]))}async function YYe({sendCalls:e,storage:t}){let r=await t.getItem(fx);await t.setItem(fx,KYe(WYe({},r),{[e.result.id]:{request:e.request,result:e.result,expiry:pn(vYe)}}))}async function JYe({resultId:e,storage:t}){let r=await t.getItem(fx);if(r){delete r[e],await t.setItem(fx,r);for(let n in r)ka(r[n].expiry)&&delete r[n];await t.setItem(fx,r)}}async function QYe({resultId:e,storage:t}){let r=await t.getItem(fx),n=r?.[e];if(n&&!ka(n.expiry))return n;await JYe({resultId:e,storage:t})}var S2e,qGe,_2e,P2e,N2e,R2e,WGe,KGe,ZGe,GGe,YGe,JGe,QGe,XGe,eYe,tYe,rYe,nYe,oYe,sYe,iYe,aYe,cYe,l2e,wYe,bYe,O2e,aP,B2e,k2e,xYe,fx,vYe,DV,EYe,AYe,CYe,u2e,SYe,IYe,d2e,cP,TYe,L2e,px,AV,RYe,g2e,OYe,BYe,y2e,w2e,b2e,kYe,UYe,CV,x2e,DYe,LYe,MYe,HYe,$Ye,SV,PV,FYe,zYe,VYe,v2e,jYe,qYe,E2e,WYe,KYe,XYe,eJe,tJe,A2e,rJe,nJe,NV,IV,TV,Ry,RV,oJe,sJe,ux,OV,iJe,aJe,cJe,C2e,lJe,uJe,BV,W5,uP,Ma,dP,M2e=b(()=>{l();s2e();eP();$c();cw();rI();S2e=Ht(ks(),1);qGe="[object RegExp]",_2e="[object String]",P2e="[object Number]",N2e="[object Boolean]",R2e="[object Arguments]",WGe="[object Symbol]",KGe="[object Date]",ZGe="[object Map]",GGe="[object Set]",YGe="[object Array]",JGe="[object ArrayBuffer]",QGe="[object Object]",XGe="[object DataView]",eYe="[object Uint8Array]",tYe="[object Uint8ClampedArray]",rYe="[object Uint16Array]",nYe="[object Uint32Array]",oYe="[object Int8Array]",sYe="[object Int16Array]",iYe="[object Int32Array]",aYe="[object Float32Array]",cYe="[object Float64Array]";l2e="error",wYe="wss://relay.walletconnect.org",bYe="wc",O2e="universal_provider",aP=`${bYe}@2:${O2e}:`,B2e="https://rpc.walletconnect.org/v1/",k2e="generic",xYe=`${B2e}bundler`,fx="call_status",vYe=86400,DV={DEFAULT_CHAIN_CHANGED:"default_chain_changed"},EYe=Object.defineProperty,AYe=Object.defineProperties,CYe=Object.getOwnPropertyDescriptors,u2e=Object.getOwnPropertySymbols,SYe=Object.prototype.hasOwnProperty,IYe=Object.prototype.propertyIsEnumerable,d2e=(e,t,r)=>t in e?EYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,cP=(e,t)=>{for(var r in t||(t={}))SYe.call(t,r)&&d2e(e,r,t[r]);if(u2e)for(var r of u2e(t))IYe.call(t,r)&&d2e(e,r,t[r]);return e},TYe=(e,t)=>AYe(e,CYe(t));L2e={},px=e=>L2e[e],AV=(e,t)=>{L2e[e]=t},RYe=Object.defineProperty,g2e=Object.getOwnPropertySymbols,OYe=Object.prototype.hasOwnProperty,BYe=Object.prototype.propertyIsEnumerable,y2e=(e,t,r)=>t in e?RYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,w2e=(e,t)=>{for(var r in t||(t={}))OYe.call(t,r)&&y2e(e,r,t[r]);if(g2e)for(var r of g2e(t))BYe.call(t,r)&&y2e(e,r,t[r]);return e},b2e="eip155",kYe=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],UYe=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,CV=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,x2e=e=>Object.keys(e).filter(t=>kYe.includes(t)).reduce((t,r)=>(t[r]=DYe(e[r]),t),{}),DYe=e=>typeof e=="string"&&NYe(e)?JSON.parse(e):e,LYe=(e,t,r)=>{let{sessionProperties:n={},scopedProperties:o={}}=e,s={};if(!xc(o)&&!xc(n))return;let i=x2e(n);for(let a of r){let c=UYe(a);if(!c)continue;s[CV(c)]=i;let u=o?.[`${b2e}:${c}`];if(u){let d=u?.[`${b2e}:${c}:${t}`];s[CV(c)]=w2e(w2e({},s[CV(c)]),x2e(d||u))}}for(let[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0},MYe=Object.defineProperty,HYe=(e,t,r)=>t in e?MYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$Ye=(e,t,r)=>HYe(e,typeof t!="symbol"?t+"":t,r),PV=class e{constructor(t){$Ye(this,"storage"),this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,r){return await this.storage.setItem(t,r)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return SV||(SV=new e(t)),SV}},FYe=Object.defineProperty,zYe=Object.defineProperties,VYe=Object.getOwnPropertyDescriptors,v2e=Object.getOwnPropertySymbols,jYe=Object.prototype.hasOwnProperty,qYe=Object.prototype.propertyIsEnumerable,E2e=(e,t,r)=>t in e?FYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,WYe=(e,t)=>{for(var r in t||(t={}))jYe.call(t,r)&&E2e(e,r,t[r]);if(v2e)for(var r of v2e(t))qYe.call(t,r)&&E2e(e,r,t[r]);return e},KYe=(e,t)=>zYe(e,VYe(t));XYe=Object.defineProperty,eJe=Object.defineProperties,tJe=Object.getOwnPropertyDescriptors,A2e=Object.getOwnPropertySymbols,rJe=Object.prototype.hasOwnProperty,nJe=Object.prototype.propertyIsEnumerable,NV=(e,t,r)=>t in e?XYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,IV=(e,t)=>{for(var r in t||(t={}))rJe.call(t,r)&&NV(e,r,t[r]);if(A2e)for(var r of A2e(t))nJe.call(t,r)&&NV(e,r,t[r]);return e},TV=(e,t)=>eJe(e,tJe(t)),Ry=(e,t,r)=>NV(e,typeof t!="symbol"?t+"":t,r),RV=class{constructor(t){Ry(this,"name","eip155"),Ry(this,"client"),Ry(this,"chainId"),Ry(this,"namespace"),Ry(this,"httpProviders"),Ry(this,"events"),Ry(this,"storage"),this.namespace=t.namespace,this.events=px("events"),this.client=px("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=PV.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r);let n=this.chainId;this.chainId=parseInt(t),this.events.emit(DV.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){let n=r||U2e(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,px("disableProviderPing")))}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProviders(){let t={};return this.namespace.chains.forEach(r=>{var n;let o=parseInt(_Ye(r));t[o]=this.createHttpProvider(o,(n=this.namespace.rpcMap)==null?void 0:n[r])}),t}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(t){let r=t||this.chainId;return this.httpProviders[r]||(this.httpProviders=TV(IV({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(t){var r,n;let o=t.request.params?(r=t.request.params[0])==null?void 0:r.chainId:"0x0";o=o.startsWith("0x")?o:`0x${o}`;let s=parseInt(o,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:o}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var r,n,o,s,i;let a=(n=(r=t.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(o=t.request)==null?void 0:o.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");let u=this.client.session.get(t.topic),d=((i=u?.sessionProperties)==null?void 0:i.capabilities)||{},f=c.length>0?c.join(","):`0x${this.chainId.toString(16)}`,p=`${a}${f}`,h=d?.[p];if(h)return h;let y;try{y=LYe(u,a,c)}catch(x){console.warn("Failed to extract capabilities from session",x)}if(y)return y;let w=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:TV(IV({},u.sessionProperties||{}),{capabilities:TV(IV({},d||{}),{[p]:w})})})}catch(x){console.warn("Failed to update session with capabilities",x)}return w}async getCallStatus(t){var r,n,o;let s=this.client.session.get(t.topic),i=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(i){let u=this.getBundlerUrl(t.chainId,i);try{return await this.getUserOperationReceipt(u,t)}catch(d){console.warn("Failed to fetch call status from bundler",d,u)}}let a=(n=s.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}let c=await QYe({resultId:(o=t.request.params)==null?void 0:o[0],storage:this.storage});if(c)try{return await ZYe(c,this.getHttpProvider.bind(this))}catch(u){console.warn("Failed to fetch call status from stored send calls",u,c)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,r){var n;let o=new URL(t),s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dr("eth_getUserOperationReceipt",[(n=r.request.params)==null?void 0:n[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(t,r){return`${xYe}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${r}`}async sendCalls(t){var r,n,o;let s=await this.client.request(t),i=(r=t.request.params)==null?void 0:r[0],a=s?.id,c=s?.capabilities||{},u=(n=c?.caip345)==null?void 0:n.caip2,d=(o=c?.caip345)==null?void 0:o.transactionHashes;return!a||!u||!(d!=null&&d.length)||await YYe({sendCalls:{request:i,result:s},storage:this.storage}),s}},oJe=Object.defineProperty,sJe=(e,t,r)=>t in e?oJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ux=(e,t,r)=>sJe(e,typeof t!="symbol"?t+"":t,r),OV=class{constructor(t){ux(this,"name",k2e),ux(this,"client"),ux(this,"httpProviders"),ux(this,"events"),ux(this,"namespace"),ux(this,"chainId"),this.namespace=t.namespace,this.events=px("events"),this.client=px("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r);let n=this.chainId;this.chainId=t,this.events.emit(DV.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return bl(t).namespace}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var t,r;let n={};return(r=(t=this.namespace)==null?void 0:t.accounts)==null||r.forEach(o=>{var s,i;let a=bl(o),c=(i=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:i[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(o,c)}),n}getHttpProvider(t){let r=bl(t).reference,n=this.httpProviders[r];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return n}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProvider(t,r){let n=r||U2e(t,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,px("disableProviderPing")))}},iJe=Object.defineProperty,aJe=Object.defineProperties,cJe=Object.getOwnPropertyDescriptors,C2e=Object.getOwnPropertySymbols,lJe=Object.prototype.hasOwnProperty,uJe=Object.prototype.propertyIsEnumerable,BV=(e,t,r)=>t in e?iJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,W5=(e,t)=>{for(var r in t||(t={}))lJe.call(t,r)&&BV(e,r,t[r]);if(C2e)for(var r of C2e(t))uJe.call(t,r)&&BV(e,r,t[r]);return e},uP=(e,t)=>aJe(e,cJe(t)),Ma=(e,t,r)=>BV(e,typeof t!="symbol"?t+"":t,r),dP=class e{constructor(t){Ma(this,"client"),Ma(this,"namespaces"),Ma(this,"optionalNamespaces"),Ma(this,"sessionProperties"),Ma(this,"scopedProperties"),Ma(this,"events",new S2e.default),Ma(this,"rpcProviders",{}),Ma(this,"session"),Ma(this,"providerOpts"),Ma(this,"logger"),Ma(this,"uri"),Ma(this,"disableProviderPing",!1),Ma(this,"connectParams");var r,n;this.providerOpts=t,this.logger=ox({logger:(r=t.logger)!=null?r:l2e,name:(n=this.providerOpts.name)!=null?n:O2e}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){let r=new e(t);return await r.initialize(),r}async request(t,r,n){let[o,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(o).request({request:W5({},t),chainId:`${o}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(t,r,n,o){let s=new Date().getTime();this.request(t,n,o).then(i=>r(null,bo(s,i))).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:Rr("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();let{uri:n,response:o}=await this.client.authenticate(t,r);n&&(this.uri=n,this.events.emit("display_uri",n));let s=await o();if(this.session=s.session,this.session){let i=m2e(this.session.namespaces);this.namespaces=lP(this.namespaces,i),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){var r,n;let{uri:o,approval:s}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(n=this.connectParams)==null?void 0:n.walletPay});o&&(this.uri=o,this.events.emit("display_uri",o));let i=await s();this.session=i;let a=m2e(i.namespaces);return this.namespaces=lP(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;let[n,o]=this.validateChain(t);this.getProvider(n).setDefaultChain(o,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");let r=this.client.pairing.getAll();if(!El(r))return;for(let n of r)t.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var t,r;if(this.client=this.providerOpts.client||await o2e.init({core:this.providerOpts.core,logger:this.providerOpts.logger||l2e,relayUrl:this.providerOpts.relayUrl||wYe,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error(n,"Failed to get session"),new Error(`The provided session: ${(r=(t=this.providerOpts)==null?void 0:t.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{let n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");let t=[...new Set(Object.keys(this.session.namespaces).map(r=>Ny(r)))];AV("client",this.client),AV("events",this.events),AV("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;let n=PYe(r,this.session);if(n?.length===0)return;let o=D2e(n),s=lP(this.namespaces,this.optionalNamespaces),i=uP(W5({},s[r]),{accounts:n,chains:o});r==="eip155"?this.rpcProviders[r]=new RV({namespace:i}):this.rpcProviders[r]=new OV({namespace:i})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{var r;let{topic:n}=t;n===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{var r;let{params:n,topic:o}=t;if(o!==((r=this.session)==null?void 0:r.topic))return;let{event:s}=n;if(s.name==="accountsChanged"){let i=s.data;i&&El(i)&&this.events.emit("accountsChanged",i.map(h2e))}else if(s.name==="chainChanged"){let i=n.chainId,a=n.event.data,c=Ny(i),u=EV(i)!==EV(a)?`${c}:${EV(a)}`:i;this.onChainChanged({currentCaipChainId:u})}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{var n,o;if(t!==((n=this.session)==null?void 0:n.topic))return;let{namespaces:s}=r,i=(o=this.client)==null?void 0:o.session.get(t);this.session=uP(W5({},i),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{var r;t.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",uP(W5({},Rr("USER_DISCONNECTED")),{data:t.topic})))}),this.on(DV.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(uP(W5({},t),{internal:!0}))})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[k2e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var r;this.getProvider(t).updateNamespace((r=this.session)==null?void 0:r.namespaces[t])})}setNamespaces(t){let{namespaces:r={},optionalNamespaces:n={},sessionProperties:o,scopedProperties:s}=t;this.optionalNamespaces=lP(r,n),this.sessionProperties=o,this.scopedProperties=s}validateChain(t){let[r,n]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(i=>Ny(i)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];let o=Ny(Object.keys(this.namespaces)[0]),s=this.rpcProviders[o].getDefaultChain();return[o,s]}async requestAccounts(){let[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:r,internal:n=!1}){if(!this.namespaces)return;let[o,s]=this.validateChain(t);s&&(this.updateNamespaceChain(o,s),n?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:o,currentCaipChainId:t,previousCaipChainId:r})):this.getProvider(o).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:r,previousCaipChainId:n}){var o,s;try{if(n===r)return;let i=(s=(o=this.session)==null?void 0:o.namespaces[t])==null?void 0:s.accounts;if(!i)return;let a=i.filter(c=>c.includes(`${r}:`)).map(h2e);if(!El(a))return;this.events.emit("accountsChanged",a)}catch(i){this.logger.warn(i,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,r){if(!this.namespaces)return;let n=this.namespaces[t]?t:`${t}:${r}`,o={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=o}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,r){var n;let o=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${aP}/${t}${o}`,r)}async getFromStore(t){var r;let n=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${aP}/${t}${n}`)}async deleteFromStore(t){var r;let n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${aP}/${t}${n}`)}async cleanupStorage(){var t;try{if(((t=this.client)==null?void 0:t.session.length)>0)return;let r=await this.client.core.storage.getKeys();for(let n of r)n.startsWith(aP)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}});var fP,H2e=b(()=>{l();fP={interpolate(e,t,r){if(e.length!==2||t.length!==2)throw new Error("inputRange and outputRange must be an array of length 2");let n=e[0]||0,o=e[1]||0,s=t[0]||0,i=t[1]||0;return ro?i:(i-s)/(o-n)*(r-n)+s}}});var pP,hP,LV,$2e,K5,Zi,Er,F2e,MV,HV=b(()=>{l();pP=globalThis,hP=pP.ShadowRoot&&(pP.ShadyCSS===void 0||pP.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,LV=Symbol(),$2e=new WeakMap,K5=class{constructor(t,r,n){if(this._$cssResult$=!0,n!==LV)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=r}get styleSheet(){let t=this.o,r=this.t;if(hP&&t===void 0){let n=r!==void 0&&r.length===1;n&&(t=$2e.get(r)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&$2e.set(r,t))}return t}toString(){return this.cssText}},Zi=e=>new K5(typeof e=="string"?e:e+"",void 0,LV),Er=(e,...t)=>{let r=e.length===1?e[0]:t.reduce((n,o,s)=>n+(i=>{if(i._$cssResult$===!0)return i.cssText;if(typeof i=="number")return i;throw Error("Value passed to 'css' function must be a 'css' function result: "+i+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[s+1],e[0]);return new K5(r,e,LV)},F2e=(e,t)=>{if(hP)e.adoptedStyleSheets=t.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(let r of t){let n=document.createElement("style"),o=pP.litNonce;o!==void 0&&n.setAttribute("nonce",o),n.textContent=r.cssText,e.appendChild(n)}},MV=hP?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let r="";for(let n of t.cssRules)r+=n.cssText;return Zi(r)})(e):e});var dJe,fJe,pJe,hJe,mJe,gJe,mP,z2e,yJe,wJe,Z5,G5,gP,V2e,Op,Y5=b(()=>{l();HV();HV();({is:dJe,defineProperty:fJe,getOwnPropertyDescriptor:pJe,getOwnPropertyNames:hJe,getOwnPropertySymbols:mJe,getPrototypeOf:gJe}=Object),mP=globalThis,z2e=mP.trustedTypes,yJe=z2e?z2e.emptyScript:"",wJe=mP.reactiveElementPolyfillSupport,Z5=(e,t)=>e,G5={toAttribute(e,t){switch(t){case Boolean:e=e?yJe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let r=e;switch(t){case Boolean:r=e!==null;break;case Number:r=e===null?null:Number(e);break;case Object:case Array:try{r=JSON.parse(e)}catch{r=null}}return r}},gP=(e,t)=>!dJe(e,t),V2e={attribute:!0,type:String,converter:G5,reflect:!1,useDefault:!1,hasChanged:gP};Symbol.metadata??=Symbol("metadata"),mP.litPropertyMetadata??=new WeakMap;Op=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,r=V2e){if(r.state&&(r.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((r=Object.create(r)).wrapped=!0),this.elementProperties.set(t,r),!r.noAccessor){let n=Symbol(),o=this.getPropertyDescriptor(t,n,r);o!==void 0&&fJe(this.prototype,t,o)}}static getPropertyDescriptor(t,r,n){let{get:o,set:s}=pJe(this.prototype,t)??{get(){return this[r]},set(i){this[r]=i}};return{get:o,set(i){let a=o?.call(this);s?.call(this,i),this.requestUpdate(t,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??V2e}static _$Ei(){if(this.hasOwnProperty(Z5("elementProperties")))return;let t=gJe(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Z5("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Z5("properties"))){let r=this.properties,n=[...hJe(r),...mJe(r)];for(let o of n)this.createProperty(o,r[o])}let t=this[Symbol.metadata];if(t!==null){let r=litPropertyMetadata.get(t);if(r!==void 0)for(let[n,o]of r)this.elementProperties.set(n,o)}this._$Eh=new Map;for(let[r,n]of this.elementProperties){let o=this._$Eu(r,n);o!==void 0&&this._$Eh.set(o,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let r=[];if(Array.isArray(t)){let n=new Set(t.flat(1/0).reverse());for(let o of n)r.unshift(MV(o))}else t!==void 0&&r.push(MV(t));return r}static _$Eu(t,r){let n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,r=this.constructor.elementProperties;for(let n of r.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return F2e(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,r,n){this._$AK(t,n)}_$ET(t,r){let n=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,n);if(o!==void 0&&n.reflect===!0){let s=(n.converter?.toAttribute!==void 0?n.converter:G5).toAttribute(r,n.type);this._$Em=t,s==null?this.removeAttribute(o):this.setAttribute(o,s),this._$Em=null}}_$AK(t,r){let n=this.constructor,o=n._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let s=n.getPropertyOptions(o),i=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:G5;this._$Em=o;let a=i.fromAttribute(r,s.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,r,n,o=!1,s){if(t!==void 0){let i=this.constructor;if(o===!1&&(s=this[t]),n??=i.getPropertyOptions(t),!((n.hasChanged??gP)(s,r)||n.useDefault&&n.reflect&&s===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,n))))return;this.C(t,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,r,{useDefault:n,reflect:o,wrapped:s},i){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,i??r??this[t]),s!==!0||i!==void 0)||(this._$AL.has(t)||(this.hasUpdated||n||(r=void 0),this._$AL.set(t,r)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[o,s]of this._$Ep)this[o]=s;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[o,s]of n){let{wrapped:i}=s,a=this[o];i!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,s,a)}}let t=!1,r=this._$AL;try{t=this.shouldUpdate(r),t?(this.willUpdate(r),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(r)):this._$EM()}catch(n){throw t=!1,this._$EM(),n}t&&this._$AE(r)}willUpdate(t){}_$AE(t){this._$EO?.forEach(r=>r.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(r=>this._$ET(r,this[r])),this._$EM()}updated(t){}firstUpdated(t){}};Op.elementStyles=[],Op.shadowRootOptions={mode:"open"},Op[Z5("elementProperties")]=new Map,Op[Z5("finalized")]=new Map,wJe?.({ReactiveElement:Op}),(mP.reactiveElementVersions??=[]).push("2.1.2")});function ewe(e,t){if(!jV(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return q2e!==void 0?q2e.createHTML(t):t}function Dy(e,t,r=e,n){if(t===kp)return t;let o=n!==void 0?r._$Co?.[n]:r._$Cl,s=X5(t)?void 0:t._$litDirective$;return o?.constructor!==s&&(o?._$AO?.(!1),s===void 0?o=void 0:(o=new s(e),o._$AT(e,r,n)),n!==void 0?(r._$Co??=[])[n]=o:r._$Cl=o),o!==void 0&&(t=Dy(e,o._$AS(e,t.values),o,n)),t}var FV,j2e,yP,q2e,zV,Bp,VV,bJe,Uy,Q5,X5,jV,J2e,$V,J5,W2e,K2e,By,Z2e,G2e,Q2e,qV,V,He,X2e,kp,hn,Y2e,ky,twe,ev,wP,hx,Ly,bP,xP,vP,EP,rwe,xJe,nwe,Up=b(()=>{l();FV=globalThis,j2e=e=>e,yP=FV.trustedTypes,q2e=yP?yP.createPolicy("lit-html",{createHTML:e=>e}):void 0,zV="$lit$",Bp=`lit$${Math.random().toFixed(9).slice(2)}$`,VV="?"+Bp,bJe=`<${VV}>`,Uy=document,Q5=()=>Uy.createComment(""),X5=e=>e===null||typeof e!="object"&&typeof e!="function",jV=Array.isArray,J2e=e=>jV(e)||typeof e?.[Symbol.iterator]=="function",$V=`[ +`)};cje=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;fje=(e,t)=>{function r(n,...o){if(ji(n),!cje)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");e.varSizeNonce?ji(u):ji(u,e.nonceLength)}let s=e.tagLength;s&&o[1]!==void 0&&ji(o[1]);let i=t(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");ji(d)}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ji(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(ji(u),s&&u.lengtht.charCodeAt(0))),mje=nge("expand 16-byte k"),gje=nge("expand 32-byte k"),yje=Lm(mje),wje=Lm(gje);_7=64,bje=16,oge=2**32-1,r1e=new Uint32Array;qo=(e,t)=>e[t++]&255|(e[t++]&255)<<8,zF=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=HF(t),ji(t,32);let r=qo(t,0),n=qo(t,2),o=qo(t,4),s=qo(t,6),i=qo(t,8),a=qo(t,10),c=qo(t,12),u=qo(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=qo(t,16+2*d)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],d=i[3],f=i[4],p=i[5],h=i[6],y=i[7],w=i[8],x=i[9],v=qo(t,r+0),T=qo(t,r+2),E=qo(t,r+4),S=qo(t,r+6),_=qo(t,r+8),O=qo(t,r+10),D=qo(t,r+12),M=qo(t,r+14),N=s[0]+(v&8191),L=s[1]+((v>>>13|T<<3)&8191),P=s[2]+((T>>>10|E<<6)&8191),R=s[3]+((E>>>7|S<<9)&8191),I=s[4]+((S>>>4|_<<12)&8191),B=s[5]+(_>>>1&8191),C=s[6]+((_>>>14|O<<2)&8191),A=s[7]+((O>>>11|D<<5)&8191),U=s[8]+((D>>>8|M<<8)&8191),H=s[9]+(M>>>5|o),k=0,F=k+N*a+L*(5*x)+P*(5*w)+R*(5*y)+I*(5*h);k=F>>>13,F&=8191,F+=B*(5*p)+C*(5*f)+A*(5*d)+U*(5*u)+H*(5*c),k+=F>>>13,F&=8191;let j=k+N*c+L*a+P*(5*x)+R*(5*w)+I*(5*y);k=j>>>13,j&=8191,j+=B*(5*h)+C*(5*p)+A*(5*f)+U*(5*d)+H*(5*u),k+=j>>>13,j&=8191;let W=k+N*u+L*c+P*a+R*(5*x)+I*(5*w);k=W>>>13,W&=8191,W+=B*(5*y)+C*(5*h)+A*(5*p)+U*(5*f)+H*(5*d),k+=W>>>13,W&=8191;let ae=k+N*d+L*u+P*c+R*a+I*(5*x);k=ae>>>13,ae&=8191,ae+=B*(5*w)+C*(5*y)+A*(5*h)+U*(5*p)+H*(5*f),k+=ae>>>13,ae&=8191;let te=k+N*f+L*d+P*u+R*c+I*a;k=te>>>13,te&=8191,te+=B*(5*x)+C*(5*w)+A*(5*y)+U*(5*h)+H*(5*p),k+=te>>>13,te&=8191;let X=k+N*p+L*f+P*d+R*u+I*c;k=X>>>13,X&=8191,X+=B*a+C*(5*x)+A*(5*w)+U*(5*y)+H*(5*h),k+=X>>>13,X&=8191;let pe=k+N*h+L*p+P*f+R*d+I*u;k=pe>>>13,pe&=8191,pe+=B*c+C*a+A*(5*x)+U*(5*w)+H*(5*y),k+=pe>>>13,pe&=8191;let me=k+N*y+L*h+P*p+R*f+I*d;k=me>>>13,me&=8191,me+=B*u+C*c+A*a+U*(5*x)+H*(5*w),k+=me>>>13,me&=8191;let Ne=k+N*w+L*y+P*h+R*p+I*f;k=Ne>>>13,Ne&=8191,Ne+=B*d+C*u+A*c+U*a+H*(5*x),k+=Ne>>>13,Ne&=8191;let ye=k+N*x+L*w+P*y+R*h+I*p;k=ye>>>13,ye&=8191,ye+=B*f+C*d+A*u+U*c+H*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+F|0,F=k&8191,k=k>>>13,j+=k,s[0]=F,s[1]=j,s[2]=W,s[3]=ae,s[4]=te,s[5]=X,s[6]=pe,s[7]=me,s[8]=Ne,s[9]=ye}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;Q6(n)}update(t){Xme(this),t=HF(t),ji(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};Aje=Eje(e=>new zF(e));Sje=vje(Cje,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ije=new Uint8Array(16),n1e=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ije.subarray(r))},Tje=new Uint8Array(32);_je=e=>(t,r,n)=>({encrypt(o,s){let i=o.length;s=e1e(i+16,s,!1),s.set(o);let a=s.subarray(0,-16);e(t,r,a,a,1);let c=o1e(e,t,r,a,n);return s.set(c,i),Q6(c),s},decrypt(o,s){s=e1e(o.length-16,s,!1);let i=o.subarray(0,-16),a=o.subarray(-16),c=o1e(e,t,r,i,n);if(!dje(a,c))throw new Error("invalid tag");return s.set(o.subarray(0,-16)),e(t,r,s,s,1),Q6(c),s}}),sge=fje({blockSize:64,nonceLength:12,tagLength:16},_je(Sje)),U7=class extends J6{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,j7(t);let n=gl(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew U7(e,t).update(r).digest();Z7.create=(e,t)=>new U7(e,t);EF=Uint8Array.from([0]),s1e=Uint8Array.of();Rje=(e,t,r,n,o)=>Nje(e,Pje(e,t,r),n,o),G7=q7,dz=BigInt(0),VF=BigInt(1);AF=e=>typeof e=="bigint"&&dz<=e;U5=e=>(VF<X6;)r&Sy&&(n=n.add(o)),o=o.double(),r>>=Sy;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=SF(r,this.bits),s=[],i=t,a=i;for(let c=0;c{let e=nqe.ORDER;return Gje({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=tqe(t);return Ba(pl(r,Jje,e)*n,e)},adjustScalarBytes:rqe})})(),p1e=(e,t)=>(e+(e>=0?t:-t)/Ege)/t;ZF=class extends Error{constructor(t=""){super(t)}},Cp={Err:ZF,_tlv:{encode:(e,t)=>{let{Err:r}=Cp;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=P7(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?P7(o.length/2|128):"";return P7(e)+s+o+t},decode(e,t){let{Err:r}=Cp,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Cp;if(et in e?vqe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,PF=(e,t)=>{for(var r in t||(t={}))Cqe.call(t,r)&&g1e(e,r,t[r]);if(m1e)for(var r of m1e(t))Sqe.call(t,r)&&g1e(e,r,t[r]);return e},Iqe=(e,t)=>Eqe(e,Aqe(t));Nqe=Object.defineProperty,Rqe=Object.defineProperties,Oqe=Object.getOwnPropertyDescriptors,y1e=Object.getOwnPropertySymbols,Bqe=Object.prototype.hasOwnProperty,kqe=Object.prototype.propertyIsEnumerable,w1e=(e,t,r)=>t in e?Nqe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Uqe=(e,t)=>{for(var r in t||(t={}))Bqe.call(t,r)&&w1e(e,r,t[r]);if(y1e)for(var r of y1e(t))kqe.call(t,r)&&w1e(e,r,t[r]);return e},Dqe=(e,t)=>Rqe(e,Oqe(t));$qe={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Fqe={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};NF={},$m=class{static get(t){return NF[t]}static set(t,r){NF[t]=r}static delete(t){delete NF[t]}}});function zWe(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,S=new Uint8Array(E);v!==T;){for(var _=y[v],O=0,D=E-1;(_!==0||O>>0,S[D]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=O,v++}for(var M=E-x;M!==E&&S[M]===0;)M++;for(var N=c.repeat(w);M>>0,E=new Uint8Array(T);y[w];){var S=r[y.charCodeAt(w)];if(S===255)return;for(var _=0,O=T-1;(S!==0||_>>0,E[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");v=_,w++}if(y[w]!==" "){for(var D=T-v;D!==T&&E[D]===0;)D++;for(var M=new Uint8Array(x+(T-D)),N=x;D!==T;)M[N++]=E[D++];return M}}}function h(y){var w=p(y);if(w)return w;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:h}}function PKe(e){return e.reduce((t,r)=>(t+=TKe[r],t),"")}function NKe(e){let t=[];for(let r of e){let n=_Ke[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}function zye(e,t,r){t=t||[],r=r||0;for(var n=r;e>=DKe;)t[r++]=e&255|fye,e/=128;for(;e&UKe;)t[r++]=e&255|fye,e>>>=7;return t[r]=e|0,zye.bytes=r-n+1,t}function Dz(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Dz.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&pye)<=MKe);return Dz.bytes=s-n,r}function Zye(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function nZe(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zye(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Gye(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}function sZe(e,t="utf8"){let r=oZe[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zye(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function OZe(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Cye(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function Sye(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}function nGe(){}function Tye(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function oGe(e,t,r){return V5(e,t,void 0,void 0,void 0,void 0,r)}function V5(e,t,r,n,o,s,i){let a=i(e,t,r,n,o,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return j5(e,t,s,i)}return j5(e,t,s,i)}function j5(e,t,r,n){if(Object.is(e,t))return!0;let o=Sye(e),s=Sye(t);if(o===Iye&&(o=Nz),s===Iye&&(s=Nz),o!==s)return!1;switch(o){case kZe:return e.toString()===t.toString();case UZe:{let c=e.valueOf(),u=t.valueOf();return OZe(c,u)}case DZe:case MZe:case LZe:return Object.is(e.valueOf(),t.valueOf());case BZe:return e.source===t.source&&e.flags===t.flags;case zZe:return e===t}r=r??new Map;let i=r.get(e),a=r.get(t);if(i!=null&&a!=null)return i===t;r.set(e,t),r.set(t,e);try{switch(o){case HZe:{if(e.size!==t.size)return!1;for(let[c,u]of e.entries())if(!t.has(c)||!V5(u,t.get(c),c,e,t,r,n))return!1;return!0}case $Ze:{if(e.size!==t.size)return!1;let c=Array.from(e.values()),u=Array.from(t.values());for(let d=0;dV5(f,h,void 0,e,t,r,n));if(p===-1)return!1;u.splice(p,1)}return!0}case FZe:case WZe:case KZe:case ZZe:case GZe:case YZe:case JZe:case QZe:case XZe:case eGe:case tGe:case rGe:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c{l();Rp=Ht(ks(),1);vk();Rk();gh();DH();Xe=Ht(jd(),1);R1();B1();B1();eP();I8();cw();$c();Hk();kye=Ht(C2(),1),Uye="wc",Dye=2,rP="core",Ru=`${Uye}@2:${rP}:`,cWe={name:rP,logger:"error"},lWe={database:":memory:"},uWe="crypto",uye="client_ed25519_seed",dWe=Xe.ONE_DAY,fWe="keychain",pWe="0.3",hWe="messages",mWe="0.3",gWe=Xe.SIX_HOURS,yWe="publisher",aV="irn",wWe="error",Lye="wss://relay.walletconnect.org",bWe="relayer",Mn={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},xWe="_subscription",vc={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},vWe=.1,Rz="2.23.2",Vr={link_mode:"link_mode",relay:"relay"},tP={inbound:"inbound",outbound:"outbound"},EWe="0.3",AWe="WALLETCONNECT_CLIENT_ID",dye="WALLETCONNECT_LINK_MODE_APPS",Da={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},CWe="subscription",SWe="0.3",Mdr=Xe.FIVE_SECONDS*1e3,IWe="pairing",TWe="0.3",$5={wc_pairingDelete:{req:{ttl:Xe.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Xe.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Xe.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Xe.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Xe.ONE_DAY,prompt:!1,tag:0},res:{ttl:Xe.ONE_DAY,prompt:!1,tag:0}}},zm={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Al={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},_We="history",PWe="0.3",NWe="expirer",La={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},RWe="0.3",OWe="verify-api",BWe="https://verify.walletconnect.com",Mye="https://verify.walletconnect.org",ax=Mye,kWe=`${ax}/v3`,UWe=[BWe,Mye],DWe="echo",LWe="https://echo.walletconnect.com",Cl={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Nu={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Ac={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Vm={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},jm={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},cx={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},MWe=.1,HWe="event-client",$We=86400,FWe="https://pulse.walletconnect.org/batch";VWe=zWe,jWe=VWe,Hye=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},qWe=e=>new TextEncoder().encode(e),WWe=e=>new TextDecoder().decode(e),Oz=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Bz=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $ye(this,t)}},kz=class{constructor(t){this.decoders=t}or(t){return $ye(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},$ye=(e,t)=>new kz({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),Uz=class{constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Oz(t,r,n),this.decoder=new Bz(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},nP=({name:e,prefix:t,encode:r,decode:n})=>new Uz(e,t,r,n),q5=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:o}=jWe(r,t);return nP({prefix:e,name:t,encode:n,decode:s=>Hye(o(s))})},KWe=(e,t,r,n)=>{let o={};for(let d=0;d=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},ZWe=(e,t,r)=>{let n=t[t.length-1]==="=",o=(1<r;)i-=r,s+=t[o&a>>i];if(i&&(s+=t[o&a<nP({prefix:t,name:e,encode(o){return ZWe(o,n,r)},decode(o){return KWe(o,n,r,e)}}),GWe=nP({prefix:"\0",name:"identity",encode:e=>WWe(e),decode:e=>qWe(e)}),YWe=Object.freeze({__proto__:null,identity:GWe}),JWe=Ko({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),QWe=Object.freeze({__proto__:null,base2:JWe}),XWe=Ko({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),eKe=Object.freeze({__proto__:null,base8:XWe}),tKe=q5({prefix:"9",name:"base10",alphabet:"0123456789"}),rKe=Object.freeze({__proto__:null,base10:tKe}),nKe=Ko({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oKe=Ko({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),sKe=Object.freeze({__proto__:null,base16:nKe,base16upper:oKe}),iKe=Ko({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aKe=Ko({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cKe=Ko({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lKe=Ko({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uKe=Ko({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dKe=Ko({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fKe=Ko({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pKe=Ko({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hKe=Ko({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),mKe=Object.freeze({__proto__:null,base32:iKe,base32upper:aKe,base32pad:cKe,base32padupper:lKe,base32hex:uKe,base32hexupper:dKe,base32hexpad:fKe,base32hexpadupper:pKe,base32z:hKe}),gKe=q5({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yKe=q5({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),wKe=Object.freeze({__proto__:null,base36:gKe,base36upper:yKe}),bKe=q5({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xKe=q5({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),vKe=Object.freeze({__proto__:null,base58btc:bKe,base58flickr:xKe}),EKe=Ko({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),AKe=Ko({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CKe=Ko({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),SKe=Ko({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),IKe=Object.freeze({__proto__:null,base64:EKe,base64pad:AKe,base64url:CKe,base64urlpad:SKe}),Fye=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),TKe=Fye.reduce((e,t,r)=>(e[r]=t,e),[]),_Ke=Fye.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);RKe=nP({prefix:"\u{1F680}",name:"base256emoji",encode:PKe,decode:NKe}),OKe=Object.freeze({__proto__:null,base256emoji:RKe}),BKe=zye,fye=128,kKe=127,UKe=~kKe,DKe=Math.pow(2,31);LKe=Dz,MKe=128,pye=127;HKe=Math.pow(2,7),$Ke=Math.pow(2,14),FKe=Math.pow(2,21),zKe=Math.pow(2,28),VKe=Math.pow(2,35),jKe=Math.pow(2,42),qKe=Math.pow(2,49),WKe=Math.pow(2,56),KKe=Math.pow(2,63),ZKe=function(e){return e(Vye.encode(e,t,r),t),mye=e=>Vye.encodingLength(e),Lz=(e,t)=>{let r=t.byteLength,n=mye(e),o=n+mye(r),s=new Uint8Array(o+r);return hye(e,s,0),hye(r,s,n),s.set(t,o),new Mz(e,r,t,s)},Mz=class{constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}},jye=({name:e,code:t,encode:r})=>new Hz(e,t,r),Hz=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?Lz(this.code,r):r.then(n=>Lz(this.code,n))}else throw Error("Unknown type, must be binary type")}},qye=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),YKe=jye({name:"sha2-256",code:18,encode:qye("SHA-256")}),JKe=jye({name:"sha2-512",code:19,encode:qye("SHA-512")}),QKe=Object.freeze({__proto__:null,sha256:YKe,sha512:JKe}),Wye=0,XKe="identity",Kye=Hye,eZe=e=>Lz(Wye,Kye(e)),tZe={code:Wye,name:XKe,encode:Kye,digest:eZe},rZe=Object.freeze({__proto__:null,identity:tZe});new TextEncoder,new TextDecoder;gye={...YWe,...QWe,...eKe,...rKe,...sKe,...mKe,...wKe,...vKe,...IKe,...OKe};({...QKe,...rZe});yye=Gye("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),_z=Gye("ascii","a",e=>{let t="a";for(let r=0;r{e=e.substring(1);let t=nZe(e.length);for(let r=0;rt in e?iZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pu=(e,t,r)=>aZe(e,typeof t!="symbol"?t+"":t,r),$z=class{constructor(t,r){this.core=t,this.logger=r,Pu(this,"keychain",new Map),Pu(this,"name",fWe),Pu(this,"version",pWe),Pu(this,"initialized",!1),Pu(this,"storagePrefix",Ru),Pu(this,"init",async()=>{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Pu(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Pu(this,"set",async(n,o)=>{this.isInitialized(),this.keychain.set(n,o),await this.persist()}),Pu(this,"get",n=>{this.isInitialized();let o=this.keychain.get(n);if(typeof o>"u"){let{message:s}=Ie("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return o}),Pu(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=t,this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,$7(t))}async getKeyChain(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?F7(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},cZe=Object.defineProperty,lZe=(e,t,r)=>t in e?cZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,No=(e,t,r)=>lZe(e,typeof t!="symbol"?t+"":t,r),Fz=class{constructor(t,r,n){this.core=t,this.logger=r,No(this,"name",uWe),No(this,"keychain"),No(this,"randomSessionIdentifier",Q7()),No(this,"initialized",!1),No(this,"clientId"),No(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),No(this,"hasKeys",o=>(this.isInitialized(),this.keychain.has(o))),No(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;let o=await this.getClientSeed(),s=J2(o),i=U8(s.publicKey);return this.clientId=i,i}),No(this,"generateKeyPair",()=>{this.isInitialized();let o=Nge();return this.setPrivateKey(o.publicKey,o.privateKey)}),No(this,"signJWT",async o=>{this.isInitialized();let s=await this.getClientSeed(),i=J2(s),a=this.randomSessionIdentifier;return await BC(a,o,dWe,i)}),No(this,"generateSharedKey",(o,s,i)=>{this.isInitialized();let a=this.getPrivateKey(o),c=Rge(a,s);return this.setSymKey(c,i)}),No(this,"setSymKey",async(o,s)=>{this.isInitialized();let i=s||tx(o);return await this.keychain.set(i,o),i}),No(this,"deleteKeyPair",async o=>{this.isInitialized(),await this.keychain.del(o)}),No(this,"deleteSymKey",async o=>{this.isInitialized(),await this.keychain.del(o)}),No(this,"encode",async(o,s,i)=>{this.isInitialized();let a=gz(i),c=wi(s);if(wz(a))return Lge(c,i?.encoding);if(yz(a)){let p=a.senderPublicKey,h=a.receiverPublicKey;o=await this.generateSharedKey(p,h)}let u=this.getSymKey(o),{type:d,senderPublicKey:f}=a;return Uge({type:d,symKey:u,message:c,senderPublicKey:f,encoding:i?.encoding})}),No(this,"decode",async(o,s,i)=>{this.isInitialized();let a=$ge(s,i);if(wz(a)){let c=Mge(s,i?.encoding);return Fs(c)}if(yz(a)){let c=a.receiverPublicKey,u=a.senderPublicKey;o=await this.generateSharedKey(c,u)}try{let c=this.getSymKey(o),u=Dge({symKey:c,encoded:s,encoding:i?.encoding});return Fs(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),No(this,"getPayloadType",(o,s=Ts)=>{let i=rx({encoded:o,encoding:s});return Hm(i.type)}),No(this,"getPayloadSenderPublicKey",(o,s=Ts)=>{let i=rx({encoded:o,encoding:s});return i.senderPublicKey?Ut(i.senderPublicKey,Is):void 0}),this.core=t,this.logger=Cr(r,this.name),this.keychain=n||new $z(this.core,this.logger)}get context(){return sr(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(uye)}catch{t=Q7(),await this.keychain.set(uye,t)}return sZe(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},uZe=Object.defineProperty,dZe=Object.defineProperties,fZe=Object.getOwnPropertyDescriptors,wye=Object.getOwnPropertySymbols,pZe=Object.prototype.hasOwnProperty,hZe=Object.prototype.propertyIsEnumerable,zz=(e,t,r)=>t in e?uZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,mZe=(e,t)=>{for(var r in t||(t={}))pZe.call(t,r)&&zz(e,r,t[r]);if(wye)for(var r of wye(t))hZe.call(t,r)&&zz(e,r,t[r]);return e},gZe=(e,t)=>dZe(e,fZe(t)),Ua=(e,t,r)=>zz(e,typeof t!="symbol"?t+"":t,r),Vz=class extends R_{constructor(t,r){super(t,r),this.logger=t,this.core=r,Ua(this,"messages",new Map),Ua(this,"messagesWithoutClientAck",new Map),Ua(this,"name",hWe),Ua(this,"version",mWe),Ua(this,"initialized",!1),Ua(this,"storagePrefix",Ru),Ua(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);let o=await this.getRelayerMessagesWithoutClientAck();typeof o<"u"&&(this.messagesWithoutClientAck=o),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Ua(this,"set",async(n,o,s)=>{this.isInitialized();let i=Ki(o),a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[i]<"u")return i;if(a[i]=o,this.messages.set(n,a),s===tP.inbound){let c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,gZe(mZe({},c),{[i]:o}))}return await this.persist(),i}),Ua(this,"get",n=>{this.isInitialized();let o=this.messages.get(n);return typeof o>"u"&&(o={}),o}),Ua(this,"getWithoutAck",n=>{this.isInitialized();let o={};for(let s of n){let i=this.messagesWithoutClientAck.get(s)||{};o[s]=Object.values(i)}return o}),Ua(this,"has",(n,o)=>{this.isInitialized();let s=this.get(n),i=Ki(o);return typeof s[i]<"u"}),Ua(this,"ack",async(n,o)=>{this.isInitialized();let s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;let i=Ki(o);delete s[i],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),Ua(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Cr(t,this.name),this.core=r}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,$7(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,$7(t))}async getRelayerMessages(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?F7(t):void 0}async getRelayerMessagesWithoutClientAck(){let t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?F7(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},yZe=Object.defineProperty,wZe=Object.defineProperties,bZe=Object.getOwnPropertyDescriptors,bye=Object.getOwnPropertySymbols,xZe=Object.prototype.hasOwnProperty,vZe=Object.prototype.propertyIsEnumerable,jz=(e,t,r)=>t in e?yZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,sx=(e,t)=>{for(var r in t||(t={}))xZe.call(t,r)&&jz(e,r,t[r]);if(bye)for(var r of bye(t))vZe.call(t,r)&&jz(e,r,t[r]);return e},xye=(e,t)=>wZe(e,bZe(t)),Ec=(e,t,r)=>jz(e,typeof t!="symbol"?t+"":t,r),qz=class extends O_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,Ec(this,"events",new Rp.EventEmitter),Ec(this,"name",yWe),Ec(this,"queue",new Map),Ec(this,"publishTimeout",(0,Xe.toMiliseconds)(Xe.ONE_MINUTE)),Ec(this,"initialPublishTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),Ec(this,"needsTransportRestart",!1),Ec(this,"publish",async(n,o,s)=>{var i,a,c,u,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:o,opts:s}});let f=s?.ttl||gWe,p=s?.prompt||!1,h=s?.tag||0,y=s?.id||_n().toString(),w=Py(L5().protocol),x={id:y,method:s?.publishMethod||w.publish,params:sx({topic:n,message:o,ttl:f,prompt:p,tag:h,attestation:s?.attestation},s?.tvf)},v=`Failed to publish payload, please try again. id:${y} tag:${h}`;try{Ln((i=x.params)==null?void 0:i.prompt)&&((a=x.params)==null||delete a.prompt),Ln((c=x.params)==null?void 0:c.tag)&&((u=x.params)==null||delete u.tag);let T=new Promise(async E=>{let S=({id:O})=>{var D;((D=x.id)==null?void 0:D.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(Mn.publish,S),E())};this.relayer.events.on(Mn.publish,S);let _=xl(new Promise((O,D)=>{this.rpcPublish(x,s).then(O).catch(M=>{this.logger.warn(M,M?.message),D(M)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${y} tag:${h}`);try{await _,this.events.removeListener(Mn.publish,S)}catch(O){this.queue.set(y,{request:x,opts:s,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:y,topic:n,message:o,opts:s}}),await xl(T,this.publishTimeout,v)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(d=s?.internal)!=null&&d.throwOnFailedPublish)throw T}finally{this.queue.delete(y)}}),Ec(this,"publishCustom",async n=>{var o,s,i,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});let{payload:u,opts:d={}}=n,{attestation:f,tvf:p,publishMethod:h,prompt:y,tag:w,ttl:x=Xe.FIVE_MINUTES}=d,v=d.id||_n().toString(),T=Py(L5().protocol),E=h||T.publish,S={id:v,method:E,params:sx(xye(sx({},u),{ttl:x,prompt:y,tag:w,attestation:f}),p)},_=`Failed to publish custom payload, please try again. id:${v} tag:${w}`;try{Ln((o=S.params)==null?void 0:o.prompt)&&((s=S.params)==null||delete s.prompt),Ln((i=S.params)==null?void 0:i.tag)&&((a=S.params)==null||delete a.tag);let O=new Promise(async D=>{let M=({id:L})=>{var P;((P=S.id)==null?void 0:P.toString())===L.toString()&&(this.removeRequestFromQueue(L),this.relayer.events.removeListener(Mn.publish,M),D())};this.relayer.events.on(Mn.publish,M);let N=xl(new Promise((L,P)=>{this.rpcPublish(S,d).then(L).catch(R=>{this.logger.warn(R,R?.message),P(R)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${E} id:${v} tag:${w}`);try{await N,this.events.removeListener(Mn.publish,M)}catch(L){this.queue.set(v,{request:S,opts:d,attempt:1}),this.logger.warn(L,L?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:v,payload:u,opts:d}}),await xl(O,this.publishTimeout,_)}catch(O){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(O),(c=d?.internal)!=null&&c.throwOnFailedPublish)throw O}finally{this.queue.delete(v)}}),Ec(this,"on",(n,o)=>{this.events.on(n,o)}),Ec(this,"once",(n,o)=>{this.events.once(n,o)}),Ec(this,"off",(n,o)=>{this.events.off(n,o)}),Ec(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.relayer=t,this.logger=Cr(r,this.name),this.registerEventListeners()}get context(){return sr(this.logger)}async rpcPublish(t,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});let n=await this.relayer.request(t);return this.relayer.events.emit(Mn.publish,sx(sx({},t),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,r)=>{var n;let o=t.attempt+1;this.queue.set(r,xye(sx({},t),{attempt:o})),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${(n=t.request.params)==null?void 0:n.tag}, attempt: ${o}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Mn.connection_stalled);return}this.checkQueue()}),this.relayer.on(Mn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}},EZe=Object.defineProperty,AZe=(e,t,r)=>t in e?EZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ix=(e,t,r)=>AZe(e,typeof t!="symbol"?t+"":t,r),Wz=class{constructor(){ix(this,"map",new Map),ix(this,"set",(t,r)=>{let n=this.get(t);this.exists(t,r)||this.map.set(t,[...n,r])}),ix(this,"get",t=>this.map.get(t)||[]),ix(this,"exists",(t,r)=>this.get(t).includes(r)),ix(this,"delete",(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;let n=this.get(t);if(!this.exists(t,r))return;let o=n.filter(s=>s!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)}),ix(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}},CZe=Object.defineProperty,SZe=Object.defineProperties,IZe=Object.getOwnPropertyDescriptors,vye=Object.getOwnPropertySymbols,TZe=Object.prototype.hasOwnProperty,_Ze=Object.prototype.propertyIsEnumerable,Kz=(e,t,r)=>t in e?CZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,F5=(e,t)=>{for(var r in t||(t={}))TZe.call(t,r)&&Kz(e,r,t[r]);if(vye)for(var r of vye(t))_Ze.call(t,r)&&Kz(e,r,t[r]);return e},Pz=(e,t)=>SZe(e,IZe(t)),Or=(e,t,r)=>Kz(e,typeof t!="symbol"?t+"":t,r),Zz=class extends U_{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,Or(this,"subscriptions",new Map),Or(this,"topicMap",new Wz),Or(this,"events",new Rp.EventEmitter),Or(this,"name",CWe),Or(this,"version",SWe),Or(this,"pending",new Map),Or(this,"cached",[]),Or(this,"initialized",!1),Or(this,"storagePrefix",Ru),Or(this,"subscribeTimeout",(0,Xe.toMiliseconds)(Xe.ONE_MINUTE)),Or(this,"initialSubscribeTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),Or(this,"clientId"),Or(this,"batchSubscribeTopicsLimit",500),Or(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Or(this,"subscribe",async(n,o)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}});try{let i=L5(o),a={topic:n,relay:i,transportType:o?.transportType};(s=o?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);let c=await this.rpcSubscribe(n,i,o);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}})),c}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}}),Or(this,"unsubscribe",async(n,o)=>{this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(n,o.id,o):await this.unsubscribeByTopic(n,o)}),Or(this,"isSubscribed",n=>new Promise(o=>{o(this.topicMap.topics.includes(n))})),Or(this,"isKnownTopic",n=>new Promise(o=>{o(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),Or(this,"on",(n,o)=>{this.events.on(n,o)}),Or(this,"once",(n,o)=>{this.events.once(n,o)}),Or(this,"off",(n,o)=>{this.events.off(n,o)}),Or(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),Or(this,"start",async()=>{await this.onConnect()}),Or(this,"stop",async()=>{await this.onDisconnect()}),Or(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Or(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;let n=[];this.pending.forEach(o=>{n.push(o)}),await this.batchSubscribe(n)}),Or(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Vs.pulse,async()=>{await this.checkPending()}),this.events.on(Da.created,async n=>{let o=Da.created;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()}),this.events.on(Da.deleted,async n=>{let o=Da.deleted;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()})}),this.relayer=t,this.logger=Cr(r,this.name),this.clientId=""}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,r){let n=!1;try{n=this.getSubscription(t).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){let n=this.topicMap.get(t);await Promise.all(n.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}});try{let o=L5(n);await this.restartToComplete({topic:t,id:r,relay:o}),await this.rpcUnsubscribe(t,r,o);let s=Rr("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r,n){var o,s;let i=await this.getSubscriptionId(t);if((o=n?.internal)!=null&&o.skipSubscribe)return i;(!n||n?.transportType===Vr.relay)&&await this.restartToComplete({topic:t,id:t,relay:r});let a={method:Py(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});let c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===Vr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},(0,Xe.toMiliseconds)(Xe.ONE_SECOND)),i;let u=new Promise(async f=>{let p=h=>{h.topic===t&&(this.events.removeListener(Da.created,p),f(h.id))};this.events.on(Da.created,p);try{let h=await xl(new Promise((y,w)=>{this.relayer.request(a).catch(x=>{this.logger.warn(x,x?.message),w(x)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(Da.created,p),f(h)}catch{}}),d=await xl(u,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${t} failed, please try again`);return d?i:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Mn.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(t){if(!t.length)return;let r=t[0].relay,n={method:Py(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await xl(new Promise(o=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(o)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Mn.connection_stalled)}}async rpcBatchFetchMessages(t){if(!t.length)return;let r=t[0].relay,n={method:Py(r.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let o;try{o=await await xl(new Promise((s,i)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),i(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Mn.connection_stalled)}return o}rpcUnsubscribe(t,r,n){let o={method:Py(n.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,Pz(F5({},r),{id:t})),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,F5({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,n),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r)}addSubscription(t,r){this.subscriptions.set(t,F5({},r)),this.topicMap.set(r.topic,t),this.events.emit(Da.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});let r=this.subscriptions.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});let n=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(n.topic,t),this.events.emit(Da.deleted,Pz(F5({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Da.sync)}async onRestart(){if(this.cached.length){let t=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n"u"||!t.length)return;if(this.subscriptions.size&&!t.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){t.length&&(await this.rpcBatchSubscribe(t),this.onBatchSubscribe(await Promise.all(t.map(async r=>Pz(F5({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);let r=await this.rpcBatchFetchMessages(t);r&&r.messages&&(await U1e((0,Xe.toMiliseconds)(Xe.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return Ki(t+await this.getClientId())}},PZe=Object.defineProperty,Eye=Object.getOwnPropertySymbols,NZe=Object.prototype.hasOwnProperty,RZe=Object.prototype.propertyIsEnumerable,Gz=(e,t,r)=>t in e?PZe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Aye=(e,t)=>{for(var r in t||(t={}))NZe.call(t,r)&&Gz(e,r,t[r]);if(Eye)for(var r of Eye(t))RZe.call(t,r)&&Gz(e,r,t[r]);return e},rr=(e,t,r)=>Gz(e,typeof t!="symbol"?t+"":t,r),Yz=class extends B_{constructor(t){var r;super(t),rr(this,"protocol","wc"),rr(this,"version",2),rr(this,"core"),rr(this,"logger"),rr(this,"events",new Rp.EventEmitter),rr(this,"provider"),rr(this,"messages"),rr(this,"subscriber"),rr(this,"publisher"),rr(this,"name",bWe),rr(this,"transportExplicitlyClosed",!1),rr(this,"initialized",!1),rr(this,"connectionAttemptInProgress",!1),rr(this,"relayUrl"),rr(this,"projectId"),rr(this,"packageName"),rr(this,"bundleId"),rr(this,"hasExperiencedNetworkDisruption",!1),rr(this,"pingTimeout"),rr(this,"heartBeatTimeout",(0,Xe.toMiliseconds)(Xe.THIRTY_SECONDS+Xe.FIVE_SECONDS)),rr(this,"reconnectTimeout"),rr(this,"connectPromise"),rr(this,"reconnectInProgress",!1),rr(this,"requestsInFlight",[]),rr(this,"connectTimeout",(0,Xe.toMiliseconds)(Xe.ONE_SECOND*15)),rr(this,"request",async n=>{var o,s;this.logger.debug("Publishing Request Payload");let i=n.id||_n().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:n.method,topic:(o=n.params)==null?void 0:o.topic},"relayer.request - publishing...");let a=`${i}:${((s=n.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);let c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${i}`),a}}),rr(this,"resetPingTimeout",()=>{P5()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,o,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(i=(s=(o=(n=this.provider)==null?void 0:n.connection)==null?void 0:o.socket)==null?void 0:s.terminate)==null||i.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),rr(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),rr(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Mn.connect)}),rr(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),rr(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Mn.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),rr(this,"registerProviderListeners",()=>{this.provider.on(vc.payload,this.onPayloadHandler),this.provider.on(vc.connect,this.onConnectHandler),this.provider.on(vc.disconnect,this.onDisconnectHandler),this.provider.on(vc.error,this.onProviderErrorHandler)}),this.core=t.core,this.logger=ox({logger:(r=t.logger)!=null?r:wWe,name:this.name}),this.messages=new Vz(this.logger,t.core),this.subscriber=new Zz(this,this.logger),this.publisher=new qz(this,this.logger),this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Lye,S1e()?this.packageName=JF():I1e()&&(this.bundleId=JF()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return sr(this.logger)}get connected(){var t,r,n;return((n=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var t,r,n;return((n=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(t,r,n){this.isInitialized(),await this.publisher.publish(t,r,n),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now(),transportType:Vr.relay},tP.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,r){var n,o,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();let i=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(o=r?.internal)==null?void 0:o.throwOnFailedPublish,a=((s=this.subscriber.topicMap.get(t))==null?void 0:s[0])||"",c,u=d=>{d.topic===t&&(this.subscriber.off(Da.created,u),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Da.created,u)}),new Promise(async(d,f)=>{a=await this.subscriber.subscribe(t,Aye({internal:{throwOnFailedPublish:i}},r)).catch(p=>{i&&f(p)})||a,d()})]),a}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await xl(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(t).then(r).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tz())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}let r=t.sort((n,o)=>n.publishedAt-o.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(let n of r)try{await this.onMessageEvent(n)}catch(o){this.logger.warn(o,"Error while processing batch message event: "+o?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(t,r){let{topic:n}=t;if(!r.sessionExists){let o=pn(Xe.FIVE_MINUTES),s={topic:n,expiry:o,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Mn.message,t),await this.recordMessageEvent(t,tP.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to connect"))};this.provider.once(vc.disconnect,s),await xl(new Promise((i,a)=>{this.provider.connect().then(i).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(i=>{o(i)}).finally(()=>{this.provider.off(vc.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(i,a)=>{let c=()=>{o(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(vc.disconnect,c),await this.subscriber.start().then(i).catch(a).finally(()=>{this.provider.off(vc.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();let o=n;this.logger.warn({},o.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,(0,Xe.toMiliseconds)(r*1))),r++}}startPingTimeout(){var t,r,n,o,s;if(P5())try{(r=(t=this.provider)==null?void 0:t.connection)!=null&&r.socket&&((s=(o=(n=this.provider)==null?void 0:n.connection)==null?void 0:o.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(i){this.logger.warn(i,i?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();let t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new da(new lw(_1e({sdkVersion:Rz,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,r){let{topic:n,message:o}=t;await this.messages.set(n,o,r)}async shouldIgnoreMessageEvent(t){let{topic:r,message:n}=t;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;let o=this.messages.has(r,n);return o&&this.logger.warn(`Ignoring duplicate message: ${n}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Hc(t)){if(!t.method.endsWith(xWe))return;let r=t.params,{topic:n,message:o,publishedAt:s,attestation:i}=r.data,a={topic:n,message:o,publishedAt:s,transportType:Vr.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Aye({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else ua(t)&&this.events.emit(Mn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,tP.inbound),this.events.emit(Mn.message,t))}async acknowledgePayload(t){let r=bo(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(vc.payload,this.onPayloadHandler),this.provider.off(vc.connect,this.onConnectHandler),this.provider.off(vc.disconnect,this.onDisconnectHandler),this.provider.off(vc.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await Tz();aye(async r=>{t!==r&&(t=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vs.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&cye())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Mn.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,Xe.toMiliseconds)(vWe)))))}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}};BZe="[object RegExp]",kZe="[object String]",UZe="[object Number]",DZe="[object Boolean]",Iye="[object Arguments]",LZe="[object Symbol]",MZe="[object Date]",HZe="[object Map]",$Ze="[object Set]",FZe="[object Array]",zZe="[object Function]",VZe="[object ArrayBuffer]",Nz="[object Object]",jZe="[object Error]",qZe="[object DataView]",WZe="[object Uint8Array]",KZe="[object Uint8ClampedArray]",ZZe="[object Uint16Array]",GZe="[object Uint32Array]",YZe="[object BigUint64Array]",JZe="[object Int8Array]",QZe="[object Int16Array]",XZe="[object Int32Array]",eGe="[object BigInt64Array]",tGe="[object Float32Array]",rGe="[object Float64Array]";iGe=Object.defineProperty,_ye=Object.getOwnPropertySymbols,aGe=Object.prototype.hasOwnProperty,cGe=Object.prototype.propertyIsEnumerable,Jz=(e,t,r)=>t in e?iGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Pye=(e,t)=>{for(var r in t||(t={}))aGe.call(t,r)&&Jz(e,r,t[r]);if(_ye)for(var r of _ye(t))cGe.call(t,r)&&Jz(e,r,t[r]);return e},Zi=(e,t,r)=>Jz(e,typeof t!="symbol"?t+"":t,r),Ou=class extends k_{constructor(t,r,n,o=Ru,s=void 0){super(t,r,n,o),this.core=t,this.logger=r,this.name=n,Zi(this,"map",new Map),Zi(this,"version",EWe),Zi(this,"cached",[]),Zi(this,"initialized",!1),Zi(this,"getKey"),Zi(this,"storagePrefix",Ru),Zi(this,"recentlyDeleted",[]),Zi(this,"recentlyDeletedLimit",200),Zi(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>{this.getKey&&i!==null&&!Ln(i)?this.map.set(this.getKey(i),i):Kge(i)?this.map.set(i.id,i):Zge(i)&&this.map.set(i.topic,i)}),this.cached=[],this.initialized=!0)}),Zi(this,"set",async(i,a)=>{this.isInitialized(),this.map.has(i)?await this.update(i,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:i,value:a}),this.map.set(i,a),await this.persist())}),Zi(this,"get",i=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:i}),this.getData(i))),Zi(this,"getAll",i=>(this.isInitialized(),i?this.values.filter(a=>Object.keys(i).every(c=>sGe(a[c],i[c]))):this.values)),Zi(this,"update",async(i,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:i,update:a});let c=Pye(Pye({},this.getData(i)),a);this.map.set(i,c),await this.persist()}),Zi(this,"delete",async(i,a)=>{this.isInitialized(),this.map.has(i)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:i,reason:a}),this.map.delete(i),this.addToRecentlyDeleted(i),await this.persist())}),this.logger=Cr(r,this.name),this.storagePrefix=o,this.getKey=s}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){let r=this.map.get(t);if(!r){if(this.recentlyDeleted.includes(t)){let{message:o}=Ie("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(o),new Error(o)}let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},lGe=Object.defineProperty,uGe=(e,t,r)=>t in e?lGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vt=(e,t,r)=>uGe(e,typeof t!="symbol"?t+"":t,r),Qz=class{constructor(t,r){this.core=t,this.logger=r,Vt(this,"name",IWe),Vt(this,"version",TWe),Vt(this,"events",new Rp.default),Vt(this,"pairings"),Vt(this,"initialized",!1),Vt(this,"storagePrefix",Ru),Vt(this,"ignoredPayloadTypes",[vl]),Vt(this,"registeredMethods",[]),Vt(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Vt(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Vt(this,"create",async n=>{this.isInitialized();let o=Q7(),s=await this.core.crypto.setSymKey(o),i=pn(Xe.FIVE_MINUTES),a={protocol:aV},c={topic:s,expiry:i,relay:a,active:!1,methods:n?.methods},u=xz({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:o,relay:a,expiryTimestamp:i,methods:n?.methods});return this.events.emit(zm.create,c),this.core.expirer.set(s,i),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}}),Vt(this,"pair",async n=>{this.isInitialized();let o=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Cl.pairing_started]}});this.isValidPair(n,o);let{topic:s,symKey:i,relay:a,expiryTimestamp:c,methods:u}=bz(n.uri);o.props.properties.topic=s,o.addTrace(Cl.pairing_uri_validation_success),o.addTrace(Cl.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(s)){if(d=this.pairings.get(s),o.addTrace(Cl.existing_pairing),d.active)throw o.setError(Nu.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);o.addTrace(Cl.pairing_not_expired)}let f=c||pn(Xe.FIVE_MINUTES),p={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,p),o.addTrace(Cl.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(zm.create,p),o.addTrace(Cl.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),o.addTrace(Cl.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{o.setError(Nu.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw o.setError(Nu.subscribe_pairing_topic_failure),h}return o.addTrace(Cl.subscribe_pairing_topic_success),p}),Vt(this,"activate",async({topic:n})=>{this.isInitialized();let o=pn(Xe.FIVE_MINUTES);this.core.expirer.set(n,o),await this.pairings.update(n,{active:!0,expiry:o})}),Vt(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:o}=n;if(this.pairings.keys.includes(o)){let s=await this.sendRequest(o,"wc_pairingPing",{}),{done:i,resolve:a,reject:c}=Pp();this.events.once(cr("pairing_ping",s),({error:u})=>{u?c(u):a()}),await i()}}),Vt(this,"updateExpiry",async({topic:n,expiry:o})=>{this.isInitialized(),await this.pairings.update(n,{expiry:o})}),Vt(this,"updateMetadata",async({topic:n,metadata:o})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:o})}),Vt(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Vt(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:o}=n;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",Rr("USER_DISCONNECTED")),await this.deletePairing(o))}),Vt(this,"formatUriFromPairing",n=>{this.isInitialized();let{topic:o,relay:s,expiry:i,methods:a}=n,c=this.core.crypto.keychain.get(o);return xz({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:c,relay:s,expiryTimestamp:i,methods:a})}),Vt(this,"sendRequest",async(n,o,s)=>{let i=dr(o,s),a=await this.core.crypto.encode(n,i),c=$5[o].req;return this.core.history.set(n,i),this.core.relayer.publish(n,a,c),i.id}),Vt(this,"sendResult",async(n,o,s)=>{let i=bo(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=$5[c].res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)}),Vt(this,"sendError",async(n,o,s)=>{let i=la(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=$5[c]?$5[c].res:$5.unregistered_method.res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)}),Vt(this,"deletePairing",async(n,o)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Rr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),o?Promise.resolve():this.core.expirer.del(n)])}),Vt(this,"cleanup",async()=>{let n=this.pairings.getAll().filter(o=>ka(o.expiry));await Promise.all(n.map(o=>this.deletePairing(o.topic)))}),Vt(this,"onRelayEventRequest",async n=>{let{topic:o,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(o,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(o,s);default:return await this.onUnknownRpcMethodRequest(o,s)}}),Vt(this,"onRelayEventResponse",async n=>{let{topic:o,payload:s}=n,i=(await this.core.history.get(o,s.id)).request.method;return i==="wc_pairingPing"?this.onPairingPingResponse(o,s):this.onUnknownRpcMethodResponse(i)}),Vt(this,"onPairingPingRequest",async(n,o)=>{let{id:s}=o;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(zm.ping,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}}),Vt(this,"onPairingPingResponse",(n,o)=>{let{id:s}=o;setTimeout(()=>{Jr(o)?this.events.emit(cr("pairing_ping",s),{}):Ir(o)&&this.events.emit(cr("pairing_ping",s),{error:o.error})},500)}),Vt(this,"onPairingDeleteRequest",async(n,o)=>{let{id:s}=o;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(zm.delete,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}}),Vt(this,"onUnknownRpcMethodRequest",async(n,o)=>{let{id:s,method:i}=o;try{if(this.registeredMethods.includes(i))return;let a=Rr("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Vt(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Rr("WC_METHOD_UNSUPPORTED",n))}),Vt(this,"isValidPair",(n,o)=>{var s;if(!_s(n)){let{message:a}=Ie("MISSING_OR_INVALID",`pair() params: ${n}`);throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(!Wge(n.uri)){let{message:a}=Ie("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw o.setError(Nu.malformed_pairing_uri),new Error(a)}let i=bz(n?.uri);if(!((s=i?.relay)!=null&&s.protocol)){let{message:a}=Ie("MISSING_OR_INVALID","pair() uri#relay-protocol");throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(!(i!=null&&i.symKey)){let{message:a}=Ie("MISSING_OR_INVALID","pair() uri#symKey");throw o.setError(Nu.malformed_pairing_uri),new Error(a)}if(i!=null&&i.expiryTimestamp&&(0,Xe.toMiliseconds)(i?.expiryTimestamp){if(!_s(n)){let{message:s}=Ie("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)}),Vt(this,"isValidDisconnect",async n=>{if(!_s(n)){let{message:s}=Ie("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)}),Vt(this,"isValidPairingTopic",async n=>{if(!An(n,!1)){let{message:o}=Ie("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(o)}if(!this.pairings.keys.includes(n)){let{message:o}=Ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(o)}if(ka(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:o}=Ie("EXPIRED",`pairing topic: ${n}`);throw new Error(o)}}),this.core=t,this.logger=Cr(r,this.name),this.pairings=new Ou(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sr(this.logger)}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(Mn.message,async t=>{let{topic:r,message:n,transportType:o}=t;if(this.pairings.keys.includes(r)&&o!==Vr.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{let s=await this.core.crypto.decode(r,n);Hc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ua(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(La.expired,async t=>{let{topic:r}=z7(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(zm.expire,{topic:r}))})}},dGe=Object.defineProperty,fGe=(e,t,r)=>t in e?dGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Wo=(e,t,r)=>fGe(e,typeof t!="symbol"?t+"":t,r),Xz=class extends N_{constructor(t,r){super(t,r),this.core=t,this.logger=r,Wo(this,"records",new Map),Wo(this,"events",new Rp.EventEmitter),Wo(this,"name",_We),Wo(this,"version",PWe),Wo(this,"cached",[]),Wo(this,"initialized",!1),Wo(this,"storagePrefix",Ru),Wo(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Wo(this,"set",(n,o,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:o,chainId:s}),this.records.has(o.id))return;let i={id:o.id,topic:n,request:{method:o.method,params:o.params||null},chainId:s,expiry:pn(Xe.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Al.created,i)}),Wo(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let o=await this.getRecord(n.id);typeof o.response>"u"&&(o.response=Ir(n)?{error:n.error}:{result:n.result},this.records.set(o.id,o),this.persist(),this.events.emit(Al.updated,o))}),Wo(this,"get",async(n,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:o}),await this.getRecord(o))),Wo(this,"delete",(n,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(s=>{if(s.topic===n){if(typeof o<"u"&&s.id!==o)return;this.records.delete(s.id),this.events.emit(Al.deleted,s)}}),this.persist()}),Wo(this,"exists",async(n,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===n:!1)),Wo(this,"on",(n,o)=>{this.events.on(n,o)}),Wo(this,"once",(n,o)=>{this.events.once(n,o)}),Wo(this,"off",(n,o)=>{this.events.off(n,o)}),Wo(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(n)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();let r=this.records.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Al.sync)}async restore(){try{let t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(Al.created,t=>{let r=Al.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Al.updated,t=>{let r=Al.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Al.deleted,t=>{let r=Al.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.core.heartbeat.on(Vs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(r=>{(0,Xe.toMiliseconds)(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Al.deleted,r,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},pGe=Object.defineProperty,hGe=(e,t,r)=>t in e?pGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ps=(e,t,r)=>hGe(e,typeof t!="symbol"?t+"":t,r),eV=class extends D_{constructor(t,r){super(t,r),this.core=t,this.logger=r,Ps(this,"expirations",new Map),Ps(this,"events",new Rp.EventEmitter),Ps(this,"name",NWe),Ps(this,"version",RWe),Ps(this,"cached",[]),Ps(this,"initialized",!1),Ps(this,"storagePrefix",Ru),Ps(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ps(this,"has",n=>{try{let o=this.formatTarget(n);return typeof this.getExpiration(o)<"u"}catch{return!1}}),Ps(this,"set",(n,o)=>{this.isInitialized();let s=this.formatTarget(n),i={target:s,expiry:o};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(La.created,{target:s,expiration:i})}),Ps(this,"get",n=>{this.isInitialized();let o=this.formatTarget(n);return this.getExpiration(o)}),Ps(this,"del",n=>{if(this.isInitialized(),this.has(n)){let o=this.formatTarget(n),s=this.getExpiration(o);this.expirations.delete(o),this.events.emit(La.deleted,{target:o,expiration:s})}}),Ps(this,"on",(n,o)=>{this.events.on(n,o)}),Ps(this,"once",(n,o)=>{this.events.once(n,o)}),Ps(this,"off",(n,o)=>{this.events.off(n,o)}),Ps(this,"removeListener",(n,o)=>{this.events.removeListener(n,o)}),this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(t){if(typeof t=="string")return N1e(t);if(typeof t=="number")return R1e(t);let{message:r}=Ie("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(La.sync)}async restore(){try{let t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){let{message:r}=Ie("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){let r=this.expirations.get(t);if(!r){let{message:n}=Ie("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(t,r){let{expiry:n}=r;(0,Xe.toMiliseconds)(n)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(La.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Vs.pulse,()=>this.checkExpirations()),this.events.on(La.created,t=>{let r=La.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(La.expired,t=>{let r=La.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(La.deleted,t=>{let r=La.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}},mGe=Object.defineProperty,gGe=(e,t,r)=>t in e?mGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Kn=(e,t,r)=>gGe(e,typeof t!="symbol"?t+"":t,r),tV=class extends L_{constructor(t,r,n){super(t,r,n),this.core=t,this.logger=r,this.store=n,Kn(this,"name",OWe),Kn(this,"abortController"),Kn(this,"isDevEnv"),Kn(this,"verifyUrlV3",kWe),Kn(this,"storagePrefix",Ru),Kn(this,"version",Dye),Kn(this,"publicKey"),Kn(this,"fetchPromise"),Kn(this,"init",async()=>{var o;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,Xe.toMiliseconds)((o=this.publicKey)==null?void 0:o.expiresAt){if(!Ty()||this.isDevEnv)return;let s=window.location.origin,{id:i,decryptedId:a}=o,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${i}&decryptedId=${a}`;try{let u=(0,kye.getDocument)(),d=this.startAbortTimer(Xe.ONE_SECOND*5),f=await new Promise((p,h)=>{let y=()=>{window.removeEventListener("message",x),u.body.removeChild(w),h("attestation aborted")};this.abortController.signal.addEventListener("abort",y);let w=u.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});let x=v=>{if(v.data&&typeof v.data=="string")try{let T=JSON.parse(v.data);if(T.type==="verify_attestation"){if(Hl(T.attestation).payload.id!==i)return;clearInterval(d),u.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",x),p(T.attestation===null?"":T.attestation)}}catch(T){this.logger.warn(T)}};u.body.appendChild(w),window.addEventListener("message",x,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Kn(this,"resolve",async o=>{if(this.isDevEnv)return"";let{attestationId:s,hash:i,encryptedId:a}=o;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Hl(s).payload.id!==a)return;let u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!i)return;let c=this.getVerifyUrl(o?.verifyUrl);return this.fetchAttestation(i,c)}),Kn(this,"fetchAttestation",async(o,s)=>{this.logger.debug(`resolving attestation: ${o} from url: ${s}`);let i=this.startAbortTimer(Xe.ONE_SECOND*5),a=await fetch(`${s}/attestation/${o}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),a.status===200?await a.json():void 0}),Kn(this,"getVerifyUrl",o=>{let s=o||ax;return UWe.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${ax}`),s=ax),s}),Kn(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let o=this.startAbortTimer(Xe.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(o),await s.json()}catch(o){this.logger.warn(o)}}),Kn(this,"persistPublicKey",async o=>{this.logger.debug(o,"persisting public key to local storage"),await this.store.setItem(this.storeKey,o),this.publicKey=o}),Kn(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Kn(this,"isValidJwtAttestation",async o=>{let s=await this.getPublicKey();try{if(s)return this.validateAttestation(o,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(o,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Kn(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Kn(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{let i=await this.fetchPublicKey();i&&(await this.persistPublicKey(i),s(i))});let o=await this.fetchPromise;return this.fetchPromise=void 0,o}),Kn(this,"validateAttestation",(o,s)=>{let i=Fge(o,s.publicKey),a={hasExpired:(0,Xe.toMiliseconds)(i.exp)this.abortController.abort(),(0,Xe.toMiliseconds)(t))}},yGe=Object.defineProperty,wGe=(e,t,r)=>t in e?yGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Nye=(e,t,r)=>wGe(e,typeof t!="symbol"?t+"":t,r),rV=class extends M_{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,Nye(this,"context",DWe),Nye(this,"registerDeviceToken",async n=>{let{clientId:o,token:s,notificationType:i,enableEncrypted:a=!1}=n,c=`${LWe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:i,token:s,always_raw:a})})}),this.logger=Cr(r,this.context)}},bGe=Object.defineProperty,Rye=Object.getOwnPropertySymbols,xGe=Object.prototype.hasOwnProperty,vGe=Object.prototype.propertyIsEnumerable,nV=(e,t,r)=>t in e?bGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,z5=(e,t)=>{for(var r in t||(t={}))xGe.call(t,r)&&nV(e,r,t[r]);if(Rye)for(var r of Rye(t))vGe.call(t,r)&&nV(e,r,t[r]);return e},Ro=(e,t,r)=>nV(e,typeof t!="symbol"?t+"":t,r),oV=class extends H_{constructor(t,r,n=!0){super(t,r,n),this.core=t,this.logger=r,Ro(this,"context",HWe),Ro(this,"storagePrefix",Ru),Ro(this,"storageVersion",MWe),Ro(this,"events",new Map),Ro(this,"shouldPersist",!1),Ro(this,"init",async()=>{if(!R5())try{let o={eventId:tz(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:XF(this.core.relayer.protocol,this.core.relayer.version,Rz)}}};await this.sendEvent([o])}catch(o){this.logger.warn(o)}}),Ro(this,"createEvent",o=>{let{event:s="ERROR",type:i="",properties:{topic:a,trace:c}}=o,u=tz(),d=this.core.projectId||"",f=Date.now(),p=z5({eventId:u,timestamp:f,props:{event:s,type:i,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,p),this.shouldPersist=!0),p}),Ro(this,"getEvent",o=>{let{eventId:s,topic:i}=o;if(s)return this.events.get(s);let a=Array.from(this.events.values()).find(c=>c.props.properties.topic===i);if(a)return z5(z5({},a),this.setMethods(a.eventId))}),Ro(this,"deleteEvent",o=>{let{eventId:s}=o;this.events.delete(s),this.shouldPersist=!0}),Ro(this,"setEventListeners",()=>{this.core.heartbeat.on(Vs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(o=>{(0,Xe.fromMiliseconds)(Date.now())-(0,Xe.fromMiliseconds)(o.timestamp)>$We&&(this.events.delete(o.eventId),this.shouldPersist=!0)})})}),Ro(this,"setMethods",o=>({addTrace:s=>this.addTrace(o,s),setError:s=>this.setError(o,s)})),Ro(this,"addTrace",(o,s)=>{let i=this.events.get(o);i&&(i.props.properties.trace.push(s),this.events.set(o,i),this.shouldPersist=!0)}),Ro(this,"setError",(o,s)=>{let i=this.events.get(o);i&&(i.props.type=s,i.timestamp=Date.now(),this.events.set(o,i),this.shouldPersist=!0)}),Ro(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ro(this,"restore",async()=>{try{let o=await this.core.storage.getItem(this.storageKey)||[];if(!o.length)return;o.forEach(s=>{this.events.set(s.eventId,z5(z5({},s),this.setMethods(s.eventId)))})}catch(o){this.logger.warn(o)}}),Ro(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;let o=[];for(let[s,i]of this.events)i.props.type&&o.push(i);if(o.length!==0)try{if((await this.sendEvent(o)).ok)for(let s of o)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Ro(this,"sendEvent",async o=>{let s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${FWe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Rz}${s}`,{method:"POST",body:JSON.stringify(o)})}),Ro(this,"getAppDomain",()=>QF().url),this.logger=Cr(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},EGe=Object.defineProperty,Oye=Object.getOwnPropertySymbols,AGe=Object.prototype.hasOwnProperty,CGe=Object.prototype.propertyIsEnumerable,sV=(e,t,r)=>t in e?EGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Bye=(e,t)=>{for(var r in t||(t={}))AGe.call(t,r)&&sV(e,r,t[r]);if(Oye)for(var r of Oye(t))CGe.call(t,r)&&sV(e,r,t[r]);return e},zr=(e,t,r)=>sV(e,typeof t!="symbol"?t+"":t,r),iV=class e extends P_{constructor(t){var r;super(t),zr(this,"protocol",Uye),zr(this,"version",Dye),zr(this,"name",rP),zr(this,"relayUrl"),zr(this,"projectId"),zr(this,"customStoragePrefix"),zr(this,"events",new Rp.EventEmitter),zr(this,"logger"),zr(this,"heartbeat"),zr(this,"relayer"),zr(this,"crypto"),zr(this,"storage"),zr(this,"history"),zr(this,"expirer"),zr(this,"pairing"),zr(this,"verify"),zr(this,"echoClient"),zr(this,"linkModeSupportedApps"),zr(this,"eventClient"),zr(this,"initialized",!1),zr(this,"logChunkController"),zr(this,"on",(a,c)=>this.events.on(a,c)),zr(this,"once",(a,c)=>this.events.once(a,c)),zr(this,"off",(a,c)=>this.events.off(a,c)),zr(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),zr(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;let d={topic:a,message:c,publishedAt:Date.now(),transportType:Vr.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:u})});let n=this.getGlobalCore(t?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Lye,this.customStoragePrefix=t!=null&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";let o=X2({level:typeof t?.logger=="string"&&t.logger?t.logger:cWe.logger,name:rP}),{logger:s,chunkLoggerController:i}=Fl({opts:o,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=i,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Cr(s,this.name),this.heartbeat=new iw,this.crypto=new Fz(this,this.logger,t?.keychain),this.history=new Xz(this,this.logger),this.expirer=new eV(this,this.logger),this.storage=t!=null&&t.storage?t.storage:new aw(Bye(Bye({},lWe),t?.storageOptions)),this.relayer=new Yz({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Qz(this,this.logger),this.verify=new tV(this,this.logger,this.storage),this.echoClient=new rV(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new oV(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){let r=new e(t);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(AWe,n),r}get context(){return sr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var t;return(t=this.logChunkController)==null?void 0:t.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(dye,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(dye)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(t){var r;try{if(this.isGlobalCoreDisabled())return;let n=`_walletConnectCore_${((r=t.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=t}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},Yye=iV});var sP,Nt,t2e,r2e,n2e,vV,cV,Qye,SGe,Xye,IGe,lx,TGe,Zo,lV,Bu,_Ge,PGe,NGe,RGe,OGe,BGe,kGe,UGe,iP,oP,DGe,LGe,MGe,e2e,HGe,$Ge,dV,lr,Go,Ee,fV,pV,hV,mV,gV,yV,wV,FGe,zGe,uV,bV,VGe,jGe,jt,xV,o2e,s2e=b(()=>{l();sP=Ht(ks(),1);Jye();DH();eP();gh();Nt=Ht(jd(),1);$c();t2e="wc",r2e=2,n2e="client",vV=`${t2e}@${r2e}:${n2e}:`,cV={name:n2e,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Qye="WALLETCONNECT_DEEPLINK_CHOICE",SGe="proposal",Xye="Proposal expired",IGe="session",lx=Nt.SEVEN_DAYS,TGe="engine",Zo={wc_sessionPropose:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Nt.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Nt.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Nt.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Nt.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Nt.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Nt.FIVE_MINUTES,prompt:!1,tag:1119}}},lV={min:Nt.FIVE_MINUTES,max:Nt.SEVEN_DAYS},Bu={idle:"IDLE",active:"ACTIVE"},_Ge={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},PGe="request",NGe=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],RGe="wc",OGe="auth",BGe="authKeys",kGe="pairingTopics",UGe="requests",iP=`${RGe}@${1.5}:${OGe}:`,oP=`${iP}:PUB_KEY`,DGe=Object.defineProperty,LGe=Object.defineProperties,MGe=Object.getOwnPropertyDescriptors,e2e=Object.getOwnPropertySymbols,HGe=Object.prototype.hasOwnProperty,$Ge=Object.prototype.propertyIsEnumerable,dV=(e,t,r)=>t in e?DGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,lr=(e,t)=>{for(var r in t||(t={}))HGe.call(t,r)&&dV(e,r,t[r]);if(e2e)for(var r of e2e(t))$Ge.call(t,r)&&dV(e,r,t[r]);return e},Go=(e,t)=>LGe(e,MGe(t)),Ee=(e,t,r)=>dV(e,typeof t!="symbol"?t+"":t,r),fV=class extends F_{constructor(t){super(t),Ee(this,"name",TGe),Ee(this,"events",new sP.default),Ee(this,"initialized",!1),Ee(this,"requestQueue",{state:Bu.idle,queue:[]}),Ee(this,"sessionRequestQueue",{state:Bu.idle,queue:[]}),Ee(this,"emittedSessionRequests",new O7({limit:500})),Ee(this,"requestQueueDelay",Nt.ONE_SECOND),Ee(this,"expectedPairingMethodMap",new Map),Ee(this,"recentlyDeletedMap",new Map),Ee(this,"recentlyDeletedLimit",200),Ee(this,"relayMessageCache",[]),Ee(this,"pendingSessions",new Map),Ee(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Zo)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,Nt.toMiliseconds)(this.requestQueueDelay)))}),Ee(this,"connect",async r=>{var n;this.isInitialized(),await this.confirmOnlineStateOrThrow();let o=Go(lr({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(o),o.optionalNamespaces=jge(o.requiredNamespaces,o.optionalNamespaces),o.requiredNamespaces={};let{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:d,authentication:f,walletPay:p}=o,h=((n=f?.[0])==null?void 0:n.ttl)||Zo.wc_sessionPropose.req.ttl||Nt.FIVE_MINUTES;this.validateRequestExpiry(h);let y=s,w,x=!1;try{if(y){let N=this.client.core.pairing.pairings.get(y);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),x=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${y}) failed`),N}if(!y||!x){let{topic:N,uri:L}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});y=N,w=L}if(!y){let{message:N}=Ie("NO_MATCHING_KEY",`connect() pairing topic: ${y}`);throw new Error(N)}let v=await this.client.core.crypto.generateKeyPair(),T=pn(h),E=lr(Go(lr(lr({requiredNamespaces:i,optionalNamespaces:a,relays:d??[{protocol:aV}],proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:T,pairingTopic:y},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Tn()}),(f||p)&&{requests:{authentication:f?.map(N=>{let{domain:L,chains:P,nonce:R,uri:I,exp:B,nbf:C,type:A,statement:U,requestId:H,resources:k,signatureTypes:F}=N;return{domain:L,chains:P,nonce:R,type:A??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:B,nbf:C,statement:U,requestId:H,resources:k,signatureTypes:F}}),walletPay:p}}),S=cr("session_connect",E.id),{reject:_,resolve:O,done:D}=Pp(h,Xye),M=({id:N})=>{N===E.id&&(this.client.events.off("proposal_expire",M),this.pendingSessions.delete(E.id),this.events.emit(S,{error:{message:Xye,code:0}}))};return this.client.events.on("proposal_expire",M),this.events.once(S,({error:N,session:L})=>{this.client.events.off("proposal_expire",M),N?_(N):L&&O(L)}),await this.setProposal(E.id,E),await this.sendProposeSession({proposal:E,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:E.id}}}).catch(N=>{throw this.deleteProposal(E.id),N}),{uri:w,approval:D}}),Ee(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),Ee(this,"approve",async r=>{var n,o,s;let i=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[Ac.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(L){throw i.setError(Vm.no_internet_connection),L}try{await this.isValidProposalId(r?.id)}catch(L){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),i.setError(Vm.proposal_not_found),L}try{await this.isValidApprove(r)}catch(L){throw this.client.logger.error("approve() -> isValidApprove() failed"),i.setError(Vm.session_approve_namespace_validation_failure),L}let{id:a,relayProtocol:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=r,y=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:i.eventId});let{pairingTopic:w,proposer:x,requiredNamespaces:v,optionalNamespaces:T}=y,E=(o=this.client.core.eventClient)==null?void 0:o.getEvent({topic:w});E||(E=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ac.session_approve_started,properties:{topic:w,trace:[Ac.session_approve_started,Ac.session_namespaces_validation_success]}}));let S=await this.client.core.crypto.generateKeyPair(),_=x.publicKey,O=await this.client.core.crypto.generateSharedKey(S,_),D=Go(lr(lr(lr({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:S,metadata:this.client.metadata},expiry:pn(lx)},d&&{sessionProperties:d}),f&&{scopedProperties:f}),p&&{sessionConfig:p}),{proposalRequestsResponses:h}),M=Vr.relay;E.addTrace(Ac.subscribing_session_topic);try{await this.client.core.relayer.subscribe(O,{transportType:M,internal:{skipSubscribe:!0}})}catch(L){throw E.setError(Vm.subscribe_session_topic_failure),L}E.addTrace(Ac.subscribe_session_topic_success);let N=Go(lr({},D),{topic:O,requiredNamespaces:v,optionalNamespaces:T,pairingTopic:w,acknowledged:!1,self:D.controller,peer:{publicKey:x.publicKey,metadata:x.metadata},controller:S,transportType:Vr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(O,N),E.addTrace(Ac.store_session);try{await this.sendApproveSession({sessionTopic:O,proposal:y,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:S},sessionSettleRequest:D,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:lr({correlationId:a},this.getTVFApproveParams(N))}}),E.addTrace(Ac.session_approve_publish_success)}catch(L){throw this.client.logger.error(L),this.client.session.delete(O,Rr("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(O),L}return this.client.core.eventClient.deleteEvent({eventId:E.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:x.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(O,pn(lx)),{topic:O,acknowledged:()=>Promise.resolve(this.client.session.get(O))}}),Ee(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(i){throw this.client.logger.error("reject() -> isValidReject() failed"),i}let{id:n,reason:o}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(i){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),i}s&&await this.sendError({id:n,topic:s,error:o,rpcOpts:Zo.wc_sessionPropose.reject}),await this.deleteProposal(n)}),Ee(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}let{topic:n,namespaces:o}=r,{done:s,resolve:i,reject:a}=Pp(Nt.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tn(),u=_n().toString(),d=this.client.session.get(n).namespaces;return this.events.once(cr("session_update",c),({error:f})=>{f?a(f):i()}),await this.client.session.update(n,{namespaces:o}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:o},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:d}),a(f)}),{acknowledged:s}}),Ee(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}let{topic:n}=r,o=Tn(),{done:s,resolve:i,reject:a}=Pp(Nt.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(cr("session_extend",o),({error:c})=>{c?a(c):i()}),await this.setExpiry(n,pn(lx)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:o,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),Ee(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}let{chainId:n,request:o,topic:s,expiry:i=Zo.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let c=Tn(),u=_n().toString(),{done:d,resolve:f,reject:p}=Pp(i,"Request expired. Please try again.");this.events.once(cr("session_request",c),({error:x,result:v})=>{x?p(x):f(v)});let h="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:Go(lr({},o),{expiryTimestamp:pn(i)}),chainId:n},expiry:i,throwOnFailedPublish:!0,appLink:y}).catch(x=>p(x)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),await d();let w={request:Go(lr({},o),{expiryTimestamp:pn(i)}),chainId:n};return await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:w,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),x()}),new Promise(async x=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){let T=await B1e(this.client.core.storage,Qye);await O1e({id:c,topic:s,wcDeepLink:T})}x()}),d()]).then(x=>x[2])}),Ee(this,"respond",async r=>{var n,o;this.isInitialized();let s=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||((o=(n=r?.response)==null?void 0:n.id)==null?void 0:o.toString()),trace:[Ac.session_request_response_started]}});try{await this.isValidRespond(r)}catch(f){throw s.addTrace(f?.message),s.setError(Vm.session_request_response_validation_failure),f}s.addTrace(Ac.session_request_response_validation_success);let{topic:i,response:a}=r,{id:c}=a,u=this.client.session.get(i);u.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let d=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(Ac.session_request_response_publish_started),Jr(a)?await this.sendResult({id:c,topic:i,result:a.result,throwOnFailedPublish:!0,appLink:d}):Ir(a)&&await this.sendError({id:c,topic:i,error:a.error,appLink:d}),this.cleanupAfterResponse(r)}catch(f){throw s.addTrace(f?.message),s.setError(Vm.session_request_response_publish_failure),f}}),Ee(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(o){throw this.client.logger.error("ping() -> isValidPing() failed"),o}let{topic:n}=r;if(this.client.session.keys.includes(n)){let o=Tn(),s=_n().toString(),{done:i,resolve:a,reject:c}=Pp(Nt.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(cr("session_ping",o),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),Ee(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);let{topic:n,event:o,chainId:s}=r,i=_n().toString(),a=Tn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:o,chainId:s},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:a})}),Ee(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Rr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:o}=Ie("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(o)}}),Ee(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>qge(n,r)))),Ee(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),Ee(this,"authenticate",async(r,n)=>{var o;this.isInitialized(),this.isValidAuthenticate(r);let s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((o=this.client.metadata.redirect)==null?void 0:o.linkMode),i=s?Vr.link_mode:Vr.relay;i===Vr.relay&&await this.confirmOnlineStateOrThrow();let{chains:a,statement:c="",uri:u,domain:d,nonce:f,type:p,exp:h,nbf:y,methods:w=[],expiry:x}=r,v=[...r.resources||[]],{topic:T,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:i});this.client.logger.info({message:"Generated new pairing",pairing:{topic:T,uri:E}});let S=await this.client.core.crypto.generateKeyPair(),_=tx(S);if(await Promise.all([this.client.auth.authKeys.set(oP,{responseTopic:_,publicKey:S}),this.client.auth.pairingTopics.set(_,{topic:_,pairingTopic:T})]),await this.client.core.relayer.subscribe(_,{transportType:i}),this.client.logger.info(`sending request to new pairing topic: ${T}`),w.length>0){let{namespace:k}=bl(a[0]),F=ege(k,"request",w);k5(v)&&(F=tge(F,v.pop())),v.push(F)}let O=x&&x>Zo.wc_sessionAuthenticate.req.ttl?x:Zo.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:p??"caip122",chains:a,statement:c,aud:u,domain:d,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:y,resources:v},requester:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:pn(O)},M={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},N={requiredNamespaces:{},optionalNamespaces:M,relays:[{protocol:"irn"}],pairingTopic:T,proposer:{publicKey:S,metadata:this.client.metadata},expiryTimestamp:pn(Zo.wc_sessionPropose.req.ttl),id:Tn()},{done:L,resolve:P,reject:R}=Pp(O,"Request expired"),I=Tn(),B=cr("session_connect",N.id),C=cr("session_request",I),A=async({error:k,session:F})=>{this.events.off(C,U),k?R(k):F&&P({session:F})},U=async k=>{var F,j,W;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),k.error){let ye=Rr("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return k.error.code===ye.code?void 0:(this.events.off(B,A),R(k.error.message))}await this.deleteProposal(N.id),this.events.off(B,A);let{cacaos:ae,responder:te}=k.result,X=[],pe=[];for(let ye of ae){await az({cacao:ye,projectId:this.client.core.projectId})||(this.client.logger.error(ye,"Signature verification failed"),R(Rr("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:Re}=ye,Et=k5(Re.resources),kt=[K7(Re.iss)],At=B5(Re.iss);if(Et){let ur=lz(Et),_r=uz(Et);X.push(...ur),kt.push(..._r)}for(let ur of kt)pe.push(`${ur}:${At}`)}let me=await this.client.core.crypto.generateSharedKey(S,te.publicKey),Ne;X.length>0&&(Ne={topic:me,acknowledged:!0,self:{publicKey:S,metadata:this.client.metadata},peer:te,controller:te.publicKey,expiry:pn(lx),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:T,namespaces:Ez([...new Set(X)],[...new Set(pe)]),transportType:i},await this.client.core.relayer.subscribe(me,{transportType:i}),await this.client.session.set(me,Ne),T&&await this.client.core.pairing.updateMetadata({topic:T,metadata:te.metadata}),Ne=this.client.session.get(me)),(F=this.client.metadata.redirect)!=null&&F.linkMode&&(j=te.metadata.redirect)!=null&&j.linkMode&&(W=te.metadata.redirect)!=null&&W.universal&&n&&(this.client.core.addLinkModeSupportedApp(te.metadata.redirect.universal),this.client.session.update(me,{transportType:Vr.link_mode})),P({auths:ae,session:Ne})};this.events.once(B,A),this.events.once(C,U);let H;try{if(s){let k=dr("wc_sessionAuthenticate",D,I);this.client.core.history.set(T,k);let F=await this.client.core.crypto.encode("",k,{type:ex,encoding:Np});H=M5(n,T,F)}else await Promise.all([this.sendRequest({topic:T,method:"wc_sessionAuthenticate",params:D,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:T,method:"wc_sessionPropose",params:N,expiry:Zo.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(k){throw this.events.off(B,A),this.events.off(C,U),k}return await this.setProposal(N.id,N),await this.setAuthRequest(I,{request:Go(lr({},D),{verifyContext:{}}),pairingTopic:T,transportType:i}),{uri:H??E,response:L}}),Ee(this,"approveSessionAuthenticate",async r=>{let{id:n,auths:o}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[jm.authenticated_session_approve_started]}});try{this.isInitialized()}catch(x){throw s.setError(cx.no_internet_connection),x}let i=this.getPendingAuthRequest(n);if(!i)throw s.setError(cx.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);let a=i.transportType||Vr.relay;a===Vr.relay&&await this.confirmOnlineStateOrThrow();let c=i.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=tx(c),f={type:vl,receiverPublicKey:c,senderPublicKey:u},p=[],h=[];for(let x of o){if(!await az({cacao:x,projectId:this.client.core.projectId})){s.setError(cx.invalid_cacao);let _=Rr("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:_,encodeOpts:f}),new Error(_.message)}s.addTrace(jm.cacaos_verified);let{p:v}=x,T=k5(v.resources),E=[K7(v.iss)],S=B5(v.iss);if(T){let _=lz(T),O=uz(T);p.push(..._),E.push(...O)}for(let _ of E)h.push(`${_}:${S}`)}let y=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(jm.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:i.requester.metadata},controller:c,expiry:pn(lx),authentication:o,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:Ez([...new Set(p)],[...new Set(h)]),transportType:a},s.addTrace(jm.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(x){throw s.setError(cx.subscribe_authenticated_session_topic_failure),x}s.addTrace(jm.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),s.addTrace(jm.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}s.addTrace(jm.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:o,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,a)})}catch(x){throw s.setError(cx.authenticated_session_approve_publish_failure),x}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}}),Ee(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();let{id:n,reason:o}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===Vr.relay&&await this.confirmOnlineStateOrThrow();let i=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=tx(i),u={type:vl,receiverPublicKey:i,senderPublicKey:a};await this.sendError({id:n,topic:c,error:o,encodeOpts:u,rpcOpts:Zo.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),Ee(this,"formatAuthMessage",r=>{this.isInitialized();let{request:n,iss:o}=r;return cz(n,o)}),Ee(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{let r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),Ee(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(s=>{var i,a;return((i=s.peerMetadata)==null?void 0:i.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),Ee(this,"deleteSession",async r=>{var n;let{topic:o,expirerHasDeleted:s=!1,emitEvent:i=!0,id:a=0}=r,{self:c}=this.client.session.get(o);await this.client.core.relayer.unsubscribe(o),await this.client.session.delete(o,Rr("USER_DISCONNECTED")),this.addToRecentlyDeleted(o,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(o)&&await this.client.core.crypto.deleteSymKey(o),s||this.client.core.expirer.del(o),this.client.core.storage.removeItem(Qye).catch(u=>this.client.logger.warn(u)),o===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Bu.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===o).map(u=>this.deletePendingSessionRequest(u.id,Rr("USER_DISCONNECTED")))),i&&this.client.events.emit("session_delete",{id:a,topic:o})}),Ee(this,"deleteProposal",async(r,n)=>{if(n)try{let o=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:o.pairingTopic})?.setError(Vm.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Rr("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),Ee(this,"deletePendingSessionRequest",async(r,n,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),o&&(this.sessionRequestQueue.state=Bu.idle,this.client.events.emit("session_request_expire",{id:r}))}),Ee(this,"deletePendingAuthRequest",async(r,n,o=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)])}),Ee(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),Ee(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,pn(Zo.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),Ee(this,"setAuthRequest",async(r,n)=>{let{request:o,pairingTopic:s,transportType:i=Vr.relay}=n;this.client.core.expirer.set(r,o.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:o.authPayload,requester:o.requester,expiryTimestamp:o.expiryTimestamp,id:r,pairingTopic:s,verifyContext:o.verifyContext,transportType:i})}),Ee(this,"setPendingSessionRequest",async r=>{let{id:n,topic:o,params:s,verifyContext:i}=r,a=s.request.expiryTimestamp||pn(Zo.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:o,params:s,verifyContext:i})}),Ee(this,"sendRequest",async r=>{let{topic:n,method:o,params:s,expiry:i,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:d,tvf:f,publishOpts:p={}}=r,h=dr(o,s,c),y,w=!!d;try{let T=w?Np:Ts;y=await this.client.core.crypto.encode(n,h,{encoding:T})}catch(T){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),T}let x;if(NGe.includes(o)){let T=Ki(JSON.stringify(h)),E=Ki(y);x=await this.client.core.verify.register({id:E,decryptedId:T})}let v=lr(lr({},Zo[o].req),p);if(v.attestation=x,i&&(v.ttl=i),a&&(v.id=a),this.client.core.history.set(n,h),w){let T=M5(d,n,y);await global.Linking.openURL(T,this.client.name)}else v.tvf=Go(lr({},f),{correlationId:h.id}),u?(v.internal=Go(lr({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,y,v)):this.client.core.relayer.publish(n,y,v).catch(T=>this.client.logger.error(T));return h.id}),Ee(this,"sendProposeSession",async r=>{let{proposal:n,publishOpts:o}=r,s=dr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);let i=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:Ts}),a=Ki(JSON.stringify(s)),c=Ki(i),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:i},opts:Go(lr({},o),{publishMethod:"wc_proposeSession",attestation:u})})}),Ee(this,"sendApproveSession",async r=>{let{sessionTopic:n,pairingProposalResponse:o,proposal:s,sessionSettleRequest:i,publishOpts:a}=r,c=bo(s.id,o),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Ts}),d=dr("wc_sessionSettle",i,a?.id),f=await this.client.core.crypto.encode(n,d,{encoding:Ts});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:Go(lr({},a),{publishMethod:"wc_approveSession"})})}),Ee(this,"sendResult",async r=>{let{id:n,topic:o,result:s,throwOnFailedPublish:i,encodeOpts:a,appLink:c}=r,u=bo(n,s),d,f=c&&typeof(global==null?void 0:global.Linking)<"u";try{let y=f?Np:Ts;d=await this.client.core.crypto.encode(o,u,Go(lr({},a||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${o} failed`),y}let p,h;try{p=await this.client.core.history.get(o,n);let y=p.request;try{h=this.getTVFParams(n,y.params,s)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${o}, ${n}) failed`),y}if(f){let y=M5(c,o,d);await global.Linking.openURL(y,this.client.name)}else{let y=p.request.method,w=Zo[y].res;w.tvf=Go(lr({},h),{correlationId:n}),i?(w.internal=Go(lr({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(o,d,w)):this.client.core.relayer.publish(o,d,w).catch(x=>this.client.logger.error(x))}await this.client.core.history.resolve(u)}),Ee(this,"sendError",async r=>{let{id:n,topic:o,error:s,encodeOpts:i,rpcOpts:a,appLink:c}=r,u=la(n,s),d,f=c&&typeof(global==null?void 0:global.Linking)<"u";try{let h=f?Np:Ts;d=await this.client.core.crypto.encode(o,u,Go(lr({},i||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${o} failed`),h}let p;try{p=await this.client.core.history.get(o,n)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${o}, ${n}) failed`),h}if(f){let h=M5(c,o,d);await global.Linking.openURL(h,this.client.name)}else{let h=p.request.method,y=a||Zo[h].res;this.client.core.relayer.publish(o,d,y)}await this.client.core.history.resolve(u)}),Ee(this,"cleanup",async()=>{let r=[],n=[];this.client.session.getAll().forEach(o=>{let s=!1;ka(o.expiry)&&(s=!0),this.client.core.crypto.keychain.has(o.topic)||(s=!0),s&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{ka(o.expiryTimestamp)&&n.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession({topic:o})),...n.map(o=>this.deleteProposal(o))])}),Ee(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),Ee(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),Ee(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Bu.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Bu.active;let r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Bu.idle}),Ee(this,"processRequest",async r=>{let{topic:n,payload:o,attestation:s,transportType:i,encryptedId:a}=r,c=o.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:o,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,o);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,o);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,o);case"wc_sessionPing":return await this.onSessionPingRequest(n,o);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,o);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(n,o);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),Ee(this,"onRelayEventResponse",async r=>{let{topic:n,payload:o,transportType:s}=r,i=(await this.client.core.history.get(n,o.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(n,o,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,o);case"wc_sessionExtend":return this.onSessionExtendResponse(n,o);case"wc_sessionPing":return this.onSessionPingResponse(n,o);case"wc_sessionRequest":return this.onSessionRequestResponse(n,o);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,o);default:return this.client.logger.info(`Unsupported response method ${i}`)}}),Ee(this,"onRelayEventUnknownPayload",r=>{let{topic:n}=r,{message:o}=Ie("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)}),Ee(this,"shouldIgnorePairingRequest",r=>{let{topic:n,requestMethod:o}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(o)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),Ee(this,"onSessionProposeRequest",async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i}=r,{params:a,id:c}=o;try{let u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Nu.proposal_listener_not_found)),this.isValidConnect(lr({},o.params));let d=a.expiryTimestamp||pn(Zo.wc_sessionPropose.req.ttl),f=lr({id:c,pairingTopic:n,expiryTimestamp:d,attestation:s,encryptedId:i},a);await this.setProposal(c,f);let p=await this.getVerifyContext({attestationId:s,hash:Ki(JSON.stringify(o)),encryptedId:i,metadata:f.proposer.metadata});u?.addTrace(Cl.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:p})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Zo.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),Ee(this,"onSessionProposeResponse",async(r,n,o)=>{let{id:s}=n;if(Jr(n)){let{result:i}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});let a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});let c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});let u=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let d=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:d,pairingTopic:r,proposalId:s,publicKey:c});let f=await this.client.core.relayer.subscribe(d,{transportType:o});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(Ir(n)){await this.deleteProposal(s);let i=cr("session_connect",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners, 954`);this.events.emit(i,{error:n.error})}}),Ee(this,"onSessionSettleRequest",async(r,n)=>{let{id:o,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:i,controller:a,expiry:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=n.params,y=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!y)return this.client.logger.error(`Pending session not found for topic ${r}`);let w=this.client.proposal.get(y.proposalId),x=Go(lr(lr(lr({topic:r,relay:i,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),f&&{scopedProperties:f}),p&&{sessionConfig:p}),{transportType:Vr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(x.topic,x),await this.setExpiry(x.topic,x.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:x.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(x),await this.sendResult({id:n.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:x}),this.events.emit(cr("session_connect",y.proposalId),{session:x})}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"onSessionSettleResponse",async(r,n)=>{let{id:o}=n;Jr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(cr("session_approve",o),{})):Ir(n)&&(await this.client.session.delete(r,Rr("USER_DISCONNECTED")),this.events.emit(cr("session_approve",o),{error:n.error}))}),Ee(this,"onSessionUpdateRequest",async(r,n)=>{let{params:o,id:s}=n;try{let i=`${r}_session_update`,a=$m.get(i);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Rr("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(lr({topic:r},o));try{$m.set(i,s),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw $m.delete(i),c}this.client.events.emit("session_update",{id:s,topic:r,params:o})}catch(i){await this.sendError({id:s,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3){let{id:o}=n,s=cr("session_update",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_update",o),{}):Ir(n)&&this.events.emit(cr("session_update",o),{error:n.error})}),Ee(this,"onSessionExtendRequest",async(r,n)=>{let{id:o}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,pn(lx)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}}),Ee(this,"onSessionExtendResponse",(r,n)=>{let{id:o}=n,s=cr("session_extend",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_extend",o),{}):Ir(n)&&this.events.emit(cr("session_extend",o),{error:n.error})}),Ee(this,"onSessionPingRequest",async(r,n)=>{let{id:o}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}}),Ee(this,"onSessionPingResponse",(r,n)=>{let{id:o}=n,s=cr("session_ping",o);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Jr(n)?this.events.emit(cr("session_ping",o),{}):Ir(n)&&this.events.emit(cr("session_ping",o),{error:n.error})},500)}),Ee(this,"onSessionDeleteRequest",async(r,n)=>{let{id:o}=n;try{await this.isValidDisconnect({topic:r,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Rr("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:o})}catch(s){this.client.logger.error(s)}}),Ee(this,"onSessionRequest",async r=>{var n,o,s;let{topic:i,payload:a,attestation:c,encryptedId:u,transportType:d}=r,{id:f,params:p}=a;try{await this.isValidRequest(lr({topic:i},p));let h=this.client.session.get(i),y=await this.getVerifyContext({attestationId:c,hash:Ki(JSON.stringify(dr("wc_sessionRequest",p,f))),encryptedId:u,metadata:h.peer.metadata,transportType:d}),w={id:f,topic:i,params:p,verifyContext:y};await this.setPendingSessionRequest(w),d===Vr.link_mode&&(n=h.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((o=h.peer.metadata.redirect)==null?void 0:o.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:i,error:h}),this.client.logger.error(h)}}),Ee(this,"onSessionRequestResponse",(r,n)=>{let{id:o}=n,s=cr("session_request",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(cr("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(cr("session_request",o),{error:n.error})}),Ee(this,"onSessionEventRequest",async(r,n)=>{let{id:o,params:s}=n;try{let i=`${r}_session_event_${s.event.name}`,a=$m.get(i);if(a&&this.isRequestOutOfSync(a,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit(lr({topic:r},s)),this.client.events.emit("session_event",{id:o,topic:r,params:s}),$m.set(i,o)}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}}),Ee(this,"onSessionAuthenticateResponse",(r,n)=>{let{id:o}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Jr(n)?this.events.emit(cr("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(cr("session_request",o),{error:n.error})}),Ee(this,"onSessionAuthenticateRequest",async r=>{var n;let{topic:o,payload:s,attestation:i,encryptedId:a,transportType:c}=r;try{let{requester:u,authPayload:d,expiryTimestamp:f}=s.params,p=await this.getVerifyContext({attestationId:i,hash:Ki(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:o,id:s.id,authPayload:d,verifyContext:p,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:o,transportType:c}),c===Vr.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:o,params:s.params,id:s.id,verifyContext:p})}catch(u){this.client.logger.error(u);let d=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:vl,receiverPublicKey:d,senderPublicKey:f};await this.sendError({id:s.id,topic:o,error:u,encodeOpts:h,rpcOpts:Zo.wc_sessionAuthenticate.autoReject,appLink:p})}}),Ee(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),Ee(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bu.idle,this.processSessionRequestQueue()},(0,Nt.toMiliseconds)(this.requestQueueDelay))}),Ee(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{let o=this.client.core.history.pending;o.length>0&&o.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(cr("session_request",s.request.id),{error:n})})}),Ee(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Bu.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),Ee(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Bu.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),Ee(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:dr("wc_sessionPropose",Go(lr({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),Ee(this,"isValidConnect",async r=>{if(!_s(r)){let{message:u}=Ie("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:s,sessionProperties:i,scopedProperties:a,relays:c}=r;if(Ln(n)||await this.isValidPairingTopic(n),!Qge(c,!0)){let{message:u}=Ie("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(o&&!Ln(o)&&xc(o)!==0){let u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(o,"requiredNamespaces")}if(s&&!Ln(s)&&xc(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),i&&!Ln(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!Ln(a)){this.validateSessionProps(a,"scopedProperties");let u=Object.keys(o||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(d=>u.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),Ee(this,"validateNamespaces",(r,n)=>{let o=Jge(r,"connect()",n);if(o)throw new Error(o.message)}),Ee(this,"isValidApprove",async r=>{if(!_s(r))throw new Error(Ie("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:o,relayProtocol:s,sessionProperties:i,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let c=this.client.proposal.get(n),u=X7(o,"approve()");if(u)throw new Error(u.message);let d=Iz(c.requiredNamespaces,o,"approve()");if(d)throw new Error(d.message);if(!An(s,!0)){let{message:f}=Ie("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(i&&!Ln(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!Ln(a)){this.validateSessionProps(a,"scopedProperties");let f=new Set(Object.keys(o));if(!Object.keys(a).every(p=>f.has(p.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),Ee(this,"isValidReject",async r=>{if(!_s(r)){let{message:s}=Ie("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:o}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!eye(o)){let{message:s}=Ie("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(s)}}),Ee(this,"isValidSessionSettleRequest",r=>{if(!_s(r)){let{message:u}=Ie("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}let{relay:n,controller:o,namespaces:s,expiry:i}=r;if(!Cz(n)){let{message:u}=Ie("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}let a=Gge(o,"onSessionSettleRequest()");if(a)throw new Error(a.message);let c=X7(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ka(i)){let{message:u}=Ie("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),Ee(this,"isValidUpdate",async r=>{if(!_s(r)){let{message:c}=Ie("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}let{topic:n,namespaces:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),i=X7(o,"update()");if(i)throw new Error(i.message);let a=Iz(s.requiredNamespaces,o,"update()");if(a)throw new Error(a.message)}),Ee(this,"isValidExtend",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),Ee(this,"isValidRequest",async r=>{if(!_s(r)){let{message:c}=Ie("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}let{topic:n,request:o,chainId:s,expiry:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!Sz(a,s)){let{message:c}=Ie("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!tye(o)){let{message:c}=Ie("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(c)}if(!oye(a,s,o.method)){let{message:c}=Ie("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(c)}this.validateRequestExpiry(i)}),Ee(this,"isValidRespond",async r=>{var n;if(!_s(r)){let{message:a}=Ie("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}let{topic:o,response:s}=r;try{await this.isValidSessionTopic(o)}catch(a){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),a}if(!rye(s)){let{message:a}=Ie("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}let i=this.client.pendingRequest.get(s.id);if(i.topic!==o){let{message:a}=Ie("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${i.topic}, received topic: ${o}`);throw new Error(a)}}),Ee(this,"isValidPing",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),Ee(this,"isValidEmit",async r=>{if(!_s(r)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:o,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:i}=this.client.session.get(n);if(!Sz(i,s)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!nye(o)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}if(!sye(i,s,o.name)){let{message:a}=Ie("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}}),Ee(this,"isValidDisconnect",async r=>{if(!_s(r)){let{message:o}=Ie("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),Ee(this,"isValidAuthenticate",r=>{let{chains:n,uri:o,domain:s,nonce:i}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!An(o,!1))throw new Error("uri is required parameter");if(!An(s,!1))throw new Error("domain is required parameter");if(!An(i,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>bl(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:a}=bl(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),Ee(this,"getVerifyContext",async r=>{let{attestationId:n,hash:o,encryptedId:s,metadata:i,transportType:a}=r,c={verified:{verifyUrl:i.verifyUrl||ax,validation:"UNKNOWN",origin:i.url||""}};try{if(a===Vr.link_mode){let d=this.getAppLinkIfEnabled(i,a);return c.verified.validation=d&&new URL(d).origin===new URL(i.url).origin?"VALID":"INVALID",c}let u=await this.client.core.verify.resolve({attestationId:n,hash:o,encryptedId:s,verifyUrl:i.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),Ee(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((o,s)=>{if(o==null){let{message:i}=Ie("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${o} for key ${Object.keys(r)[s]}`);throw new Error(i)}})}),Ee(this,"getPendingAuthRequest",r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),Ee(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let o=0,s=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(o++>=s)break;this.recentlyDeletedMap.delete(i)}}}),Ee(this,"checkRecentlyDeleted",r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:o}=Ie("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(o)}}),Ee(this,"isLinkModeEnabled",(r,n)=>{var o,s,i,a,c,u,d,f,p;return!r||n!==Vr.link_mode?!1:((s=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:s.linkMode)===!0&&((a=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((d=r?.redirect)==null?void 0:d.universal)!==void 0&&((f=r?.redirect)==null?void 0:f.universal)!==""&&((p=r?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),Ee(this,"getAppLinkIfEnabled",(r,n)=>{var o;return this.isLinkModeEnabled(r,n)?(o=r?.redirect)==null?void 0:o.universal:void 0}),Ee(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;let n=ez(r,"topic")||"",o=decodeURIComponent(ez(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:Vr.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:o,sessionExists:s})}),Ee(this,"registerLinkModeListeners",async()=>{var r;if(R5()||_p()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){let n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);let o=await n.getInitialURL();o&&setTimeout(()=>{this.handleLinkModeMessage({url:o})},50)}}}),Ee(this,"getTVFApproveParams",r=>{try{let n=vz(r.namespaces),o=zge(r.namespaces),s=Vge(r.namespaces),i=r.sessionProperties,a=r.scopedProperties;return{approvedChains:n,approvedMethods:o,approvedEvents:s,sessionProperties:i,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}}),Ee(this,"getTVFParams",(r,n,o)=>{var s,i,a;if(!((s=n.request)!=null&&s.method))return{};let c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{let u=this.extractTxHashesFromResult(n.request,o);c.txHashes=u,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(i=n.request.params)==null?void 0:i[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),Ee(this,"isValidContractData",r=>{var n;if(!r)return!1;try{let o=r?.data||((n=r?.[0])==null?void 0:n.data);if(!o.startsWith("0x"))return!1;let s=o.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),Ee(this,"extractTxHashesFromResult",(r,n)=>{var o;try{if(!n)return[];let s=r.method,i=_Ge[s];if(s==="sui_signTransaction")return[G1e(n.transactionBytes)];if(s==="near_signTransaction")return[sz(n)];if(s==="near_signTransactions")return n.map(c=>sz(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(o=n.tx_json)==null?void 0:o.hash];if(s==="polkadot_signTransaction")return[lye({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return El(n)?n.map(c=>iz(c)):[iz(n)];if(s==="cosmos_signDirect")return[Y1e(n)];if(s==="wallet_sendCalls")return J1e(n);if(typeof n=="string")return[n];let a=n[i.key];if(El(a))return s==="solana_signAllTransactions"?a.map(c=>Z1e(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{let t=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(t);for(let[n,o]of Object.entries(r))for(let s of o)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:t}=Ie("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){let{topic:r,message:n,attestation:o,transportType:s}=t,{publicKey:i}=this.client.auth.authKeys.keys.includes(oP)?this.client.auth.authKeys.get(oP):{responseTopic:void 0,publicKey:void 0};try{let a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i,encoding:s===Vr.link_mode?Np:Ts});Hc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:o,transportType:s,encryptedId:Ki(n)})):ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(La.expired,async t=>{let{topic:r,id:n}=z7(t.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Ie("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Ie("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(zm.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(zm.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!An(t,!1)){let{message:r}=Ie("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.core.pairing.pairings.get(t).expiry)){let{message:r}=Ie("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!An(t,!1)){let{message:r}=Ie("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});let{message:r}=Ie("EXPIRED",`session topic: ${t}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(t)){let{message:r}=Ie("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(An(t,!1)){let{message:r}=Ie("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{let{message:r}=Ie("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!Xge(t)){let{message:r}=Ie("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){let{message:r}=Ie("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(ka(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);let{message:r}=Ie("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}validateRequestExpiry(t){if(t&&!iye(t,lV)){let{message:r}=Ie("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${lV.min} and ${lV.max}`);throw new Error(r)}}},pV=class extends Ou{constructor(t,r){super(t,r,SGe,vV),this.core=t,this.logger=r}},hV=class extends Ou{constructor(t,r){super(t,r,IGe,vV),this.core=t,this.logger=r}},mV=class extends Ou{constructor(t,r){super(t,r,PGe,vV,n=>n.id),this.core=t,this.logger=r}},gV=class extends Ou{constructor(t,r){super(t,r,BGe,iP,()=>oP),this.core=t,this.logger=r}},yV=class extends Ou{constructor(t,r){super(t,r,kGe,iP),this.core=t,this.logger=r}},wV=class extends Ou{constructor(t,r){super(t,r,UGe,iP,n=>n.id),this.core=t,this.logger=r}},FGe=Object.defineProperty,zGe=(e,t,r)=>t in e?FGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,uV=(e,t,r)=>zGe(e,typeof t!="symbol"?t+"":t,r),bV=class{constructor(t,r){this.core=t,this.logger=r,uV(this,"authKeys"),uV(this,"pairingTopics"),uV(this,"requests"),this.authKeys=new gV(this.core,this.logger),this.pairingTopics=new yV(this.core,this.logger),this.requests=new wV(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},VGe=Object.defineProperty,jGe=(e,t,r)=>t in e?VGe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,jt=(e,t,r)=>jGe(e,typeof t!="symbol"?t+"":t,r),xV=class e extends $_{constructor(t){super(t),jt(this,"protocol",t2e),jt(this,"version",r2e),jt(this,"name",cV.name),jt(this,"metadata"),jt(this,"core"),jt(this,"logger"),jt(this,"events",new sP.EventEmitter),jt(this,"engine"),jt(this,"session"),jt(this,"proposal"),jt(this,"pendingRequest"),jt(this,"auth"),jt(this,"signConfig"),jt(this,"on",(n,o)=>this.events.on(n,o)),jt(this,"once",(n,o)=>this.events.once(n,o)),jt(this,"off",(n,o)=>this.events.off(n,o)),jt(this,"removeListener",(n,o)=>this.events.removeListener(n,o)),jt(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),jt(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"update",async n=>{try{return await this.engine.update(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"request",async n=>{try{return await this.engine.request(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"find",n=>{try{return this.engine.find(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),jt(this,"authenticate",async(n,o)=>{try{return await this.engine.authenticate(n,o)}catch(s){throw this.logger.error(s.message),s}}),jt(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}}),jt(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}}),this.name=t?.name||cV.name,this.metadata=T1e(t?.metadata),this.signConfig=t?.signConfig;let r=ox({logger:t?.logger||cV.logger,name:this.name});this.logger=r,this.core=t?.core||new Yye(t),this.session=new hV(this.core,this.logger),this.proposal=new pV(this.core,this.logger),this.pendingRequest=new mV(this.core,this.logger),this.engine=new fV(this),this.auth=new bV(this.core,this.logger)}static async init(t){let r=new e(t);return await r.initialize(),r}get context(){return sr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}},o2e=xV});function kV(e){return e==null||typeof e!="object"&&typeof e!="function"}function I2e(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function T2e(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}function UV(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lYe(e,t){return dx(e,void 0,e,new Map,t)}function dx(e,t,r,n=new Map,o=void 0){let s=o?.(e,t,r,n);if(s!=null)return s;if(kV(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){let i=new Array(e.length);n.set(e,i);for(let a=0;a{let i=t?.(r,n,o,s);if(i!=null)return i;if(typeof e=="object")switch(Object.prototype.toString.call(e)){case P2e:case _2e:case N2e:{let a=new e.constructor(e?.valueOf());return Oy(a,e),a}case R2e:{let a={};return Oy(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}})}function i2e(e){return dYe(e)}function a2e(e){return e!==null&&typeof e=="object"&&T2e(e)==="[object Arguments]"}function c2e(e){return typeof e=="object"&&e!==null}function fYe(){}function pYe(e){return UV(e)}function hYe(e){if(typeof e!="object"||e==null)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!=="[object Object]"){let r=e[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable?!1:e.toString()===`[object ${r}]`}let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function mYe(e){if(kV(e))return e;if(Array.isArray(e)||UV(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e),r=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new r(e);if(e instanceof RegExp){let n=new r(e);return n.lastIndex=e.lastIndex,n}if(e instanceof DataView)return new r(e.buffer.slice(0));if(e instanceof Error){let n=new r(e.message);return n.stack=e.stack,n.name=e.name,n.cause=e.cause,n}if(typeof File<"u"&&e instanceof File)return new r([e],e.name,{type:e.type,lastModified:e.lastModified});if(typeof e=="object"){let n=Object.create(t);return Object.assign(n,e)}return e}function gYe(e,...t){let r=t.slice(0,-1),n=t[t.length-1],o=e;for(let s=0;s`${t.split(":")[0]}:${t.split(":")[1]}`)}function PYe(e,t){let r=Object.keys(t.namespaces).filter(o=>o.includes(e));if(!r.length)return[];let n=[];return r.forEach(o=>{let s=t.namespaces[o].accounts;n.push(...s)}),n}function f2e(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>{var n,o;return((n=r?.chains)==null?void 0:n.length)&&((o=r?.chains)==null?void 0:o.length)>0}))}function lP(e={},t={}){let r=f2e(p2e(e)),n=f2e(p2e(t));return yYe(r,n)}function p2e(e){var t,r,n,o,s;let i={};if(!xc(e))return i;for(let[a,c]of Object.entries(e)){let u=H5(a)?[a]:c.chains,d=c.methods||[],f=c.events||[],p=c.rpcMap||{},h=Ny(a);i[h]=TYe(cP(cP({},i[h]),c),{chains:ml(u,(t=i[h])==null?void 0:t.chains),methods:ml(d,(r=i[h])==null?void 0:r.methods),events:ml(f,(n=i[h])==null?void 0:n.events)}),(xc(p)||xc(((o=i[h])==null?void 0:o.rpcMap)||{}))&&(i[h].rpcMap=cP(cP({},p),(s=i[h])==null?void 0:s.rpcMap))}return i}function h2e(e){return e.includes(":")?e.split(":")[2]:e}function m2e(e){let t={};for(let[r,n]of Object.entries(e)){let o=n.methods||[],s=n.events||[],i=n.accounts||[],a=H5(r)?[r]:n.chains?n.chains:D2e(n.accounts);t[r]={chains:a,methods:o,events:s,accounts:i}}return t}function EV(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function NYe(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}async function ZYe(e,t){let r=bl(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,o=await Promise.allSettled(n.map(f=>GYe(r.reference,f,t))),s=o.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);o.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));let i=!s.length||s.some(f=>!f),a=s.every(f=>f?.status==="0x1"),c=s.every(f=>f?.status==="0x0"),u=s.some(f=>f?.status==="0x0"),d;return i?d=100:a?d=200:c?d=500:u&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function GYe(e,t,r){return await r(parseInt(e)).request(dr("eth_getTransactionReceipt",[t]))}async function YYe({sendCalls:e,storage:t}){let r=await t.getItem(fx);await t.setItem(fx,KYe(WYe({},r),{[e.result.id]:{request:e.request,result:e.result,expiry:pn(vYe)}}))}async function JYe({resultId:e,storage:t}){let r=await t.getItem(fx);if(r){delete r[e],await t.setItem(fx,r);for(let n in r)ka(r[n].expiry)&&delete r[n];await t.setItem(fx,r)}}async function QYe({resultId:e,storage:t}){let r=await t.getItem(fx),n=r?.[e];if(n&&!ka(n.expiry))return n;await JYe({resultId:e,storage:t})}var S2e,qGe,_2e,P2e,N2e,R2e,WGe,KGe,ZGe,GGe,YGe,JGe,QGe,XGe,eYe,tYe,rYe,nYe,oYe,sYe,iYe,aYe,cYe,l2e,wYe,bYe,O2e,aP,B2e,k2e,xYe,fx,vYe,DV,EYe,AYe,CYe,u2e,SYe,IYe,d2e,cP,TYe,L2e,px,AV,RYe,g2e,OYe,BYe,y2e,w2e,b2e,kYe,UYe,CV,x2e,DYe,LYe,MYe,HYe,$Ye,SV,PV,FYe,zYe,VYe,v2e,jYe,qYe,E2e,WYe,KYe,XYe,eJe,tJe,A2e,rJe,nJe,NV,IV,TV,Ry,RV,oJe,sJe,ux,OV,iJe,aJe,cJe,C2e,lJe,uJe,BV,W5,uP,Ma,dP,M2e=b(()=>{l();s2e();eP();$c();cw();rI();S2e=Ht(ks(),1);qGe="[object RegExp]",_2e="[object String]",P2e="[object Number]",N2e="[object Boolean]",R2e="[object Arguments]",WGe="[object Symbol]",KGe="[object Date]",ZGe="[object Map]",GGe="[object Set]",YGe="[object Array]",JGe="[object ArrayBuffer]",QGe="[object Object]",XGe="[object DataView]",eYe="[object Uint8Array]",tYe="[object Uint8ClampedArray]",rYe="[object Uint16Array]",nYe="[object Uint32Array]",oYe="[object Int8Array]",sYe="[object Int16Array]",iYe="[object Int32Array]",aYe="[object Float32Array]",cYe="[object Float64Array]";l2e="error",wYe="wss://relay.walletconnect.org",bYe="wc",O2e="universal_provider",aP=`${bYe}@2:${O2e}:`,B2e="https://rpc.walletconnect.org/v1/",k2e="generic",xYe=`${B2e}bundler`,fx="call_status",vYe=86400,DV={DEFAULT_CHAIN_CHANGED:"default_chain_changed"},EYe=Object.defineProperty,AYe=Object.defineProperties,CYe=Object.getOwnPropertyDescriptors,u2e=Object.getOwnPropertySymbols,SYe=Object.prototype.hasOwnProperty,IYe=Object.prototype.propertyIsEnumerable,d2e=(e,t,r)=>t in e?EYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,cP=(e,t)=>{for(var r in t||(t={}))SYe.call(t,r)&&d2e(e,r,t[r]);if(u2e)for(var r of u2e(t))IYe.call(t,r)&&d2e(e,r,t[r]);return e},TYe=(e,t)=>AYe(e,CYe(t));L2e={},px=e=>L2e[e],AV=(e,t)=>{L2e[e]=t},RYe=Object.defineProperty,g2e=Object.getOwnPropertySymbols,OYe=Object.prototype.hasOwnProperty,BYe=Object.prototype.propertyIsEnumerable,y2e=(e,t,r)=>t in e?RYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,w2e=(e,t)=>{for(var r in t||(t={}))OYe.call(t,r)&&y2e(e,r,t[r]);if(g2e)for(var r of g2e(t))BYe.call(t,r)&&y2e(e,r,t[r]);return e},b2e="eip155",kYe=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],UYe=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,CV=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,x2e=e=>Object.keys(e).filter(t=>kYe.includes(t)).reduce((t,r)=>(t[r]=DYe(e[r]),t),{}),DYe=e=>typeof e=="string"&&NYe(e)?JSON.parse(e):e,LYe=(e,t,r)=>{let{sessionProperties:n={},scopedProperties:o={}}=e,s={};if(!xc(o)&&!xc(n))return;let i=x2e(n);for(let a of r){let c=UYe(a);if(!c)continue;s[CV(c)]=i;let u=o?.[`${b2e}:${c}`];if(u){let d=u?.[`${b2e}:${c}:${t}`];s[CV(c)]=w2e(w2e({},s[CV(c)]),x2e(d||u))}}for(let[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0},MYe=Object.defineProperty,HYe=(e,t,r)=>t in e?MYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$Ye=(e,t,r)=>HYe(e,typeof t!="symbol"?t+"":t,r),PV=class e{constructor(t){$Ye(this,"storage"),this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,r){return await this.storage.setItem(t,r)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return SV||(SV=new e(t)),SV}},FYe=Object.defineProperty,zYe=Object.defineProperties,VYe=Object.getOwnPropertyDescriptors,v2e=Object.getOwnPropertySymbols,jYe=Object.prototype.hasOwnProperty,qYe=Object.prototype.propertyIsEnumerable,E2e=(e,t,r)=>t in e?FYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,WYe=(e,t)=>{for(var r in t||(t={}))jYe.call(t,r)&&E2e(e,r,t[r]);if(v2e)for(var r of v2e(t))qYe.call(t,r)&&E2e(e,r,t[r]);return e},KYe=(e,t)=>zYe(e,VYe(t));XYe=Object.defineProperty,eJe=Object.defineProperties,tJe=Object.getOwnPropertyDescriptors,A2e=Object.getOwnPropertySymbols,rJe=Object.prototype.hasOwnProperty,nJe=Object.prototype.propertyIsEnumerable,NV=(e,t,r)=>t in e?XYe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,IV=(e,t)=>{for(var r in t||(t={}))rJe.call(t,r)&&NV(e,r,t[r]);if(A2e)for(var r of A2e(t))nJe.call(t,r)&&NV(e,r,t[r]);return e},TV=(e,t)=>eJe(e,tJe(t)),Ry=(e,t,r)=>NV(e,typeof t!="symbol"?t+"":t,r),RV=class{constructor(t){Ry(this,"name","eip155"),Ry(this,"client"),Ry(this,"chainId"),Ry(this,"namespace"),Ry(this,"httpProviders"),Ry(this,"events"),Ry(this,"storage"),this.namespace=t.namespace,this.events=px("events"),this.client=px("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=PV.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r);let n=this.chainId;this.chainId=parseInt(t),this.events.emit(DV.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){let n=r||U2e(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,px("disableProviderPing")))}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProviders(){let t={};return this.namespace.chains.forEach(r=>{var n;let o=parseInt(_Ye(r));t[o]=this.createHttpProvider(o,(n=this.namespace.rpcMap)==null?void 0:n[r])}),t}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(t){let r=t||this.chainId;return this.httpProviders[r]||(this.httpProviders=TV(IV({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(t){var r,n;let o=t.request.params?(r=t.request.params[0])==null?void 0:r.chainId:"0x0";o=o.startsWith("0x")?o:`0x${o}`;let s=parseInt(o,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:o}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){var r,n,o,s,i;let a=(n=(r=t.request)==null?void 0:r.params)==null?void 0:n[0],c=((s=(o=t.request)==null?void 0:o.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");let u=this.client.session.get(t.topic),d=((i=u?.sessionProperties)==null?void 0:i.capabilities)||{},f=c.length>0?c.join(","):`0x${this.chainId.toString(16)}`,p=`${a}${f}`,h=d?.[p];if(h)return h;let y;try{y=LYe(u,a,c)}catch(x){console.warn("Failed to extract capabilities from session",x)}if(y)return y;let w=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:TV(IV({},u.sessionProperties||{}),{capabilities:TV(IV({},d||{}),{[p]:w})})})}catch(x){console.warn("Failed to update session with capabilities",x)}return w}async getCallStatus(t){var r,n,o;let s=this.client.session.get(t.topic),i=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(i){let u=this.getBundlerUrl(t.chainId,i);try{return await this.getUserOperationReceipt(u,t)}catch(d){console.warn("Failed to fetch call status from bundler",d,u)}}let a=(n=s.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,t)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}let c=await QYe({resultId:(o=t.request.params)==null?void 0:o[0],storage:this.storage});if(c)try{return await ZYe(c,this.getHttpProvider.bind(this))}catch(u){console.warn("Failed to fetch call status from stored send calls",u,c)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,r){var n;let o=new URL(t),s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dr("eth_getUserOperationReceipt",[(n=r.request.params)==null?void 0:n[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(t,r){return`${xYe}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${r}`}async sendCalls(t){var r,n,o;let s=await this.client.request(t),i=(r=t.request.params)==null?void 0:r[0],a=s?.id,c=s?.capabilities||{},u=(n=c?.caip345)==null?void 0:n.caip2,d=(o=c?.caip345)==null?void 0:o.transactionHashes;return!a||!u||!(d!=null&&d.length)||await YYe({sendCalls:{request:i,result:s},storage:this.storage}),s}},oJe=Object.defineProperty,sJe=(e,t,r)=>t in e?oJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ux=(e,t,r)=>sJe(e,typeof t!="symbol"?t+"":t,r),OV=class{constructor(t){ux(this,"name",k2e),ux(this,"client"),ux(this,"httpProviders"),ux(this,"events"),ux(this,"namespace"),ux(this,"chainId"),this.namespace=t.namespace,this.events=px("events"),this.client=px("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r);let n=this.chainId;this.chainId=t,this.events.emit(DV.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return bl(t).namespace}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var t,r;let n={};return(r=(t=this.namespace)==null?void 0:t.accounts)==null||r.forEach(o=>{var s,i;let a=bl(o),c=(i=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:i[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(o,c)}),n}getHttpProvider(t){let r=bl(t).reference,n=this.httpProviders[r];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return n}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProvider(t,r){let n=r||U2e(t,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,px("disableProviderPing")))}},iJe=Object.defineProperty,aJe=Object.defineProperties,cJe=Object.getOwnPropertyDescriptors,C2e=Object.getOwnPropertySymbols,lJe=Object.prototype.hasOwnProperty,uJe=Object.prototype.propertyIsEnumerable,BV=(e,t,r)=>t in e?iJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,W5=(e,t)=>{for(var r in t||(t={}))lJe.call(t,r)&&BV(e,r,t[r]);if(C2e)for(var r of C2e(t))uJe.call(t,r)&&BV(e,r,t[r]);return e},uP=(e,t)=>aJe(e,cJe(t)),Ma=(e,t,r)=>BV(e,typeof t!="symbol"?t+"":t,r),dP=class e{constructor(t){Ma(this,"client"),Ma(this,"namespaces"),Ma(this,"optionalNamespaces"),Ma(this,"sessionProperties"),Ma(this,"scopedProperties"),Ma(this,"events",new S2e.default),Ma(this,"rpcProviders",{}),Ma(this,"session"),Ma(this,"providerOpts"),Ma(this,"logger"),Ma(this,"uri"),Ma(this,"disableProviderPing",!1),Ma(this,"connectParams");var r,n;this.providerOpts=t,this.logger=ox({logger:(r=t.logger)!=null?r:l2e,name:(n=this.providerOpts.name)!=null?n:O2e}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){let r=new e(t);return await r.initialize(),r}async request(t,r,n){let[o,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(o).request({request:W5({},t),chainId:`${o}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(t,r,n,o){let s=new Date().getTime();this.request(t,n,o).then(i=>r(null,bo(s,i))).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var t;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(t=this.session)==null?void 0:t.topic,reason:Rr("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();let{uri:n,response:o}=await this.client.authenticate(t,r);n&&(this.uri=n,this.events.emit("display_uri",n));let s=await o();if(this.session=s.session,this.session){let i=m2e(this.session.namespaces);this.namespaces=lP(this.namespaces,i),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){var r,n;let{uri:o,approval:s}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(n=this.connectParams)==null?void 0:n.walletPay});o&&(this.uri=o,this.events.emit("display_uri",o));let i=await s();this.session=i;let a=m2e(i.namespaces);return this.namespaces=lP(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;let[n,o]=this.validateChain(t);this.getProvider(n).setDefaultChain(o,r)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");let r=this.client.pairing.getAll();if(!El(r))return;for(let n of r)t.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var t,r;if(this.client=this.providerOpts.client||await o2e.init({core:this.providerOpts.core,logger:this.providerOpts.logger||l2e,relayUrl:this.providerOpts.relayUrl||wYe,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error(n,"Failed to get session"),new Error(`The provided session: ${(r=(t=this.providerOpts)==null?void 0:t.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{let n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");let t=[...new Set(Object.keys(this.session.namespaces).map(r=>Ny(r)))];AV("client",this.client),AV("events",this.events),AV("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;let n=PYe(r,this.session);if(n?.length===0)return;let o=D2e(n),s=lP(this.namespaces,this.optionalNamespaces),i=uP(W5({},s[r]),{accounts:n,chains:o});r==="eip155"?this.rpcProviders[r]=new RV({namespace:i}):this.rpcProviders[r]=new OV({namespace:i})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{var r;let{topic:n}=t;n===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{var r;let{params:n,topic:o}=t;if(o!==((r=this.session)==null?void 0:r.topic))return;let{event:s}=n;if(s.name==="accountsChanged"){let i=s.data;i&&El(i)&&this.events.emit("accountsChanged",i.map(h2e))}else if(s.name==="chainChanged"){let i=n.chainId,a=n.event.data,c=Ny(i),u=EV(i)!==EV(a)?`${c}:${EV(a)}`:i;this.onChainChanged({currentCaipChainId:u})}else this.events.emit(s.name,s.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{var n,o;if(t!==((n=this.session)==null?void 0:n.topic))return;let{namespaces:s}=r,i=(o=this.client)==null?void 0:o.session.get(t);this.session=uP(W5({},i),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{var r;t.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",uP(W5({},Rr("USER_DISCONNECTED")),{data:t.topic})))}),this.on(DV.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged(uP(W5({},t),{internal:!0}))})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[k2e]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{var r;this.getProvider(t).updateNamespace((r=this.session)==null?void 0:r.namespaces[t])})}setNamespaces(t){let{namespaces:r={},optionalNamespaces:n={},sessionProperties:o,scopedProperties:s}=t;this.optionalNamespaces=lP(r,n),this.sessionProperties=o,this.scopedProperties=s}validateChain(t){let[r,n]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(i=>Ny(i)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];let o=Ny(Object.keys(this.namespaces)[0]),s=this.rpcProviders[o].getDefaultChain();return[o,s]}async requestAccounts(){let[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:r,internal:n=!1}){if(!this.namespaces)return;let[o,s]=this.validateChain(t);s&&(this.updateNamespaceChain(o,s),n?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:o,currentCaipChainId:t,previousCaipChainId:r})):this.getProvider(o).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:r,previousCaipChainId:n}){var o,s;try{if(n===r)return;let i=(s=(o=this.session)==null?void 0:o.namespaces[t])==null?void 0:s.accounts;if(!i)return;let a=i.filter(c=>c.includes(`${r}:`)).map(h2e);if(!El(a))return;this.events.emit("accountsChanged",a)}catch(i){this.logger.warn(i,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,r){if(!this.namespaces)return;let n=this.namespaces[t]?t:`${t}:${r}`,o={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=o}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,r){var n;let o=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${aP}/${t}${o}`,r)}async getFromStore(t){var r;let n=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${aP}/${t}${n}`)}async deleteFromStore(t){var r;let n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${aP}/${t}${n}`)}async cleanupStorage(){var t;try{if(((t=this.client)==null?void 0:t.session.length)>0)return;let r=await this.client.core.storage.getKeys();for(let n of r)n.startsWith(aP)&&await this.client.core.storage.removeItem(n)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}});var fP,H2e=b(()=>{l();fP={interpolate(e,t,r){if(e.length!==2||t.length!==2)throw new Error("inputRange and outputRange must be an array of length 2");let n=e[0]||0,o=e[1]||0,s=t[0]||0,i=t[1]||0;return ro?i:(i-s)/(o-n)*(r-n)+s}}});var pP,hP,LV,$2e,K5,Gi,Er,F2e,MV,HV=b(()=>{l();pP=globalThis,hP=pP.ShadowRoot&&(pP.ShadyCSS===void 0||pP.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,LV=Symbol(),$2e=new WeakMap,K5=class{constructor(t,r,n){if(this._$cssResult$=!0,n!==LV)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=r}get styleSheet(){let t=this.o,r=this.t;if(hP&&t===void 0){let n=r!==void 0&&r.length===1;n&&(t=$2e.get(r)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&$2e.set(r,t))}return t}toString(){return this.cssText}},Gi=e=>new K5(typeof e=="string"?e:e+"",void 0,LV),Er=(e,...t)=>{let r=e.length===1?e[0]:t.reduce((n,o,s)=>n+(i=>{if(i._$cssResult$===!0)return i.cssText;if(typeof i=="number")return i;throw Error("Value passed to 'css' function must be a 'css' function result: "+i+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[s+1],e[0]);return new K5(r,e,LV)},F2e=(e,t)=>{if(hP)e.adoptedStyleSheets=t.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(let r of t){let n=document.createElement("style"),o=pP.litNonce;o!==void 0&&n.setAttribute("nonce",o),n.textContent=r.cssText,e.appendChild(n)}},MV=hP?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let r="";for(let n of t.cssRules)r+=n.cssText;return Gi(r)})(e):e});var dJe,fJe,pJe,hJe,mJe,gJe,mP,z2e,yJe,wJe,Z5,G5,gP,V2e,Op,Y5=b(()=>{l();HV();HV();({is:dJe,defineProperty:fJe,getOwnPropertyDescriptor:pJe,getOwnPropertyNames:hJe,getOwnPropertySymbols:mJe,getPrototypeOf:gJe}=Object),mP=globalThis,z2e=mP.trustedTypes,yJe=z2e?z2e.emptyScript:"",wJe=mP.reactiveElementPolyfillSupport,Z5=(e,t)=>e,G5={toAttribute(e,t){switch(t){case Boolean:e=e?yJe:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let r=e;switch(t){case Boolean:r=e!==null;break;case Number:r=e===null?null:Number(e);break;case Object:case Array:try{r=JSON.parse(e)}catch{r=null}}return r}},gP=(e,t)=>!dJe(e,t),V2e={attribute:!0,type:String,converter:G5,reflect:!1,useDefault:!1,hasChanged:gP};Symbol.metadata??=Symbol("metadata"),mP.litPropertyMetadata??=new WeakMap;Op=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,r=V2e){if(r.state&&(r.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((r=Object.create(r)).wrapped=!0),this.elementProperties.set(t,r),!r.noAccessor){let n=Symbol(),o=this.getPropertyDescriptor(t,n,r);o!==void 0&&fJe(this.prototype,t,o)}}static getPropertyDescriptor(t,r,n){let{get:o,set:s}=pJe(this.prototype,t)??{get(){return this[r]},set(i){this[r]=i}};return{get:o,set(i){let a=o?.call(this);s?.call(this,i),this.requestUpdate(t,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??V2e}static _$Ei(){if(this.hasOwnProperty(Z5("elementProperties")))return;let t=gJe(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Z5("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Z5("properties"))){let r=this.properties,n=[...hJe(r),...mJe(r)];for(let o of n)this.createProperty(o,r[o])}let t=this[Symbol.metadata];if(t!==null){let r=litPropertyMetadata.get(t);if(r!==void 0)for(let[n,o]of r)this.elementProperties.set(n,o)}this._$Eh=new Map;for(let[r,n]of this.elementProperties){let o=this._$Eu(r,n);o!==void 0&&this._$Eh.set(o,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let r=[];if(Array.isArray(t)){let n=new Set(t.flat(1/0).reverse());for(let o of n)r.unshift(MV(o))}else t!==void 0&&r.push(MV(t));return r}static _$Eu(t,r){let n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,r=this.constructor.elementProperties;for(let n of r.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return F2e(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,r,n){this._$AK(t,n)}_$ET(t,r){let n=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,n);if(o!==void 0&&n.reflect===!0){let s=(n.converter?.toAttribute!==void 0?n.converter:G5).toAttribute(r,n.type);this._$Em=t,s==null?this.removeAttribute(o):this.setAttribute(o,s),this._$Em=null}}_$AK(t,r){let n=this.constructor,o=n._$Eh.get(t);if(o!==void 0&&this._$Em!==o){let s=n.getPropertyOptions(o),i=typeof s.converter=="function"?{fromAttribute:s.converter}:s.converter?.fromAttribute!==void 0?s.converter:G5;this._$Em=o;let a=i.fromAttribute(r,s.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,r,n,o=!1,s){if(t!==void 0){let i=this.constructor;if(o===!1&&(s=this[t]),n??=i.getPropertyOptions(t),!((n.hasChanged??gP)(s,r)||n.useDefault&&n.reflect&&s===this._$Ej?.get(t)&&!this.hasAttribute(i._$Eu(t,n))))return;this.C(t,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,r,{useDefault:n,reflect:o,wrapped:s},i){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,i??r??this[t]),s!==!0||i!==void 0)||(this._$AL.has(t)||(this.hasUpdated||n||(r=void 0),this._$AL.set(t,r)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}let t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[o,s]of this._$Ep)this[o]=s;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[o,s]of n){let{wrapped:i}=s,a=this[o];i!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,s,a)}}let t=!1,r=this._$AL;try{t=this.shouldUpdate(r),t?(this.willUpdate(r),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(r)):this._$EM()}catch(n){throw t=!1,this._$EM(),n}t&&this._$AE(r)}willUpdate(t){}_$AE(t){this._$EO?.forEach(r=>r.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(r=>this._$ET(r,this[r])),this._$EM()}updated(t){}firstUpdated(t){}};Op.elementStyles=[],Op.shadowRootOptions={mode:"open"},Op[Z5("elementProperties")]=new Map,Op[Z5("finalized")]=new Map,wJe?.({ReactiveElement:Op}),(mP.reactiveElementVersions??=[]).push("2.1.2")});function ewe(e,t){if(!jV(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return q2e!==void 0?q2e.createHTML(t):t}function Dy(e,t,r=e,n){if(t===kp)return t;let o=n!==void 0?r._$Co?.[n]:r._$Cl,s=X5(t)?void 0:t._$litDirective$;return o?.constructor!==s&&(o?._$AO?.(!1),s===void 0?o=void 0:(o=new s(e),o._$AT(e,r,n)),n!==void 0?(r._$Co??=[])[n]=o:r._$Cl=o),o!==void 0&&(t=Dy(e,o._$AS(e,t.values),o,n)),t}var FV,j2e,yP,q2e,zV,Bp,VV,bJe,Uy,Q5,X5,jV,J2e,$V,J5,W2e,K2e,By,Z2e,G2e,Q2e,qV,V,He,X2e,kp,hn,Y2e,ky,twe,ev,wP,hx,Ly,bP,xP,vP,EP,rwe,xJe,nwe,Up=b(()=>{l();FV=globalThis,j2e=e=>e,yP=FV.trustedTypes,q2e=yP?yP.createPolicy("lit-html",{createHTML:e=>e}):void 0,zV="$lit$",Bp=`lit$${Math.random().toFixed(9).slice(2)}$`,VV="?"+Bp,bJe=`<${VV}>`,Uy=document,Q5=()=>Uy.createComment(""),X5=e=>e===null||typeof e!="object"&&typeof e!="function",jV=Array.isArray,J2e=e=>jV(e)||typeof e?.[Symbol.iterator]=="function",$V=`[ \f\r]`,J5=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,W2e=/-->/g,K2e=/>/g,By=RegExp(`>|${$V}(?:([^\\s"'>=/]+)(${$V}*=${$V}*(?:[^ -\f\r"'\`<>=]|("|')|))|$)`,"g"),Z2e=/'/g,G2e=/"/g,Q2e=/^(?:script|style|textarea|title)$/i,qV=e=>(t,...r)=>({_$litType$:e,strings:t,values:r}),V=qV(1),He=qV(2),X2e=qV(3),kp=Symbol.for("lit-noChange"),hn=Symbol.for("lit-nothing"),Y2e=new WeakMap,ky=Uy.createTreeWalker(Uy,129);twe=(e,t)=>{let r=e.length-1,n=[],o,s=t===2?"":t===3?"":"",i=J5;for(let a=0;a"?(i=o??J5,f=-1):d[1]===void 0?f=-2:(f=i.lastIndex-d[2].length,u=d[1],i=d[3]===void 0?By:d[3]==='"'?G2e:Z2e):i===G2e||i===Z2e?i=By:i===W2e||i===K2e?i=J5:(i=By,o=void 0);let h=i===By&&e[a+1].startsWith("/>")?" ":"";s+=i===J5?c+bJe:f>=0?(n.push(u),c.slice(0,f)+zV+c.slice(f)+Bp+h):c+Bp+(f===-2?a:h)}return[ewe(e,s+(e[r]||"")+(t===2?"":t===3?"":"")),n]},ev=class e{constructor({strings:t,_$litType$:r},n){let o;this.parts=[];let s=0,i=0,a=t.length-1,c=this.parts,[u,d]=twe(t,r);if(this.el=e.createElement(u,n),ky.currentNode=this.el.content,r===2||r===3){let f=this.el.content.firstChild;f.replaceWith(...f.childNodes)}for(;(o=ky.nextNode())!==null&&c.length0){o.textContent=yP?yP.emptyScript:"";for(let h=0;h2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=hn}_$AI(t,r=this,n,o){let s=this.strings,i=!1;if(s===void 0)t=Dy(this,t,r,0),i=!X5(t)||t!==this._$AH&&t!==kp,i&&(this._$AH=t);else{let a=t,c,u;for(t=s[0],c=0;c{let n=r?.renderBefore??t,o=n._$litPart$;if(o===void 0){let s=r?.renderBefore??null;n._$litPart$=o=new hx(t.insertBefore(Q5(),s),s,void 0,r??{})}return o._$AI(e),o}});var WV,ie,vJe,owe=b(()=>{l();Y5();Y5();Up();Up();WV=globalThis,ie=class extends Op{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=nwe(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return kp}};ie._$litElement$=!0,ie.finalized=!0,WV.litElementHydrateSupport?.({LitElement:ie});vJe=WV.litElementPolyfillSupport;vJe?.({LitElement:ie});(WV.litElementVersions??=[]).push("4.2.2")});var swe=b(()=>{l();});var he=b(()=>{l();Y5();Up();owe();swe()});var iwe,tv,awe,cwe,EJe,AJe,CJe,SJe,IJe,TJe,AP,KV=b(()=>{l();iwe={black:"#202020",white:"#FFFFFF",white010:"rgba(255, 255, 255, 0.1)",accent010:"rgba(9, 136, 240, 0.1)",accent020:"rgba(9, 136, 240, 0.2)",accent030:"rgba(9, 136, 240, 0.3)",accent040:"rgba(9, 136, 240, 0.4)",accent050:"rgba(9, 136, 240, 0.5)",accent060:"rgba(9, 136, 240, 0.6)",accent070:"rgba(9, 136, 240, 0.7)",accent080:"rgba(9, 136, 240, 0.8)",accent090:"rgba(9, 136, 240, 0.9)",accent100:"rgba(9, 136, 240, 1.0)",accentSecondary010:"rgba(199, 185, 148, 0.1)",accentSecondary020:"rgba(199, 185, 148, 0.2)",accentSecondary030:"rgba(199, 185, 148, 0.3)",accentSecondary040:"rgba(199, 185, 148, 0.4)",accentSecondary050:"rgba(199, 185, 148, 0.5)",accentSecondary060:"rgba(199, 185, 148, 0.6)",accentSecondary070:"rgba(199, 185, 148, 0.7)",accentSecondary080:"rgba(199, 185, 148, 0.8)",accentSecondary090:"rgba(199, 185, 148, 0.9)",accentSecondary100:"rgba(199, 185, 148, 1.0)",productWalletKit:"#FFB800",productAppKit:"#FF573B",productCloud:"#0988F0",productDocumentation:"#008847",neutrals050:"#F6F6F6",neutrals100:"#F3F3F3",neutrals200:"#E9E9E9",neutrals300:"#D0D0D0",neutrals400:"#BBB",neutrals500:"#9A9A9A",neutrals600:"#6C6C6C",neutrals700:"#4F4F4F",neutrals800:"#363636",neutrals900:"#2A2A2A",neutrals1000:"#252525",semanticSuccess010:"rgba(48, 164, 107, 0.1)",semanticSuccess020:"rgba(48, 164, 107, 0.2)",semanticSuccess030:"rgba(48, 164, 107, 0.3)",semanticSuccess040:"rgba(48, 164, 107, 0.4)",semanticSuccess050:"rgba(48, 164, 107, 0.5)",semanticSuccess060:"rgba(48, 164, 107, 0.6)",semanticSuccess070:"rgba(48, 164, 107, 0.7)",semanticSuccess080:"rgba(48, 164, 107, 0.8)",semanticSuccess090:"rgba(48, 164, 107, 0.9)",semanticSuccess100:"rgba(48, 164, 107, 1.0)",semanticError010:"rgba(223, 74, 52, 0.1)",semanticError020:"rgba(223, 74, 52, 0.2)",semanticError030:"rgba(223, 74, 52, 0.3)",semanticError040:"rgba(223, 74, 52, 0.4)",semanticError050:"rgba(223, 74, 52, 0.5)",semanticError060:"rgba(223, 74, 52, 0.6)",semanticError070:"rgba(223, 74, 52, 0.7)",semanticError080:"rgba(223, 74, 52, 0.8)",semanticError090:"rgba(223, 74, 52, 0.9)",semanticError100:"rgba(223, 74, 52, 1.0)",semanticWarning010:"rgba(243, 161, 63, 0.1)",semanticWarning020:"rgba(243, 161, 63, 0.2)",semanticWarning030:"rgba(243, 161, 63, 0.3)",semanticWarning040:"rgba(243, 161, 63, 0.4)",semanticWarning050:"rgba(243, 161, 63, 0.5)",semanticWarning060:"rgba(243, 161, 63, 0.6)",semanticWarning070:"rgba(243, 161, 63, 0.7)",semanticWarning080:"rgba(243, 161, 63, 0.8)",semanticWarning090:"rgba(243, 161, 63, 0.9)",semanticWarning100:"rgba(243, 161, 63, 1.0)"},tv={core:{backgroundAccentPrimary:"#0988F0",backgroundAccentCertified:"#C7B994",backgroundWalletKit:"#FFB800",backgroundAppKit:"#FF573B",backgroundCloud:"#0988F0",backgroundDocumentation:"#008847",backgroundSuccess:"rgba(48, 164, 107, 0.20)",backgroundError:"rgba(223, 74, 52, 0.20)",backgroundWarning:"rgba(243, 161, 63, 0.20)",textAccentPrimary:"#0988F0",textAccentCertified:"#C7B994",textWalletKit:"#FFB800",textAppKit:"#FF573B",textCloud:"#0988F0",textDocumentation:"#008847",textSuccess:"#30A46B",textError:"#DF4A34",textWarning:"#F3A13F",borderAccentPrimary:"#0988F0",borderSecondary:"#C7B994",borderSuccess:"#30A46B",borderError:"#DF4A34",borderWarning:"#F3A13F",foregroundAccent010:"rgba(9, 136, 240, 0.1)",foregroundAccent020:"rgba(9, 136, 240, 0.2)",foregroundAccent040:"rgba(9, 136, 240, 0.4)",foregroundAccent060:"rgba(9, 136, 240, 0.6)",foregroundSecondary020:"rgba(199, 185, 148, 0.2)",foregroundSecondary040:"rgba(199, 185, 148, 0.4)",foregroundSecondary060:"rgba(199, 185, 148, 0.6)",iconAccentPrimary:"#0988F0",iconAccentCertified:"#C7B994",iconSuccess:"#30A46B",iconError:"#DF4A34",iconWarning:"#F3A13F",glass010:"rgba(255, 255, 255, 0.1)",zIndex:"9999"},dark:{overlay:"rgba(0, 0, 0, 0.50)",backgroundPrimary:"#202020",backgroundInvert:"#FFFFFF",textPrimary:"#FFFFFF",textSecondary:"#9A9A9A",textTertiary:"#BBBBBB",textInvert:"#202020",borderPrimary:"#2A2A2A",borderPrimaryDark:"#363636",borderSecondary:"#4F4F4F",foregroundPrimary:"#252525",foregroundSecondary:"#2A2A2A",foregroundTertiary:"#363636",iconDefault:"#9A9A9A",iconInverse:"#FFFFFF"},light:{overlay:"rgba(230 , 230, 230, 0.5)",backgroundPrimary:"#FFFFFF",borderPrimaryDark:"#E9E9E9",backgroundInvert:"#202020",textPrimary:"#202020",textSecondary:"#9A9A9A",textTertiary:"#6C6C6C",textInvert:"#FFFFFF",borderPrimary:"#E9E9E9",borderSecondary:"#D0D0D0",foregroundPrimary:"#F3F3F3",foregroundSecondary:"#E9E9E9",foregroundTertiary:"#D0D0D0",iconDefault:"#9A9A9A",iconInverse:"#202020"}},awe={1:"4px",2:"8px",10:"10px",3:"12px",4:"16px",6:"24px",5:"20px",8:"32px",16:"64px",20:"80px",32:"128px",64:"256px",128:"512px",round:"9999px"},cwe={0:"0px","01":"2px",1:"4px",2:"8px",3:"12px",4:"16px",5:"20px",6:"24px",7:"28px",8:"32px",9:"36px",10:"40px",12:"48px",14:"56px",16:"64px",20:"80px",32:"128px",64:"256px"},EJe={regular:"KHTeka",mono:"KHTekaMono"},AJe={regular:"400",medium:"500"},CJe={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},SJe={"h1-regular-mono":{lineHeight:"50px",letterSpacing:"-3px"},"h1-regular":{lineHeight:"50px",letterSpacing:"-1px"},"h1-medium":{lineHeight:"50px",letterSpacing:"-0.84px"},"h2-regular-mono":{lineHeight:"44px",letterSpacing:"-2.64px"},"h2-regular":{lineHeight:"44px",letterSpacing:"-0.88px"},"h2-medium":{lineHeight:"44px",letterSpacing:"-0.88px"},"h3-regular-mono":{lineHeight:"38px",letterSpacing:"-2.28px"},"h3-regular":{lineHeight:"38px",letterSpacing:"-0.76px"},"h3-medium":{lineHeight:"38px",letterSpacing:"-0.76px"},"h4-regular-mono":{lineHeight:"32px",letterSpacing:"-1.92px"},"h4-regular":{lineHeight:"32px",letterSpacing:"-0.32px"},"h4-medium":{lineHeight:"32px",letterSpacing:"-0.32px"},"h5-regular-mono":{lineHeight:"26px",letterSpacing:"-1.56px"},"h5-regular":{lineHeight:"26px",letterSpacing:"-0.26px"},"h5-medium":{lineHeight:"26px",letterSpacing:"-0.26px"},"h6-regular-mono":{lineHeight:"20px",letterSpacing:"-1.2px"},"h6-regular":{lineHeight:"20px",letterSpacing:"-0.6px"},"h6-medium":{lineHeight:"20px",letterSpacing:"-0.6px"},"lg-regular-mono":{lineHeight:"16px",letterSpacing:"-0.96px"},"lg-regular":{lineHeight:"18px",letterSpacing:"-0.16px"},"lg-medium":{lineHeight:"18px",letterSpacing:"-0.16px"},"md-regular-mono":{lineHeight:"14px",letterSpacing:"-0.84px"},"md-regular":{lineHeight:"16px",letterSpacing:"-0.14px"},"md-medium":{lineHeight:"16px",letterSpacing:"-0.14px"},"sm-regular-mono":{lineHeight:"12px",letterSpacing:"-0.72px"},"sm-regular":{lineHeight:"14px",letterSpacing:"-0.12px"},"sm-medium":{lineHeight:"14px",letterSpacing:"-0.12px"}},IJe={"ease-out-power-2":"cubic-bezier(0.23, 0.09, 0.08, 1.13)","ease-out-power-1":"cubic-bezier(0.12, 0.04, 0.2, 1.06)","ease-in-power-2":"cubic-bezier(0.92, -0.13, 0.77, 0.91)","ease-in-power-1":"cubic-bezier(0.88, -0.06, 0.8, 0.96)","ease-inout-power-2":"cubic-bezier(0.77, 0.09, 0.23, 1.13)","ease-inout-power-1":"cubic-bezier(0.88, 0.04, 0.12, 1.06)"},TJe={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},AP={colors:iwe,fontFamily:EJe,fontWeight:AJe,textSize:CJe,typography:SJe,tokens:{core:tv.core,theme:tv.dark},borderRadius:awe,spacing:cwe,durations:TJe,easings:IJe}});function CP(e){if(!e)return{};let t={};return t["font-family"]=e["--apkt-font-family"]??e["--w3m-font-family"]??"KHTeka",t.accent=e["--apkt-accent"]??e["--w3m-accent"]??"#0988F0",t["color-mix"]=e["--apkt-color-mix"]??e["--w3m-color-mix"]??"#000",t["color-mix-strength"]=e["--apkt-color-mix-strength"]??e["--w3m-color-mix-strength"]??0,t["font-size-master"]=e["--apkt-font-size-master"]??e["--w3m-font-size-master"]??"10px",t["border-radius-master"]=e["--apkt-border-radius-master"]??e["--w3m-border-radius-master"]??"4px",e["--apkt-z-index"]!==void 0?t["z-index"]=e["--apkt-z-index"]:e["--w3m-z-index"]!==void 0&&(t["z-index"]=e["--w3m-z-index"]),t}function fe(e,...t){return Er(e,...t.map(r=>typeof r=="function"?Zi(r($t)):Zi(r)))}var lwe,ku,$t,Rt=b(()=>{l();he();KV();lwe="--apkt";ku={createCSSVariables(e){let t={},r={};function n(s,i,a=""){for(let[c,u]of Object.entries(s)){let d=a?`${a}-${c}`:c;u&&typeof u=="object"&&Object.keys(u).length?(i[c]={},n(u,i[c],d)):typeof u=="string"&&(i[c]=`${lwe}-${d}`)}}function o(s,i){for(let[a,c]of Object.entries(s))c&&typeof c=="object"?(i[a]={},o(c,i[a])):typeof c=="string"&&(i[a]=`var(${c})`)}return n(e,t),o(t,r),{cssVariables:t,cssVariablesVarPrefix:r}},assignCSSVariables(e,t){let r={};function n(o,s,i){for(let[a,c]of Object.entries(o)){let u=i?`${i}-${a}`:a,d=s[a];c&&typeof c=="object"?n(c,d,u):typeof d=="string"&&(r[`${lwe}-${u}`]=d)}}return n(e,t),r},createRootStyles(e,t){let r={...AP,tokens:{...AP.tokens,theme:e==="light"?tv.light:tv.dark}},{cssVariables:n}=ku.createCSSVariables(r),o=ku.assignCSSVariables(n,r),s=ku.generateW3MVariables(t),i=ku.generateW3MOverrides(t),a=ku.generateScaledVariables(t),c=ku.generateBaseVariables(o),u={...o,...c,...s,...i,...a},d=ku.applyColorMixToVariables(t,u),f={...u,...d};return`:root {${Object.entries(f).map(([h,y])=>`${h}:${y.replace("/[:;{}]/g","")};`).join("")}}`},generateW3MVariables(e){if(!e)return{};let t=CP(e),r={};return r["--w3m-font-family"]=t["font-family"],r["--w3m-accent"]=t.accent,r["--w3m-color-mix"]=t["color-mix"],r["--w3m-color-mix-strength"]=`${t["color-mix-strength"]}%`,r["--w3m-font-size-master"]=t["font-size-master"],r["--w3m-border-radius-master"]=t["border-radius-master"],r},generateW3MOverrides(e){if(!e)return{};let t=CP(e),r={};if(e["--apkt-accent"]||e["--w3m-accent"]){let n=t.accent;r["--apkt-tokens-core-iconAccentPrimary"]=n,r["--apkt-tokens-core-borderAccentPrimary"]=n,r["--apkt-tokens-core-textAccentPrimary"]=n,r["--apkt-tokens-core-backgroundAccentPrimary"]=n}return(e["--apkt-font-family"]||e["--w3m-font-family"])&&(r["--apkt-fontFamily-regular"]=t["font-family"]),t["z-index"]!==void 0&&(r["--apkt-tokens-core-zIndex"]=`${t["z-index"]}`),r},generateScaledVariables(e){if(!e)return{};let t=CP(e),r={};if(e["--apkt-font-size-master"]||e["--w3m-font-size-master"]){let n=parseFloat(t["font-size-master"].replace("px",""));r["--apkt-textSize-h1"]=`${Number(n)*5}px`,r["--apkt-textSize-h2"]=`${Number(n)*4.4}px`,r["--apkt-textSize-h3"]=`${Number(n)*3.8}px`,r["--apkt-textSize-h4"]=`${Number(n)*3.2}px`,r["--apkt-textSize-h5"]=`${Number(n)*2.6}px`,r["--apkt-textSize-h6"]=`${Number(n)*2}px`,r["--apkt-textSize-large"]=`${Number(n)*1.6}px`,r["--apkt-textSize-medium"]=`${Number(n)*1.4}px`,r["--apkt-textSize-small"]=`${Number(n)*1.2}px`}if(e["--apkt-border-radius-master"]||e["--w3m-border-radius-master"]){let n=parseFloat(t["border-radius-master"].replace("px",""));r["--apkt-borderRadius-1"]=`${Number(n)}px`,r["--apkt-borderRadius-2"]=`${Number(n)*2}px`,r["--apkt-borderRadius-3"]=`${Number(n)*3}px`,r["--apkt-borderRadius-4"]=`${Number(n)*4}px`,r["--apkt-borderRadius-5"]=`${Number(n)*5}px`,r["--apkt-borderRadius-6"]=`${Number(n)*6}px`,r["--apkt-borderRadius-8"]=`${Number(n)*8}px`,r["--apkt-borderRadius-16"]=`${Number(n)*16}px`,r["--apkt-borderRadius-20"]=`${Number(n)*20}px`,r["--apkt-borderRadius-32"]=`${Number(n)*32}px`,r["--apkt-borderRadius-64"]=`${Number(n)*64}px`,r["--apkt-borderRadius-128"]=`${Number(n)*128}px`}return r},generateColorMixCSS(e,t){if(!e?.["--w3m-color-mix"]||!e["--w3m-color-mix-strength"])return"";let r=e["--w3m-color-mix"],n=e["--w3m-color-mix-strength"];if(!n||n===0)return"";let o=Object.keys(t||{}).filter(i=>{let a=i.includes("-tokens-core-background")||i.includes("-tokens-core-text")||i.includes("-tokens-core-border")||i.includes("-tokens-core-foreground")||i.includes("-tokens-core-icon")||i.includes("-tokens-theme-background")||i.includes("-tokens-theme-text")||i.includes("-tokens-theme-border")||i.includes("-tokens-theme-foreground")||i.includes("-tokens-theme-icon"),c=i.includes("-borderRadius-")||i.includes("-spacing-")||i.includes("-textSize-")||i.includes("-fontFamily-")||i.includes("-fontWeight-")||i.includes("-typography-")||i.includes("-duration-")||i.includes("-ease-")||i.includes("-path-")||i.includes("-width-")||i.includes("-height-")||i.includes("-visual-size-")||i.includes("-modal-width")||i.includes("-cover");return a&&!c});return o.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) { +\f\r"'\`<>=]|("|')|))|$)`,"g"),Z2e=/'/g,G2e=/"/g,Q2e=/^(?:script|style|textarea|title)$/i,qV=e=>(t,...r)=>({_$litType$:e,strings:t,values:r}),V=qV(1),He=qV(2),X2e=qV(3),kp=Symbol.for("lit-noChange"),hn=Symbol.for("lit-nothing"),Y2e=new WeakMap,ky=Uy.createTreeWalker(Uy,129);twe=(e,t)=>{let r=e.length-1,n=[],o,s=t===2?"":t===3?"":"",i=J5;for(let a=0;a"?(i=o??J5,f=-1):d[1]===void 0?f=-2:(f=i.lastIndex-d[2].length,u=d[1],i=d[3]===void 0?By:d[3]==='"'?G2e:Z2e):i===G2e||i===Z2e?i=By:i===W2e||i===K2e?i=J5:(i=By,o=void 0);let h=i===By&&e[a+1].startsWith("/>")?" ":"";s+=i===J5?c+bJe:f>=0?(n.push(u),c.slice(0,f)+zV+c.slice(f)+Bp+h):c+Bp+(f===-2?a:h)}return[ewe(e,s+(e[r]||"")+(t===2?"":t===3?"":"")),n]},ev=class e{constructor({strings:t,_$litType$:r},n){let o;this.parts=[];let s=0,i=0,a=t.length-1,c=this.parts,[u,d]=twe(t,r);if(this.el=e.createElement(u,n),ky.currentNode=this.el.content,r===2||r===3){let f=this.el.content.firstChild;f.replaceWith(...f.childNodes)}for(;(o=ky.nextNode())!==null&&c.length0){o.textContent=yP?yP.emptyScript:"";for(let h=0;h2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=hn}_$AI(t,r=this,n,o){let s=this.strings,i=!1;if(s===void 0)t=Dy(this,t,r,0),i=!X5(t)||t!==this._$AH&&t!==kp,i&&(this._$AH=t);else{let a=t,c,u;for(t=s[0],c=0;c{let n=r?.renderBefore??t,o=n._$litPart$;if(o===void 0){let s=r?.renderBefore??null;n._$litPart$=o=new hx(t.insertBefore(Q5(),s),s,void 0,r??{})}return o._$AI(e),o}});var WV,ie,vJe,owe=b(()=>{l();Y5();Y5();Up();Up();WV=globalThis,ie=class extends Op{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){let r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=nwe(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return kp}};ie._$litElement$=!0,ie.finalized=!0,WV.litElementHydrateSupport?.({LitElement:ie});vJe=WV.litElementPolyfillSupport;vJe?.({LitElement:ie});(WV.litElementVersions??=[]).push("4.2.2")});var swe=b(()=>{l();});var he=b(()=>{l();Y5();Up();owe();swe()});var iwe,tv,awe,cwe,EJe,AJe,CJe,SJe,IJe,TJe,AP,KV=b(()=>{l();iwe={black:"#202020",white:"#FFFFFF",white010:"rgba(255, 255, 255, 0.1)",accent010:"rgba(9, 136, 240, 0.1)",accent020:"rgba(9, 136, 240, 0.2)",accent030:"rgba(9, 136, 240, 0.3)",accent040:"rgba(9, 136, 240, 0.4)",accent050:"rgba(9, 136, 240, 0.5)",accent060:"rgba(9, 136, 240, 0.6)",accent070:"rgba(9, 136, 240, 0.7)",accent080:"rgba(9, 136, 240, 0.8)",accent090:"rgba(9, 136, 240, 0.9)",accent100:"rgba(9, 136, 240, 1.0)",accentSecondary010:"rgba(199, 185, 148, 0.1)",accentSecondary020:"rgba(199, 185, 148, 0.2)",accentSecondary030:"rgba(199, 185, 148, 0.3)",accentSecondary040:"rgba(199, 185, 148, 0.4)",accentSecondary050:"rgba(199, 185, 148, 0.5)",accentSecondary060:"rgba(199, 185, 148, 0.6)",accentSecondary070:"rgba(199, 185, 148, 0.7)",accentSecondary080:"rgba(199, 185, 148, 0.8)",accentSecondary090:"rgba(199, 185, 148, 0.9)",accentSecondary100:"rgba(199, 185, 148, 1.0)",productWalletKit:"#FFB800",productAppKit:"#FF573B",productCloud:"#0988F0",productDocumentation:"#008847",neutrals050:"#F6F6F6",neutrals100:"#F3F3F3",neutrals200:"#E9E9E9",neutrals300:"#D0D0D0",neutrals400:"#BBB",neutrals500:"#9A9A9A",neutrals600:"#6C6C6C",neutrals700:"#4F4F4F",neutrals800:"#363636",neutrals900:"#2A2A2A",neutrals1000:"#252525",semanticSuccess010:"rgba(48, 164, 107, 0.1)",semanticSuccess020:"rgba(48, 164, 107, 0.2)",semanticSuccess030:"rgba(48, 164, 107, 0.3)",semanticSuccess040:"rgba(48, 164, 107, 0.4)",semanticSuccess050:"rgba(48, 164, 107, 0.5)",semanticSuccess060:"rgba(48, 164, 107, 0.6)",semanticSuccess070:"rgba(48, 164, 107, 0.7)",semanticSuccess080:"rgba(48, 164, 107, 0.8)",semanticSuccess090:"rgba(48, 164, 107, 0.9)",semanticSuccess100:"rgba(48, 164, 107, 1.0)",semanticError010:"rgba(223, 74, 52, 0.1)",semanticError020:"rgba(223, 74, 52, 0.2)",semanticError030:"rgba(223, 74, 52, 0.3)",semanticError040:"rgba(223, 74, 52, 0.4)",semanticError050:"rgba(223, 74, 52, 0.5)",semanticError060:"rgba(223, 74, 52, 0.6)",semanticError070:"rgba(223, 74, 52, 0.7)",semanticError080:"rgba(223, 74, 52, 0.8)",semanticError090:"rgba(223, 74, 52, 0.9)",semanticError100:"rgba(223, 74, 52, 1.0)",semanticWarning010:"rgba(243, 161, 63, 0.1)",semanticWarning020:"rgba(243, 161, 63, 0.2)",semanticWarning030:"rgba(243, 161, 63, 0.3)",semanticWarning040:"rgba(243, 161, 63, 0.4)",semanticWarning050:"rgba(243, 161, 63, 0.5)",semanticWarning060:"rgba(243, 161, 63, 0.6)",semanticWarning070:"rgba(243, 161, 63, 0.7)",semanticWarning080:"rgba(243, 161, 63, 0.8)",semanticWarning090:"rgba(243, 161, 63, 0.9)",semanticWarning100:"rgba(243, 161, 63, 1.0)"},tv={core:{backgroundAccentPrimary:"#0988F0",backgroundAccentCertified:"#C7B994",backgroundWalletKit:"#FFB800",backgroundAppKit:"#FF573B",backgroundCloud:"#0988F0",backgroundDocumentation:"#008847",backgroundSuccess:"rgba(48, 164, 107, 0.20)",backgroundError:"rgba(223, 74, 52, 0.20)",backgroundWarning:"rgba(243, 161, 63, 0.20)",textAccentPrimary:"#0988F0",textAccentCertified:"#C7B994",textWalletKit:"#FFB800",textAppKit:"#FF573B",textCloud:"#0988F0",textDocumentation:"#008847",textSuccess:"#30A46B",textError:"#DF4A34",textWarning:"#F3A13F",borderAccentPrimary:"#0988F0",borderSecondary:"#C7B994",borderSuccess:"#30A46B",borderError:"#DF4A34",borderWarning:"#F3A13F",foregroundAccent010:"rgba(9, 136, 240, 0.1)",foregroundAccent020:"rgba(9, 136, 240, 0.2)",foregroundAccent040:"rgba(9, 136, 240, 0.4)",foregroundAccent060:"rgba(9, 136, 240, 0.6)",foregroundSecondary020:"rgba(199, 185, 148, 0.2)",foregroundSecondary040:"rgba(199, 185, 148, 0.4)",foregroundSecondary060:"rgba(199, 185, 148, 0.6)",iconAccentPrimary:"#0988F0",iconAccentCertified:"#C7B994",iconSuccess:"#30A46B",iconError:"#DF4A34",iconWarning:"#F3A13F",glass010:"rgba(255, 255, 255, 0.1)",zIndex:"9999"},dark:{overlay:"rgba(0, 0, 0, 0.50)",backgroundPrimary:"#202020",backgroundInvert:"#FFFFFF",textPrimary:"#FFFFFF",textSecondary:"#9A9A9A",textTertiary:"#BBBBBB",textInvert:"#202020",borderPrimary:"#2A2A2A",borderPrimaryDark:"#363636",borderSecondary:"#4F4F4F",foregroundPrimary:"#252525",foregroundSecondary:"#2A2A2A",foregroundTertiary:"#363636",iconDefault:"#9A9A9A",iconInverse:"#FFFFFF"},light:{overlay:"rgba(230 , 230, 230, 0.5)",backgroundPrimary:"#FFFFFF",borderPrimaryDark:"#E9E9E9",backgroundInvert:"#202020",textPrimary:"#202020",textSecondary:"#9A9A9A",textTertiary:"#6C6C6C",textInvert:"#FFFFFF",borderPrimary:"#E9E9E9",borderSecondary:"#D0D0D0",foregroundPrimary:"#F3F3F3",foregroundSecondary:"#E9E9E9",foregroundTertiary:"#D0D0D0",iconDefault:"#9A9A9A",iconInverse:"#202020"}},awe={1:"4px",2:"8px",10:"10px",3:"12px",4:"16px",6:"24px",5:"20px",8:"32px",16:"64px",20:"80px",32:"128px",64:"256px",128:"512px",round:"9999px"},cwe={0:"0px","01":"2px",1:"4px",2:"8px",3:"12px",4:"16px",5:"20px",6:"24px",7:"28px",8:"32px",9:"36px",10:"40px",12:"48px",14:"56px",16:"64px",20:"80px",32:"128px",64:"256px"},EJe={regular:"KHTeka",mono:"KHTekaMono"},AJe={regular:"400",medium:"500"},CJe={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},SJe={"h1-regular-mono":{lineHeight:"50px",letterSpacing:"-3px"},"h1-regular":{lineHeight:"50px",letterSpacing:"-1px"},"h1-medium":{lineHeight:"50px",letterSpacing:"-0.84px"},"h2-regular-mono":{lineHeight:"44px",letterSpacing:"-2.64px"},"h2-regular":{lineHeight:"44px",letterSpacing:"-0.88px"},"h2-medium":{lineHeight:"44px",letterSpacing:"-0.88px"},"h3-regular-mono":{lineHeight:"38px",letterSpacing:"-2.28px"},"h3-regular":{lineHeight:"38px",letterSpacing:"-0.76px"},"h3-medium":{lineHeight:"38px",letterSpacing:"-0.76px"},"h4-regular-mono":{lineHeight:"32px",letterSpacing:"-1.92px"},"h4-regular":{lineHeight:"32px",letterSpacing:"-0.32px"},"h4-medium":{lineHeight:"32px",letterSpacing:"-0.32px"},"h5-regular-mono":{lineHeight:"26px",letterSpacing:"-1.56px"},"h5-regular":{lineHeight:"26px",letterSpacing:"-0.26px"},"h5-medium":{lineHeight:"26px",letterSpacing:"-0.26px"},"h6-regular-mono":{lineHeight:"20px",letterSpacing:"-1.2px"},"h6-regular":{lineHeight:"20px",letterSpacing:"-0.6px"},"h6-medium":{lineHeight:"20px",letterSpacing:"-0.6px"},"lg-regular-mono":{lineHeight:"16px",letterSpacing:"-0.96px"},"lg-regular":{lineHeight:"18px",letterSpacing:"-0.16px"},"lg-medium":{lineHeight:"18px",letterSpacing:"-0.16px"},"md-regular-mono":{lineHeight:"14px",letterSpacing:"-0.84px"},"md-regular":{lineHeight:"16px",letterSpacing:"-0.14px"},"md-medium":{lineHeight:"16px",letterSpacing:"-0.14px"},"sm-regular-mono":{lineHeight:"12px",letterSpacing:"-0.72px"},"sm-regular":{lineHeight:"14px",letterSpacing:"-0.12px"},"sm-medium":{lineHeight:"14px",letterSpacing:"-0.12px"}},IJe={"ease-out-power-2":"cubic-bezier(0.23, 0.09, 0.08, 1.13)","ease-out-power-1":"cubic-bezier(0.12, 0.04, 0.2, 1.06)","ease-in-power-2":"cubic-bezier(0.92, -0.13, 0.77, 0.91)","ease-in-power-1":"cubic-bezier(0.88, -0.06, 0.8, 0.96)","ease-inout-power-2":"cubic-bezier(0.77, 0.09, 0.23, 1.13)","ease-inout-power-1":"cubic-bezier(0.88, 0.04, 0.12, 1.06)"},TJe={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},AP={colors:iwe,fontFamily:EJe,fontWeight:AJe,textSize:CJe,typography:SJe,tokens:{core:tv.core,theme:tv.dark},borderRadius:awe,spacing:cwe,durations:TJe,easings:IJe}});function CP(e){if(!e)return{};let t={};return t["font-family"]=e["--apkt-font-family"]??e["--w3m-font-family"]??"KHTeka",t.accent=e["--apkt-accent"]??e["--w3m-accent"]??"#0988F0",t["color-mix"]=e["--apkt-color-mix"]??e["--w3m-color-mix"]??"#000",t["color-mix-strength"]=e["--apkt-color-mix-strength"]??e["--w3m-color-mix-strength"]??0,t["font-size-master"]=e["--apkt-font-size-master"]??e["--w3m-font-size-master"]??"10px",t["border-radius-master"]=e["--apkt-border-radius-master"]??e["--w3m-border-radius-master"]??"4px",e["--apkt-z-index"]!==void 0?t["z-index"]=e["--apkt-z-index"]:e["--w3m-z-index"]!==void 0&&(t["z-index"]=e["--w3m-z-index"]),t}function fe(e,...t){return Er(e,...t.map(r=>typeof r=="function"?Gi(r($t)):Gi(r)))}var lwe,ku,$t,Rt=b(()=>{l();he();KV();lwe="--apkt";ku={createCSSVariables(e){let t={},r={};function n(s,i,a=""){for(let[c,u]of Object.entries(s)){let d=a?`${a}-${c}`:c;u&&typeof u=="object"&&Object.keys(u).length?(i[c]={},n(u,i[c],d)):typeof u=="string"&&(i[c]=`${lwe}-${d}`)}}function o(s,i){for(let[a,c]of Object.entries(s))c&&typeof c=="object"?(i[a]={},o(c,i[a])):typeof c=="string"&&(i[a]=`var(${c})`)}return n(e,t),o(t,r),{cssVariables:t,cssVariablesVarPrefix:r}},assignCSSVariables(e,t){let r={};function n(o,s,i){for(let[a,c]of Object.entries(o)){let u=i?`${i}-${a}`:a,d=s[a];c&&typeof c=="object"?n(c,d,u):typeof d=="string"&&(r[`${lwe}-${u}`]=d)}}return n(e,t),r},createRootStyles(e,t){let r={...AP,tokens:{...AP.tokens,theme:e==="light"?tv.light:tv.dark}},{cssVariables:n}=ku.createCSSVariables(r),o=ku.assignCSSVariables(n,r),s=ku.generateW3MVariables(t),i=ku.generateW3MOverrides(t),a=ku.generateScaledVariables(t),c=ku.generateBaseVariables(o),u={...o,...c,...s,...i,...a},d=ku.applyColorMixToVariables(t,u),f={...u,...d};return`:root {${Object.entries(f).map(([h,y])=>`${h}:${y.replace("/[:;{}]/g","")};`).join("")}}`},generateW3MVariables(e){if(!e)return{};let t=CP(e),r={};return r["--w3m-font-family"]=t["font-family"],r["--w3m-accent"]=t.accent,r["--w3m-color-mix"]=t["color-mix"],r["--w3m-color-mix-strength"]=`${t["color-mix-strength"]}%`,r["--w3m-font-size-master"]=t["font-size-master"],r["--w3m-border-radius-master"]=t["border-radius-master"],r},generateW3MOverrides(e){if(!e)return{};let t=CP(e),r={};if(e["--apkt-accent"]||e["--w3m-accent"]){let n=t.accent;r["--apkt-tokens-core-iconAccentPrimary"]=n,r["--apkt-tokens-core-borderAccentPrimary"]=n,r["--apkt-tokens-core-textAccentPrimary"]=n,r["--apkt-tokens-core-backgroundAccentPrimary"]=n}return(e["--apkt-font-family"]||e["--w3m-font-family"])&&(r["--apkt-fontFamily-regular"]=t["font-family"]),t["z-index"]!==void 0&&(r["--apkt-tokens-core-zIndex"]=`${t["z-index"]}`),r},generateScaledVariables(e){if(!e)return{};let t=CP(e),r={};if(e["--apkt-font-size-master"]||e["--w3m-font-size-master"]){let n=parseFloat(t["font-size-master"].replace("px",""));r["--apkt-textSize-h1"]=`${Number(n)*5}px`,r["--apkt-textSize-h2"]=`${Number(n)*4.4}px`,r["--apkt-textSize-h3"]=`${Number(n)*3.8}px`,r["--apkt-textSize-h4"]=`${Number(n)*3.2}px`,r["--apkt-textSize-h5"]=`${Number(n)*2.6}px`,r["--apkt-textSize-h6"]=`${Number(n)*2}px`,r["--apkt-textSize-large"]=`${Number(n)*1.6}px`,r["--apkt-textSize-medium"]=`${Number(n)*1.4}px`,r["--apkt-textSize-small"]=`${Number(n)*1.2}px`}if(e["--apkt-border-radius-master"]||e["--w3m-border-radius-master"]){let n=parseFloat(t["border-radius-master"].replace("px",""));r["--apkt-borderRadius-1"]=`${Number(n)}px`,r["--apkt-borderRadius-2"]=`${Number(n)*2}px`,r["--apkt-borderRadius-3"]=`${Number(n)*3}px`,r["--apkt-borderRadius-4"]=`${Number(n)*4}px`,r["--apkt-borderRadius-5"]=`${Number(n)*5}px`,r["--apkt-borderRadius-6"]=`${Number(n)*6}px`,r["--apkt-borderRadius-8"]=`${Number(n)*8}px`,r["--apkt-borderRadius-16"]=`${Number(n)*16}px`,r["--apkt-borderRadius-20"]=`${Number(n)*20}px`,r["--apkt-borderRadius-32"]=`${Number(n)*32}px`,r["--apkt-borderRadius-64"]=`${Number(n)*64}px`,r["--apkt-borderRadius-128"]=`${Number(n)*128}px`}return r},generateColorMixCSS(e,t){if(!e?.["--w3m-color-mix"]||!e["--w3m-color-mix-strength"])return"";let r=e["--w3m-color-mix"],n=e["--w3m-color-mix-strength"];if(!n||n===0)return"";let o=Object.keys(t||{}).filter(i=>{let a=i.includes("-tokens-core-background")||i.includes("-tokens-core-text")||i.includes("-tokens-core-border")||i.includes("-tokens-core-foreground")||i.includes("-tokens-core-icon")||i.includes("-tokens-theme-background")||i.includes("-tokens-theme-text")||i.includes("-tokens-theme-border")||i.includes("-tokens-theme-foreground")||i.includes("-tokens-theme-icon"),c=i.includes("-borderRadius-")||i.includes("-spacing-")||i.includes("-textSize-")||i.includes("-fontFamily-")||i.includes("-fontWeight-")||i.includes("-typography-")||i.includes("-duration-")||i.includes("-ease-")||i.includes("-path-")||i.includes("-width-")||i.includes("-height-")||i.includes("-visual-size-")||i.includes("-modal-width")||i.includes("-cover");return a&&!c});return o.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) { :root { ${o.map(i=>{let a=t?.[i]||"";return a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?`${i}: color-mix(in srgb, ${r} ${n}%, ${a});`:`${i}: color-mix(in srgb, ${r} ${n}%, var(${i}-base, ${a}));`}).join("")} } @@ -86,8 +86,8 @@ ${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toSt @font-face { font-family: 'KHTeka'; src: - url(${Zi(Dp["KHTeka-400-woff2"])}) format('woff2'), - url(${Zi(Dp["KHTeka-400-woff"])}) format('woff'); + url(${Gi(Dp["KHTeka-400-woff2"])}) format('woff2'), + url(${Gi(Dp["KHTeka-400-woff"])}) format('woff'); font-weight: 400; font-style: normal; font-display: swap; @@ -96,8 +96,8 @@ ${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toSt @font-face { font-family: 'KHTeka'; src: - url(${Zi(Dp["KHTeka-300-woff2"])}) format('woff2'), - url(${Zi(Dp["KHTeka-300-woff"])}) format('woff'); + url(${Gi(Dp["KHTeka-300-woff2"])}) format('woff2'), + url(${Gi(Dp["KHTeka-300-woff"])}) format('woff'); font-weight: 300; font-style: normal; } @@ -105,8 +105,8 @@ ${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toSt @font-face { font-family: 'KHTekaMono'; src: - url(${Zi(Dp["KHTekaMono-400-woff2"])}) format('woff2'), - url(${Zi(Dp["KHTekaMono-400-woff"])}) format('woff'); + url(${Gi(Dp["KHTekaMono-400-woff2"])}) format('woff2'), + url(${Gi(Dp["KHTekaMono-400-woff"])}) format('woff'); font-weight: 400; font-style: normal; } @@ -114,8 +114,8 @@ ${e.length}`,r=new TextEncoder().encode(t+e);return"0x"+Buffer.from(AVe(r)).toSt @font-face { font-family: 'KHTeka'; src: - url(${Zi(Dp["KHTeka-400-woff2"])}) format('woff2'), - url(${Zi(Dp["KHTeka-400-woff"])}) format('woff'); + url(${Gi(Dp["KHTeka-400-woff2"])}) format('woff2'), + url(${Gi(Dp["KHTeka-400-woff"])}) format('woff'); font-weight: 400; font-style: normal; } @@ -311,7 +311,7 @@ ${t.statement} height: inherit; box-sizing: border-box; } -`});var Gi,Ns,$y=b(()=>{l();he();$e();Mt();gx();Bt();Dwe();Gi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ns=class extends ie{render(){return this.style.cssText=` +`});var Yi,Ns,$y=b(()=>{l();he();$e();Mt();gx();Bt();Dwe();Yi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Ns=class extends ie{render(){return this.style.cssText=` flex-direction: ${this.flexDirection}; flex-wrap: ${this.flexWrap}; flex-basis: ${this.flexBasis}; @@ -331,7 +331,7 @@ ${t.statement} margin-bottom: ${this.margin&&hr.getSpacingStyles(this.margin,2)}; margin-left: ${this.margin&&hr.getSpacingStyles(this.margin,3)}; width: ${this.width}; - `,V``}};Ns.styles=[Me,Uwe];Gi([q()],Ns.prototype,"flexDirection",void 0);Gi([q()],Ns.prototype,"flexWrap",void 0);Gi([q()],Ns.prototype,"flexBasis",void 0);Gi([q()],Ns.prototype,"flexGrow",void 0);Gi([q()],Ns.prototype,"flexShrink",void 0);Gi([q()],Ns.prototype,"alignItems",void 0);Gi([q()],Ns.prototype,"justifyContent",void 0);Gi([q()],Ns.prototype,"columnGap",void 0);Gi([q()],Ns.prototype,"rowGap",void 0);Gi([q()],Ns.prototype,"gap",void 0);Gi([q()],Ns.prototype,"padding",void 0);Gi([q()],Ns.prototype,"margin",void 0);Gi([q()],Ns.prototype,"width",void 0);Ns=Gi([ne("wui-flex")],Ns)});var jr=b(()=>{l();$y()});var Ce,Lwe=b(()=>{l();Up();Ce=e=>e??hn});var kr=b(()=>{l();Lwe()});var Hwe,DJe,$we,Mwe,rj,nj,T0r,_0r,Fwe=b(()=>{l();Up();Hwe=Symbol.for(""),DJe=e=>{if(e?.r===Hwe)return e?._$litStatic$},$we=e=>({_$litStatic$:e,r:Hwe}),Mwe=new Map,rj=e=>(t,...r)=>{let n=r.length,o,s,i=[],a=[],c,u=0,d=!1;for(;u{l();Fwe()});var Vwe,jwe=b(()=>{l();he();Vwe=He` + `,V``}};Ns.styles=[Me,Uwe];Yi([q()],Ns.prototype,"flexDirection",void 0);Yi([q()],Ns.prototype,"flexWrap",void 0);Yi([q()],Ns.prototype,"flexBasis",void 0);Yi([q()],Ns.prototype,"flexGrow",void 0);Yi([q()],Ns.prototype,"flexShrink",void 0);Yi([q()],Ns.prototype,"alignItems",void 0);Yi([q()],Ns.prototype,"justifyContent",void 0);Yi([q()],Ns.prototype,"columnGap",void 0);Yi([q()],Ns.prototype,"rowGap",void 0);Yi([q()],Ns.prototype,"gap",void 0);Yi([q()],Ns.prototype,"padding",void 0);Yi([q()],Ns.prototype,"margin",void 0);Yi([q()],Ns.prototype,"width",void 0);Ns=Yi([ne("wui-flex")],Ns)});var jr=b(()=>{l();$y()});var Ce,Lwe=b(()=>{l();Up();Ce=e=>e??hn});var kr=b(()=>{l();Lwe()});var Hwe,DJe,$we,Mwe,rj,nj,T0r,_0r,Fwe=b(()=>{l();Up();Hwe=Symbol.for(""),DJe=e=>{if(e?.r===Hwe)return e?._$litStatic$},$we=e=>({_$litStatic$:e,r:Hwe}),Mwe=new Map,rj=e=>(t,...r)=>{let n=r.length,o,s,i=[],a=[],c,u=0,d=!1;for(;u{l();Fwe()});var Vwe,jwe=b(()=>{l();he();Vwe=He` @@ -1993,7 +1993,7 @@ ${t.statement} wui-flex.namespace-icon:not(:first-child) { margin-left: -4px; } -`});var Yi,set,Os,P8e=b(()=>{l();he();$e();kr();uo();Rs();Sx();Mt();Bt();C8e();hj();HP();_8e();Yi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},set={eip155:"ethereum",solana:"solana",bip122:"bitcoin",polkadot:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:"ton"},Os=class extends ie{constructor(){super(...arguments),this.walletImages=[],this.imageSrc="",this.name="",this.size="md",this.tabIdx=void 0,this.namespaces=[],this.disabled=!1,this.showAllWallets=!1,this.loading=!1,this.loadingSpinnerColor="accent-100"}render(){return this.dataset.size=this.size,V` +`});var Ji,set,Os,P8e=b(()=>{l();he();$e();kr();uo();Rs();Sx();Mt();Bt();C8e();hj();HP();_8e();Ji=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},set={eip155:"ethereum",solana:"solana",bip122:"bitcoin",polkadot:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:"ton"},Os=class extends ie{constructor(){super(...arguments),this.walletImages=[],this.imageSrc="",this.name="",this.size="md",this.tabIdx=void 0,this.namespaces=[],this.disabled=!1,this.showAllWallets=!1,this.loading=!1,this.loadingSpinnerColor="accent-100"}render(){return this.dataset.size=this.size,V`
+`});var Ic,Qi,n5e=b(()=>{l();he();$e();kr();lN();uo();Rs();Mt();Bt();r5e();Ic=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Qi=class extends ie{constructor(){super(...arguments),this.inputElementRef=Lx(),this.disabled=!1,this.loading=!1,this.placeholder="",this.type="text",this.value="",this.size="md"}render(){return V`
${this.templateLeftIcon()} ${this.loading?V``:V``} - `:null}templateError(){return this.errorText?V`${this.errorText}`:null}templateWarning(){return this.warningText?V`${this.warningText}`:null}dispatchInputChangeEvent(){this.dispatchEvent(new CustomEvent("inputChange",{detail:this.inputElementRef.value?.value,bubbles:!0,composed:!0}))}};Ji.styles=[Me,Gt,t5e];Ic([q()],Ji.prototype,"icon",void 0);Ic([q({type:Boolean})],Ji.prototype,"disabled",void 0);Ic([q({type:Boolean})],Ji.prototype,"loading",void 0);Ic([q()],Ji.prototype,"placeholder",void 0);Ic([q()],Ji.prototype,"type",void 0);Ic([q()],Ji.prototype,"value",void 0);Ic([q()],Ji.prototype,"errorText",void 0);Ic([q()],Ji.prototype,"warningText",void 0);Ic([q()],Ji.prototype,"onSubmit",void 0);Ic([q()],Ji.prototype,"size",void 0);Ic([q({attribute:!1})],Ji.prototype,"onKeyDown",void 0);Ji=Ic([ne("wui-input-text")],Ji)});var o5e,s5e=b(()=>{l();Rt();o5e=fe` + `:null}templateError(){return this.errorText?V`${this.errorText}`:null}templateWarning(){return this.warningText?V`${this.warningText}`:null}dispatchInputChangeEvent(){this.dispatchEvent(new CustomEvent("inputChange",{detail:this.inputElementRef.value?.value,bubbles:!0,composed:!0}))}};Qi.styles=[Me,Gt,t5e];Ic([q()],Qi.prototype,"icon",void 0);Ic([q({type:Boolean})],Qi.prototype,"disabled",void 0);Ic([q({type:Boolean})],Qi.prototype,"loading",void 0);Ic([q()],Qi.prototype,"placeholder",void 0);Ic([q()],Qi.prototype,"type",void 0);Ic([q()],Qi.prototype,"value",void 0);Ic([q()],Qi.prototype,"errorText",void 0);Ic([q()],Qi.prototype,"warningText",void 0);Ic([q()],Qi.prototype,"onSubmit",void 0);Ic([q()],Qi.prototype,"size",void 0);Ic([q({attribute:!1})],Qi.prototype,"onKeyDown",void 0);Qi=Ic([ne("wui-input-text")],Qi)});var o5e,s5e=b(()=>{l();Rt();o5e=fe` :host { position: relative; display: inline-block; @@ -3376,7 +3376,7 @@ Minimum version required to store current data is: `+s+`. width: inherit; height: inherit; } -`});var Tc,Qi,g5e=b(()=>{l();he();$e();Mt();gx();Bt();m5e();Tc=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Qi=class extends ie{render(){return this.style.cssText=` +`});var Tc,Xi,g5e=b(()=>{l();he();$e();Mt();gx();Bt();m5e();Tc=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Xi=class extends ie{render(){return this.style.cssText=` grid-template-rows: ${this.gridTemplateRows}; grid-template-columns: ${this.gridTemplateColumns}; justify-items: ${this.justifyItems}; @@ -3394,7 +3394,7 @@ Minimum version required to store current data is: `+s+`. margin-right: ${this.margin&&hr.getSpacingStyles(this.margin,1)}; margin-bottom: ${this.margin&&hr.getSpacingStyles(this.margin,2)}; margin-left: ${this.margin&&hr.getSpacingStyles(this.margin,3)}; - `,V``}};Qi.styles=[Me,h5e];Tc([q()],Qi.prototype,"gridTemplateRows",void 0);Tc([q()],Qi.prototype,"gridTemplateColumns",void 0);Tc([q()],Qi.prototype,"justifyItems",void 0);Tc([q()],Qi.prototype,"alignItems",void 0);Tc([q()],Qi.prototype,"justifyContent",void 0);Tc([q()],Qi.prototype,"alignContent",void 0);Tc([q()],Qi.prototype,"columnGap",void 0);Tc([q()],Qi.prototype,"rowGap",void 0);Tc([q()],Qi.prototype,"gap",void 0);Tc([q()],Qi.prototype,"padding",void 0);Tc([q()],Qi.prototype,"margin",void 0);Qi=Tc([ne("wui-grid")],Qi)});var Qj=b(()=>{l();g5e()});var y5e,w5e=b(()=>{l();Ve();y5e=fe` + `,V``}};Xi.styles=[Me,h5e];Tc([q()],Xi.prototype,"gridTemplateRows",void 0);Tc([q()],Xi.prototype,"gridTemplateColumns",void 0);Tc([q()],Xi.prototype,"justifyItems",void 0);Tc([q()],Xi.prototype,"alignItems",void 0);Tc([q()],Xi.prototype,"justifyContent",void 0);Tc([q()],Xi.prototype,"alignContent",void 0);Tc([q()],Xi.prototype,"columnGap",void 0);Tc([q()],Xi.prototype,"rowGap",void 0);Tc([q()],Xi.prototype,"gap",void 0);Tc([q()],Xi.prototype,"padding",void 0);Tc([q()],Xi.prototype,"margin",void 0);Xi=Tc([ne("wui-grid")],Xi)});var Qj=b(()=>{l();g5e()});var y5e,w5e=b(()=>{l();Ve();y5e=fe` button { display: flex; flex-direction: column; @@ -3695,7 +3695,7 @@ Minimum version required to store current data is: `+s+`. opacity: 0.5; cursor: not-allowed; } -`});var Xi,Bs,P5e=b(()=>{l();he();$e();kr();wE();Rs();Mt();Bt();_5e();Xi=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Bs=class extends ie{constructor(){super(...arguments),this.type="primary",this.imageSrc="google",this.imageSize=void 0,this.loading=!1,this.boxColor="foregroundPrimary",this.disabled=!1,this.rightIcon=!0,this.boxed=!0,this.rounded=!1,this.fullSize=!1}render(){return this.dataset.rounded=this.rounded?"true":"false",this.dataset.type=this.type,V` +`});var ea,Bs,P5e=b(()=>{l();he();$e();kr();wE();Rs();Mt();Bt();_5e();ea=function(e,t,r,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},Bs=class extends ie{constructor(){super(...arguments),this.type="primary",this.imageSrc="google",this.imageSize=void 0,this.loading=!1,this.boxColor="foregroundPrimary",this.disabled=!1,this.rightIcon=!0,this.boxed=!0,this.rounded=!1,this.fullSize=!1}render(){return this.dataset.rounded=this.rounded?"true":"false",this.dataset.type=this.type,V`
- `}onViewChange(t){let r=t.split(",").filter(Boolean),n=this.historyState.split(",").filter(Boolean),o=n.length,s=r.length,i=r[r.length-1]||"",a=hr.cssDurationToNumber(this.transitionDuration),c="";s>o?c="next":s{this.historyState=t,this.setView?.(i)},a),setTimeout(()=>{this.viewDirection=""},a*2)}getWrapper(){return this.shadowRoot?.querySelector("div.page")}updateContainerHeight(){let t=this.getWrapper();if(!t)return;let r=parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--apkt-footer-height")||"0"),n=0;if(this.mobileFullScreen){let o=window.visualViewport?.height||window.innerHeight,s=this.getHeaderHeight();n=o-s-r,this.style.setProperty("--local-border-bottom-radius","0px")}else n=t.getBoundingClientRect().height+r,this.style.setProperty("--local-border-bottom-radius",r?"var(--apkt-borderRadius-5)":"0px");this.style.setProperty("--local-container-height",`${n}px`),this.previousHeight!=="0px"&&this.style.setProperty("--local-duration-height",this.transitionDuration),this.previousHeight=`${n}px`}getHeaderHeight(){return Vtt}};$a.styles=[iAe];Vd([q({type:String})],$a.prototype,"transitionDuration",void 0);Vd([q({type:String})],$a.prototype,"transitionFunction",void 0);Vd([q({type:String})],$a.prototype,"history",void 0);Vd([q({type:String})],$a.prototype,"view",void 0);Vd([q({attribute:!1})],$a.prototype,"setView",void 0);Vd([le()],$a.prototype,"viewDirection",void 0);Vd([le()],$a.prototype,"historyState",void 0);Vd([le()],$a.prototype,"previousHeight",void 0);Vd([le()],$a.prototype,"mobileFullScreen",void 0);$a=Vd([ne("w3m-router-container")],$a)});var lAe={};Te(lAe,{AppKitModal:()=>Rq,W3mListWallet:()=>Jn,W3mModal:()=>Nq,W3mModalBase:()=>ea,W3mRouterContainer:()=>$a,W3mUsageExceededView:()=>TN});var uAe=b(()=>{l();XEe();rAe();sAe();cAe()});var dAe,ZE,fAe=b(()=>{l();ct();Iwe();dAe=!1,ZE=class extends RP{async open(t){re.isConnected()||await super.open(t)}async close(){if(await super.close(),this.options.manualWCControl){let t=$.getAccountData(this.activeChainNamespace)?.address;ee.finalizeWcConnection(t)}}async syncIdentity(t){return Promise.resolve()}async syncBalance(t){return Promise.resolve()}async injectModalUi(){if(!dAe&&se.isClient()){if(await Promise.resolve().then(()=>(O5e(),R5e)),await Promise.resolve().then(()=>(uAe(),lAe)),!document.querySelector("w3m-modal")){let r=document.createElement("w3m-modal");!Y.state.disableAppend&&!Y.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",r)}dAe=!0}}}});var pAe,hAe=b(()=>{l();pAe="1.8.17-wc-circular-dependencies-fix.0"});var mAe={};Te(mAe,{AppKit:()=>ZE,createAppKit:()=>jtt});function jtt(e){return new ZE({...e,basic:!0,sdkVersion:`html-core-${pAe}`})}var gAe=b(()=>{l();fAe();hAe()});var EAe=_e((r$r,vAe)=>{l();vAe.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var s1=_e(p2=>{l();var kq,ort=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];p2.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};p2.getSymbolTotalCodewords=function(t){return ort[t]};p2.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t};p2.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');kq=t};p2.isKanjiModeEnabled=function(){return typeof kq<"u"};p2.toSJIS=function(t){return kq(t)}});var NN=_e(Nc=>{l();Nc.L={bit:1};Nc.M={bit:0};Nc.Q={bit:3};Nc.H={bit:2};function srt(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return Nc.L;case"m":case"medium":return Nc.M;case"q":case"quartile":return Nc.Q;case"h":case"high":return Nc.H;default:throw new Error("Unknown EC Level: "+e)}}Nc.isValid=function(t){return t&&typeof t.bit<"u"&&t.bit>=0&&t.bit<4};Nc.from=function(t,r){if(Nc.isValid(t))return t;try{return srt(t)}catch{return r}}});var SAe=_e((c$r,CAe)=>{l();function AAe(){this.buffer=[],this.length=0}AAe.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let r=0;r>>t-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};CAe.exports=AAe});var TAe=_e((u$r,IAe)=>{l();function GE(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}GE.prototype.set=function(e,t,r,n){let o=e*this.size+t;this.data[o]=r,n&&(this.reservedBit[o]=!0)};GE.prototype.get=function(e,t){return this.data[e*this.size+t]};GE.prototype.xor=function(e,t,r){this.data[e*this.size+t]^=r};GE.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};IAe.exports=GE});var _Ae=_e(RN=>{l();var irt=s1().getSymbolSize;RN.getRowColCoords=function(t){if(t===1)return[];let r=Math.floor(t/7)+2,n=irt(t),o=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let i=1;i{l();var art=s1().getSymbolSize,PAe=7;NAe.getPositions=function(t){let r=art(t);return[[0,0],[r-PAe,0],[0,r-PAe]]}});var OAe=_e(Wr=>{l();Wr.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var h2={N1:3,N2:3,N3:40,N4:10};Wr.isValid=function(t){return t!=null&&t!==""&&!isNaN(t)&&t>=0&&t<=7};Wr.from=function(t){return Wr.isValid(t)?parseInt(t,10):void 0};Wr.getPenaltyN1=function(t){let r=t.size,n=0,o=0,s=0,i=null,a=null;for(let c=0;c=5&&(n+=h2.N1+(o-5)),i=d,o=1),d=t.get(u,c),d===a?s++:(s>=5&&(n+=h2.N1+(s-5)),a=d,s=1)}o>=5&&(n+=h2.N1+(o-5)),s>=5&&(n+=h2.N1+(s-5))}return n};Wr.getPenaltyN2=function(t){let r=t.size,n=0;for(let o=0;o=10&&(o===1488||o===93)&&n++,s=s<<1&2047|t.get(a,i),a>=10&&(s===1488||s===93)&&n++}return n*h2.N3};Wr.getPenaltyN4=function(t){let r=0,n=t.data.length;for(let s=0;s{l();var i1=NN(),ON=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],BN=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Uq.getBlocksCount=function(t,r){switch(r){case i1.L:return ON[(t-1)*4+0];case i1.M:return ON[(t-1)*4+1];case i1.Q:return ON[(t-1)*4+2];case i1.H:return ON[(t-1)*4+3];default:return}};Uq.getTotalCodewordsCount=function(t,r){switch(r){case i1.L:return BN[(t-1)*4+0];case i1.M:return BN[(t-1)*4+1];case i1.Q:return BN[(t-1)*4+2];case i1.H:return BN[(t-1)*4+3];default:return}}});var BAe=_e(UN=>{l();var YE=new Uint8Array(512),kN=new Uint8Array(256);(function(){let t=1;for(let r=0;r<255;r++)YE[r]=t,kN[t]=r,t<<=1,t&256&&(t^=285);for(let r=255;r<512;r++)YE[r]=YE[r-255]})();UN.log=function(t){if(t<1)throw new Error("log("+t+")");return kN[t]};UN.exp=function(t){return YE[t]};UN.mul=function(t,r){return t===0||r===0?0:YE[kN[t]+kN[r]]}});var kAe=_e(JE=>{l();var Lq=BAe();JE.mul=function(t,r){let n=new Uint8Array(t.length+r.length-1);for(let o=0;o=0;){let o=n[0];for(let i=0;i{l();var UAe=kAe();function Mq(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Mq.prototype.initialize=function(t){this.degree=t,this.genPoly=UAe.generateECPolynomial(this.degree)};Mq.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(t.length+this.degree);r.set(t);let n=UAe.mod(r,this.genPoly),o=this.degree-n.length;if(o>0){let s=new Uint8Array(this.degree);return s.set(n,o),s}return n};DAe.exports=Mq});var Hq=_e(MAe=>{l();MAe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}});var $q=_e(Zp=>{l();var HAe="[0-9]+",lrt="[A-Z $%*+\\-./:]+",QE="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";QE=QE.replace(/u/g,"\\u");var urt="(?:(?![A-Z0-9 $%*+\\-./:]|"+QE+`)(?:.|[\r + `}onViewChange(t){let r=t.split(",").filter(Boolean),n=this.historyState.split(",").filter(Boolean),o=n.length,s=r.length,i=r[r.length-1]||"",a=hr.cssDurationToNumber(this.transitionDuration),c="";s>o?c="next":s{this.historyState=t,this.setView?.(i)},a),setTimeout(()=>{this.viewDirection=""},a*2)}getWrapper(){return this.shadowRoot?.querySelector("div.page")}updateContainerHeight(){let t=this.getWrapper();if(!t)return;let r=parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--apkt-footer-height")||"0"),n=0;if(this.mobileFullScreen){let o=window.visualViewport?.height||window.innerHeight,s=this.getHeaderHeight();n=o-s-r,this.style.setProperty("--local-border-bottom-radius","0px")}else n=t.getBoundingClientRect().height+r,this.style.setProperty("--local-border-bottom-radius",r?"var(--apkt-borderRadius-5)":"0px");this.style.setProperty("--local-container-height",`${n}px`),this.previousHeight!=="0px"&&this.style.setProperty("--local-duration-height",this.transitionDuration),this.previousHeight=`${n}px`}getHeaderHeight(){return Vtt}};$a.styles=[iAe];Vd([q({type:String})],$a.prototype,"transitionDuration",void 0);Vd([q({type:String})],$a.prototype,"transitionFunction",void 0);Vd([q({type:String})],$a.prototype,"history",void 0);Vd([q({type:String})],$a.prototype,"view",void 0);Vd([q({attribute:!1})],$a.prototype,"setView",void 0);Vd([le()],$a.prototype,"viewDirection",void 0);Vd([le()],$a.prototype,"historyState",void 0);Vd([le()],$a.prototype,"previousHeight",void 0);Vd([le()],$a.prototype,"mobileFullScreen",void 0);$a=Vd([ne("w3m-router-container")],$a)});var lAe={};Te(lAe,{AppKitModal:()=>Rq,W3mListWallet:()=>Jn,W3mModal:()=>Nq,W3mModalBase:()=>ta,W3mRouterContainer:()=>$a,W3mUsageExceededView:()=>TN});var uAe=b(()=>{l();XEe();rAe();sAe();cAe()});var dAe,ZE,fAe=b(()=>{l();ct();Iwe();dAe=!1,ZE=class extends RP{async open(t){re.isConnected()||await super.open(t)}async close(){if(await super.close(),this.options.manualWCControl){let t=$.getAccountData(this.activeChainNamespace)?.address;ee.finalizeWcConnection(t)}}async syncIdentity(t){return Promise.resolve()}async syncBalance(t){return Promise.resolve()}async injectModalUi(){if(!dAe&&se.isClient()){if(await Promise.resolve().then(()=>(O5e(),R5e)),await Promise.resolve().then(()=>(uAe(),lAe)),!document.querySelector("w3m-modal")){let r=document.createElement("w3m-modal");!Y.state.disableAppend&&!Y.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",r)}dAe=!0}}}});var pAe,hAe=b(()=>{l();pAe="1.8.17-wc-circular-dependencies-fix.0"});var mAe={};Te(mAe,{AppKit:()=>ZE,createAppKit:()=>jtt});function jtt(e){return new ZE({...e,basic:!0,sdkVersion:`html-core-${pAe}`})}var gAe=b(()=>{l();fAe();hAe()});var EAe=_e((r$r,vAe)=>{l();vAe.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var s1=_e(p2=>{l();var kq,ort=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];p2.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};p2.getSymbolTotalCodewords=function(t){return ort[t]};p2.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t};p2.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');kq=t};p2.isKanjiModeEnabled=function(){return typeof kq<"u"};p2.toSJIS=function(t){return kq(t)}});var NN=_e(Nc=>{l();Nc.L={bit:1};Nc.M={bit:0};Nc.Q={bit:3};Nc.H={bit:2};function srt(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"l":case"low":return Nc.L;case"m":case"medium":return Nc.M;case"q":case"quartile":return Nc.Q;case"h":case"high":return Nc.H;default:throw new Error("Unknown EC Level: "+e)}}Nc.isValid=function(t){return t&&typeof t.bit<"u"&&t.bit>=0&&t.bit<4};Nc.from=function(t,r){if(Nc.isValid(t))return t;try{return srt(t)}catch{return r}}});var SAe=_e((c$r,CAe)=>{l();function AAe(){this.buffer=[],this.length=0}AAe.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let r=0;r>>t-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};CAe.exports=AAe});var TAe=_e((u$r,IAe)=>{l();function GE(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}GE.prototype.set=function(e,t,r,n){let o=e*this.size+t;this.data[o]=r,n&&(this.reservedBit[o]=!0)};GE.prototype.get=function(e,t){return this.data[e*this.size+t]};GE.prototype.xor=function(e,t,r){this.data[e*this.size+t]^=r};GE.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};IAe.exports=GE});var _Ae=_e(RN=>{l();var irt=s1().getSymbolSize;RN.getRowColCoords=function(t){if(t===1)return[];let r=Math.floor(t/7)+2,n=irt(t),o=n===145?26:Math.ceil((n-13)/(2*r-2))*2,s=[n-7];for(let i=1;i{l();var art=s1().getSymbolSize,PAe=7;NAe.getPositions=function(t){let r=art(t);return[[0,0],[r-PAe,0],[0,r-PAe]]}});var OAe=_e(Wr=>{l();Wr.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var h2={N1:3,N2:3,N3:40,N4:10};Wr.isValid=function(t){return t!=null&&t!==""&&!isNaN(t)&&t>=0&&t<=7};Wr.from=function(t){return Wr.isValid(t)?parseInt(t,10):void 0};Wr.getPenaltyN1=function(t){let r=t.size,n=0,o=0,s=0,i=null,a=null;for(let c=0;c=5&&(n+=h2.N1+(o-5)),i=d,o=1),d=t.get(u,c),d===a?s++:(s>=5&&(n+=h2.N1+(s-5)),a=d,s=1)}o>=5&&(n+=h2.N1+(o-5)),s>=5&&(n+=h2.N1+(s-5))}return n};Wr.getPenaltyN2=function(t){let r=t.size,n=0;for(let o=0;o=10&&(o===1488||o===93)&&n++,s=s<<1&2047|t.get(a,i),a>=10&&(s===1488||s===93)&&n++}return n*h2.N3};Wr.getPenaltyN4=function(t){let r=0,n=t.data.length;for(let s=0;s{l();var i1=NN(),ON=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],BN=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Uq.getBlocksCount=function(t,r){switch(r){case i1.L:return ON[(t-1)*4+0];case i1.M:return ON[(t-1)*4+1];case i1.Q:return ON[(t-1)*4+2];case i1.H:return ON[(t-1)*4+3];default:return}};Uq.getTotalCodewordsCount=function(t,r){switch(r){case i1.L:return BN[(t-1)*4+0];case i1.M:return BN[(t-1)*4+1];case i1.Q:return BN[(t-1)*4+2];case i1.H:return BN[(t-1)*4+3];default:return}}});var BAe=_e(UN=>{l();var YE=new Uint8Array(512),kN=new Uint8Array(256);(function(){let t=1;for(let r=0;r<255;r++)YE[r]=t,kN[t]=r,t<<=1,t&256&&(t^=285);for(let r=255;r<512;r++)YE[r]=YE[r-255]})();UN.log=function(t){if(t<1)throw new Error("log("+t+")");return kN[t]};UN.exp=function(t){return YE[t]};UN.mul=function(t,r){return t===0||r===0?0:YE[kN[t]+kN[r]]}});var kAe=_e(JE=>{l();var Lq=BAe();JE.mul=function(t,r){let n=new Uint8Array(t.length+r.length-1);for(let o=0;o=0;){let o=n[0];for(let i=0;i{l();var UAe=kAe();function Mq(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Mq.prototype.initialize=function(t){this.degree=t,this.genPoly=UAe.generateECPolynomial(this.degree)};Mq.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(t.length+this.degree);r.set(t);let n=UAe.mod(r,this.genPoly),o=this.degree-n.length;if(o>0){let s=new Uint8Array(this.degree);return s.set(n,o),s}return n};DAe.exports=Mq});var Hq=_e(MAe=>{l();MAe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}});var $q=_e(Zp=>{l();var HAe="[0-9]+",lrt="[A-Z $%*+\\-./:]+",QE="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";QE=QE.replace(/u/g,"\\u");var urt="(?:(?![A-Z0-9 $%*+\\-./:]|"+QE+`)(?:.|[\r ]))+`;Zp.KANJI=new RegExp(QE,"g");Zp.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Zp.BYTE=new RegExp(urt,"g");Zp.NUMERIC=new RegExp(HAe,"g");Zp.ALPHANUMERIC=new RegExp(lrt,"g");var drt=new RegExp("^"+QE+"$"),frt=new RegExp("^"+HAe+"$"),prt=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Zp.testKanji=function(t){return drt.test(t)};Zp.testNumeric=function(t){return frt.test(t)};Zp.testAlphanumeric=function(t){return prt.test(t)}});var a1=_e(Qn=>{l();var hrt=Hq(),Fq=$q();Qn.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};Qn.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};Qn.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};Qn.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};Qn.MIXED={bit:-1};Qn.getCharCountIndicator=function(t,r){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!hrt.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?t.ccBits[0]:r<27?t.ccBits[1]:t.ccBits[2]};Qn.getBestModeForData=function(t){return Fq.testNumeric(t)?Qn.NUMERIC:Fq.testAlphanumeric(t)?Qn.ALPHANUMERIC:Fq.testKanji(t)?Qn.KANJI:Qn.BYTE};Qn.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")};Qn.isValid=function(t){return t&&t.bit&&t.ccBits};function mrt(e){if(typeof e!="string")throw new Error("Param is not a string");switch(e.toLowerCase()){case"numeric":return Qn.NUMERIC;case"alphanumeric":return Qn.ALPHANUMERIC;case"kanji":return Qn.KANJI;case"byte":return Qn.BYTE;default:throw new Error("Unknown mode: "+e)}}Qn.from=function(t,r){if(Qn.isValid(t))return t;try{return mrt(t)}catch{return r}}});var jAe=_e(m2=>{l();var DN=s1(),grt=Dq(),$Ae=NN(),c1=a1(),zq=Hq(),zAe=7973,FAe=DN.getBCHDigit(zAe);function yrt(e,t,r){for(let n=1;n<=40;n++)if(t<=m2.getCapacity(n,r,e))return n}function VAe(e,t){return c1.getCharCountIndicator(e,t)+4}function wrt(e,t){let r=0;return e.forEach(function(n){let o=VAe(n.mode,t);r+=o+n.getBitsLength()}),r}function brt(e,t){for(let r=1;r<=40;r++)if(wrt(e,r)<=m2.getCapacity(r,t,c1.MIXED))return r}m2.from=function(t,r){return zq.isValid(t)?parseInt(t,10):r};m2.getCapacity=function(t,r,n){if(!zq.isValid(t))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=c1.BYTE);let o=DN.getSymbolTotalCodewords(t),s=grt.getTotalCodewordsCount(t,r),i=(o-s)*8;if(n===c1.MIXED)return i;let a=i-VAe(n,t);switch(n){case c1.NUMERIC:return Math.floor(a/10*3);case c1.ALPHANUMERIC:return Math.floor(a/11*2);case c1.KANJI:return Math.floor(a/13);case c1.BYTE:default:return Math.floor(a/8)}};m2.getBestVersionForData=function(t,r){let n,o=$Ae.from(r,$Ae.M);if(Array.isArray(t)){if(t.length>1)return brt(t,o);if(t.length===0)return 1;n=t[0]}else n=t;return yrt(n.mode,n.getLength(),o)};m2.getEncodedBits=function(t){if(!zq.isValid(t)||t<7)throw new Error("Invalid QR Code version");let r=t<<12;for(;DN.getBCHDigit(r)-FAe>=0;)r^=zAe<{l();var Vq=s1(),WAe=1335,xrt=21522,qAe=Vq.getBCHDigit(WAe);KAe.getEncodedBits=function(t,r){let n=t.bit<<3|r,o=n<<10;for(;Vq.getBCHDigit(o)-qAe>=0;)o^=WAe<{l();var vrt=a1();function qx(e){this.mode=vrt.NUMERIC,this.data=e.toString()}qx.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)};qx.prototype.getLength=function(){return this.data.length};qx.prototype.getBitsLength=function(){return qx.getBitsLength(this.data.length)};qx.prototype.write=function(t){let r,n,o;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),o=parseInt(n,10),t.put(o,10);let s=this.data.length-r;s>0&&(n=this.data.substr(r),o=parseInt(n,10),t.put(o,s*3+1))};GAe.exports=qx});var QAe=_e((M$r,JAe)=>{l();var Ert=a1(),jq=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Wx(e){this.mode=Ert.ALPHANUMERIC,this.data=e}Wx.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};Wx.prototype.getLength=function(){return this.data.length};Wx.prototype.getBitsLength=function(){return Wx.getBitsLength(this.data.length)};Wx.prototype.write=function(t){let r;for(r=0;r+2<=this.data.length;r+=2){let n=jq.indexOf(this.data[r])*45;n+=jq.indexOf(this.data[r+1]),t.put(n,11)}this.data.length%2&&t.put(jq.indexOf(this.data[r]),6)};JAe.exports=Wx});var eCe=_e(($$r,XAe)=>{l();var Art=a1();function Kx(e){this.mode=Art.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}Kx.getBitsLength=function(t){return t*8};Kx.prototype.getLength=function(){return this.data.length};Kx.prototype.getBitsLength=function(){return Kx.getBitsLength(this.data.length)};Kx.prototype.write=function(e){for(let t=0,r=this.data.length;t{l();var Crt=a1(),Srt=s1();function Zx(e){this.mode=Crt.KANJI,this.data=e}Zx.getBitsLength=function(t){return t*13};Zx.prototype.getLength=function(){return this.data.length};Zx.prototype.getBitsLength=function(){return Zx.getBitsLength(this.data.length)};Zx.prototype.write=function(e){let t;for(t=0;t=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),e.put(r,13)}};tCe.exports=Zx});var uCe=_e(Gx=>{l();var gr=a1(),sCe=YAe(),iCe=QAe(),aCe=eCe(),cCe=rCe(),XE=$q(),LN=s1(),Irt=Rj();function nCe(e){return unescape(encodeURIComponent(e)).length}function eA(e,t,r){let n=[],o;for(;(o=e.exec(r))!==null;)n.push({data:o[0],index:o.index,mode:t,length:o[0].length});return n}function lCe(e){let t=eA(XE.NUMERIC,gr.NUMERIC,e),r=eA(XE.ALPHANUMERIC,gr.ALPHANUMERIC,e),n,o;return LN.isKanjiModeEnabled()?(n=eA(XE.BYTE,gr.BYTE,e),o=eA(XE.KANJI,gr.KANJI,e)):(n=eA(XE.BYTE_KANJI,gr.BYTE,e),o=[]),t.concat(r,n,o).sort(function(i,a){return i.index-a.index}).map(function(i){return{data:i.data,mode:i.mode,length:i.length}})}function qq(e,t){switch(t){case gr.NUMERIC:return sCe.getBitsLength(e);case gr.ALPHANUMERIC:return iCe.getBitsLength(e);case gr.KANJI:return cCe.getBitsLength(e);case gr.BYTE:return aCe.getBitsLength(e)}}function Trt(e){return e.reduce(function(t,r){let n=t.length-1>=0?t[t.length-1]:null;return n&&n.mode===r.mode?(t[t.length-1].data+=r.data,t):(t.push(r),t)},[])}function _rt(e){let t=[];for(let r=0;r{l();var HN=s1(),Wq=NN(),Nrt=SAe(),Rrt=TAe(),Ort=_Ae(),Brt=RAe(),Gq=OAe(),Yq=Dq(),krt=LAe(),MN=jAe(),Urt=ZAe(),Drt=a1(),Kq=uCe();function Lrt(e,t){let r=e.size,n=Brt.getPositions(t);for(let o=0;o=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?e.set(s+a,i+c,!0,!0):e.set(s+a,i+c,!1,!0))}}function Mrt(e){let t=e.size;for(let r=8;r>a&1)===1,e.set(o,s,i,!0),e.set(s,o,i,!0)}function Zq(e,t,r){let n=e.size,o=Urt.getEncodedBits(t,r),s,i;for(s=0;s<15;s++)i=(o>>s&1)===1,s<6?e.set(s,8,i,!0):s<8?e.set(s+1,8,i,!0):e.set(n-15+s,8,i,!0),s<8?e.set(8,n-s-1,i,!0):s<9?e.set(8,15-s-1+1,i,!0):e.set(8,15-s-1,i,!0);e.set(n-8,8,1,!0)}function Frt(e,t){let r=e.size,n=-1,o=r-1,s=7,i=0;for(let a=r-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!e.isReserved(o,a-c)){let u=!1;i>>s&1)===1),e.set(o,a-c,u),s--,s===-1&&(i++,s=7)}if(o+=n,o<0||r<=o){o-=n,n=-n;break}}}function zrt(e,t,r){let n=new Nrt;r.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),Drt.getCharCountIndicator(c.mode,e)),c.write(n)});let o=HN.getSymbolTotalCodewords(e),s=Yq.getTotalCodewordsCount(e,t),i=(o-s)*8;for(n.getLengthInBits()+4<=i&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(i-n.getLengthInBits())/8;for(let c=0;c=7&&$rt(c,t),Frt(c,i),isNaN(n)&&(n=Gq.getBestMask(c,Zq.bind(null,c,r))),Gq.applyMask(n,c),Zq(c,r,n),{modules:c,version:t,errorCorrectionLevel:r,maskPattern:n,segments:o}}dCe.create=function(t,r){if(typeof t>"u"||t==="")throw new Error("No input text");let n=Wq.M,o,s;return typeof r<"u"&&(n=Wq.from(r.errorCorrectionLevel,Wq.M),o=MN.from(r.version),s=Gq.from(r.maskPattern),r.toSJISFunc&&HN.setToSJISFunction(r.toSJISFunc)),jrt(t,o,n,s)}});var Jq=_e(g2=>{l();function pCe(e){if(typeof e=="number"&&(e=e.toString()),typeof e!="string")throw new Error("Color should be defined as hex string");let t=e.slice().replace("#","").split("");if(t.length<3||t.length===5||t.length>8)throw new Error("Invalid hex color: "+e);(t.length===3||t.length===4)&&(t=Array.prototype.concat.apply([],t.map(function(n){return[n,n]}))),t.length===6&&t.push("F","F");let r=parseInt(t.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+t.slice(0,6).join("")}}g2.getOptions=function(t){t||(t={}),t.color||(t.color={});let r=typeof t.margin>"u"||t.margin===null||t.margin<0?4:t.margin,n=t.width&&t.width>=21?t.width:void 0,o=t.scale||4;return{width:n,scale:n?4:o,margin:r,color:{dark:pCe(t.color.dark||"#000000ff"),light:pCe(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}};g2.getScale=function(t,r){return r.width&&r.width>=t+r.margin*2?r.width/(t+r.margin*2):r.scale};g2.getImageWidth=function(t,r){let n=g2.getScale(t,r);return Math.floor((t+r.margin*2)*n)};g2.qrToImageData=function(t,r,n){let o=r.modules.size,s=r.modules.data,i=g2.getScale(o,n),a=Math.floor((o+n.margin*2)*i),c=n.margin*i,u=[n.color.light,n.color.dark];for(let d=0;d=c&&f>=c&&d{l();var Qq=Jq();function qrt(e,t,r){e.clearRect(0,0,t.width,t.height),t.style||(t.style={}),t.height=r,t.width=r,t.style.height=r+"px",t.style.width=r+"px"}function Wrt(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}$N.render=function(t,r,n){let o=n,s=r;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),r||(s=Wrt()),o=Qq.getOptions(o);let i=Qq.getImageWidth(t.modules.size,o),a=s.getContext("2d"),c=a.createImageData(i,i);return Qq.qrToImageData(c.data,t,o),qrt(a,s,i),a.putImageData(c,0,0),s};$N.renderToDataURL=function(t,r,n){let o=n;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),o||(o={});let s=$N.render(t,r,o),i=o.type||"image/png",a=o.rendererOpts||{};return s.toDataURL(i,a.quality)}});var yCe=_e(gCe=>{l();var Krt=Jq();function mCe(e,t){let r=e.a/255,n=t+'="'+e.hex+'"';return r<1?n+" "+t+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function Xq(e,t,r){let n=e+t;return typeof r<"u"&&(n+=" "+r),n}function Zrt(e,t,r){let n="",o=0,s=!1,i=0;for(let a=0;a0&&c>0&&e[a-1]||(n+=s?Xq("M",c+r,.5+u+r):Xq("m",o,0),o=0,s=!1),c+1':"",u="',d='viewBox="0 0 '+a+" "+a+'"',p=''+c+u+` `;return typeof n=="function"&&n(null,p),p}});var bCe=_e(tA=>{l();var Grt=EAe(),eW=fCe(),wCe=hCe(),Yrt=yCe();function tW(e,t,r,n,o){let s=[].slice.call(arguments,1),i=s.length,a=typeof s[i-1]=="function";if(!a&&!Grt())throw new Error("Callback required as last argument");if(a){if(i<2)throw new Error("Too few arguments provided");i===2?(o=r,r=t,t=n=void 0):i===3&&(t.getContext&&typeof o>"u"?(o=n,n=void 0):(o=n,n=r,r=t,t=void 0))}else{if(i<1)throw new Error("Too few arguments provided");return i===1?(r=t,t=n=void 0):i===2&&!t.getContext&&(n=r,r=t,t=void 0),new Promise(function(c,u){try{let d=eW.create(r,n);c(e(d,t,n))}catch(d){u(d)}})}try{let c=eW.create(r,n);o(null,e(c,t,n))}catch(c){o(c)}}tA.create=eW.create;tA.toCanvas=tW.bind(null,wCe.render);tA.toDataURL=tW.bind(null,wCe.renderToDataURL);tA.toString=tW.bind(null,function(e,t,r){return Yrt.render(e,r)})});l();l();var yAe=Ht(ks(),1);l();jN();var mf=Ht(jd(),1),Dc=Ht(C2(),1),eQ=Ht(JN(),1);l();l();var hA=BigInt(4294967295),LW=BigInt(32);function QN(e,t=!1){return t?{h:Number(e&hA),l:Number(e>>LW&hA)}:{h:Number(e>>LW&hA)|0,l:Number(e&hA)|0}}function mA(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;se>>>r,eR=(e,t,r)=>e<<32-r|t>>>r,Nl=(e,t,r)=>e>>>r|t<<32-r,Rl=(e,t,r)=>e<<32-r|t>>>r,u1=(e,t,r)=>e<<64-r|t>>>r-32,d1=(e,t,r)=>e>>>r-32|t<<64-r,MW=(e,t)=>t,HW=(e,t)=>e,$W=(e,t,r)=>e<>>32-r,FW=(e,t,r)=>t<>>32-r,zW=(e,t,r)=>t<>>64-r,VW=(e,t,r)=>e<>>64-r;function ra(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Xx=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),e8=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,jW=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),qW=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,WW=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),KW=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;l();l();var f1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Wd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Jo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Cn(e,...t){if(!Wd(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function p1(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Jo(e.outputLen),Jo(e.blockLen)}function Fa(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function S2(e,t){Cn(e);let r=t.outputLen;if(e.length>>t}var YW=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function JW(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var Bl=YW?e=>e:e=>JW(e);function OSe(e){for(let t=0;te:OSe,QW=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",BSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function za(e){if(Cn(e),QW)return e.toHex();let t="";for(let r=0;r=qd._0&&e<=qd._9)return e-qd._0;if(e>=qd.A&&e<=qd.F)return e-(qd.A-10);if(e>=qd.a&&e<=qd.f)return e-(qd.a-10)}function m1(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(QW)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;oe().update(Qo(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function XW(e){let t=(n,o)=>e(o).update(Qo(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Us(e=32){if(f1&&typeof f1.getRandomValues=="function")return f1.getRandomValues(new Uint8Array(e));if(f1&&typeof f1.randomBytes=="function")return Uint8Array.from(f1.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var kSe=BigInt(0),t8=BigInt(1),USe=BigInt(2),DSe=BigInt(7),LSe=BigInt(256),MSe=BigInt(113),rK=[],nK=[],oK=[];for(let e=0,t=t8,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],rK.push(2*(5*n+r)),nK.push((e+1)*(e+2)/2%64);let o=kSe;for(let s=0;s<7;s++)t=(t<>DSe)*MSe)%LSe,t&USe&&(o^=t8<<(t8<r>32?zW(e,t,r):$W(e,t,r),tK=(e,t,r)=>r>32?VW(e,t,r):FW(e,t,r);function FSe(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,c=(i+2)%10,u=r[c],d=r[c+1],f=eK(u,d,1)^r[a],p=tK(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[i+h]^=f,e[i+h+1]^=p}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=nK[i],c=eK(o,s,a),u=tK(o,s,a),d=rK[i];o=e[d],s=e[d+1],e[d]=c,e[d+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=HSe[n],e[1]^=$Se[n]}fo(r)}var rR=class e extends Ol{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Jo(n),!(0=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Jo(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(S2(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,fo(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},zSe=(e,t,r)=>g1(()=>new rR(t,e,r));var yA=zSe(1,136,256/8);l();l();l();l();var iK="0.1.1";function aK(){return iK}var nr=class e extends Error{constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=`https://oxlib.sh${o??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o?["",n?`Details: ${n}`:void 0,o?`See: ${i}`:void 0]:[]].filter(c=>typeof c=="string").join(` -`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${aK()}`}),this.cause=r.cause,this.details=n,this.docs=i,this.docsPath=o,this.shortMessage=t}walk(t){return cK(this,t)}};function cK(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?cK(e.cause,t):t?null:e}l();l();function VSe(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function lK(e,t,r){return e&t^~e&r}function uK(e,t,r){return e&t^e&r^t&r}var r8=class extends Ol{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=gA(this.buffer)}update(t){Fa(this),t=Qo(t),Cn(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>>3,w=Rc(h,17)^Rc(h,19)^h>>>10;Gp[f]=w+Gp[f-7]+y+Gp[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=Rc(a,6)^Rc(a,11)^Rc(a,25),h=d+p+lK(a,c,u)+jSe[f]+Gp[f]|0,w=(Rc(n,2)^Rc(n,13)^Rc(n,22))+uK(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){fo(Gp)}destroy(){this.set(0,0,0,0,0,0,0,0),fo(this.buffer)}};var dK=mA(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),qSe=dK[0],WSe=dK[1],Yp=new Uint32Array(80),Jp=new Uint32Array(80),n8=class extends r8{constructor(t=64){super(128,t,16,!1),this.Ah=Do[0]|0,this.Al=Do[1]|0,this.Bh=Do[2]|0,this.Bl=Do[3]|0,this.Ch=Do[4]|0,this.Cl=Do[5]|0,this.Dh=Do[6]|0,this.Dl=Do[7]|0,this.Eh=Do[8]|0,this.El=Do[9]|0,this.Fh=Do[10]|0,this.Fl=Do[11]|0,this.Gh=Do[12]|0,this.Gl=Do[13]|0,this.Hh=Do[14]|0,this.Hl=Do[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)Yp[E]=t.getUint32(r),Jp[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Yp[E-15]|0,_=Jp[E-15]|0,O=Nl(S,_,1)^Nl(S,_,8)^XN(S,_,7),D=Rl(S,_,1)^Rl(S,_,8)^eR(S,_,7),M=Yp[E-2]|0,N=Jp[E-2]|0,L=Nl(M,N,19)^u1(M,N,61)^XN(M,N,6),P=Rl(M,N,19)^d1(M,N,61)^eR(M,N,6),R=jW(D,P,Jp[E-7],Jp[E-16]),I=qW(R,O,L,Yp[E-7],Yp[E-16]);Yp[E]=I|0,Jp[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Nl(f,p,14)^Nl(f,p,18)^u1(f,p,41),_=Rl(f,p,14)^Rl(f,p,18)^d1(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=WW(T,_,D,WSe[E],Jp[E]),N=KW(M,v,S,O,qSe[E],Yp[E]),L=M|0,P=Nl(n,o,28)^u1(n,o,34)^u1(n,o,39),R=Rl(n,o,28)^d1(n,o,34)^d1(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=ra(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Xx(L,R,B);n=e8(C,N,P,I),o=C|0}({h:n,l:o}=ra(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ra(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ra(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=ra(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=ra(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=ra(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=ra(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=ra(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){fo(Yp,Jp)}destroy(){fo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},nR=class extends n8{constructor(){super(48),this.Ah=Uo[0]|0,this.Al=Uo[1]|0,this.Bh=Uo[2]|0,this.Bl=Uo[3]|0,this.Ch=Uo[4]|0,this.Cl=Uo[5]|0,this.Dh=Uo[6]|0,this.Dl=Uo[7]|0,this.Eh=Uo[8]|0,this.El=Uo[9]|0,this.Fh=Uo[10]|0,this.Fl=Uo[11]|0,this.Gh=Uo[12]|0,this.Gl=Uo[13]|0,this.Hh=Uo[14]|0,this.Hl=Uo[15]|0}};var Xo=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);var oR=class extends n8{constructor(){super(32),this.Ah=Xo[0]|0,this.Al=Xo[1]|0,this.Bh=Xo[2]|0,this.Bl=Xo[3]|0,this.Ch=Xo[4]|0,this.Cl=Xo[5]|0,this.Dh=Xo[6]|0,this.Dl=Xo[7]|0,this.Eh=Xo[8]|0,this.El=Xo[9]|0,this.Fh=Xo[10]|0,this.Fl=Xo[11]|0,this.Gh=Xo[12]|0,this.Gl=Xo[13]|0,this.Hh=Xo[14]|0,this.Hl=Xo[15]|0}},Zd=g1(()=>new wA);var bA=g1(()=>new n8),fK=g1(()=>new nR),pK=g1(()=>new oR);var o8=Zd;l();l();var cR=BigInt(0),aR=BigInt(1);function T2(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function lR(e){if(!T2(e))throw new Error("Uint8Array expected")}function _2(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function s8(e){let t=e.toString(16);return t.length&1?"0"+t:t}function gK(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?cR:BigInt("0x"+e)}var yK=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",KSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function P2(e){if(lR(e),yK)return e.toHex();let t="";for(let r=0;r=Gd._0&&e<=Gd._9)return e-Gd._0;if(e>=Gd.A&&e<=Gd.F)return e-(Gd.A-10);if(e>=Gd.a&&e<=Gd.f)return e-(Gd.a-10)}function i8(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(yK)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;otypeof e=="bigint"&&cR<=e;function xA(e,t,r){return sR(e)&&sR(t)&&sR(r)&&t<=e&&ecR;e>>=aR,t+=1);return t}var b1=e=>(aR<new Uint8Array(e),mK=e=>Uint8Array.from(e);function bK(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=iR(e),o=iR(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=iR(0))=>{o=a(mK([0]),f),n=a(),f.length!==0&&(o=a(mK([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}var ZSe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||T2(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function x1(e,t,r={}){let n=(o,s,i)=>{let a=ZSe[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function fR(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}l();l();function xK(e,t){if(pR(e)>t)throw new vA({givenSize:pR(e),maxSize:t})}var Jd={zero:48,nine:57,A:65,F:70,a:97,f:102};function hR(e){if(e>=Jd.zero&&e<=Jd.nine)return e-Jd.zero;if(e>=Jd.A&&e<=Jd.F)return e-(Jd.A-10);if(e>=Jd.a&&e<=Jd.f)return e-(Jd.a-10)}function vK(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new EA({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;st)throw new CA({givenSize:Va(e),maxSize:t})}function EK(e,t){if(typeof t=="number"&&t>0&&t>Va(e)-1)throw new c8({offset:t,position:"start",size:Va(e)})}function AK(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Va(e)!==r-t)throw new c8({offset:r,position:"end",size:Va(e)})}function mR(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new SA({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function CK(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;stypeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+YSe:o,r)}var JSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function QSe(e,t={}){let{strict:r=!1}=t;if(!e)throw new IA(e);if(typeof e!="string")throw new IA(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new TA(e);if(!e.startsWith("0x"))throw new TA(e)}function _A(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Ul(e){return e instanceof Uint8Array?na(e):Array.isArray(e)?na(new Uint8Array(e)):e}function na(e,t={}){let r="";for(let o=0;os||othis.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}};var oIe={checksum:new PA(8192)},NA=oIe.checksum;l();function NK(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new RA({prefix:n,cause:new AR});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new RA({prefix:n,cause:new ER});return}throw new vR({publicKey:e})}function SR(e){let t=(()=>{if(bR(e))return RK(e);if(TK(e))return sIe(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return NK(t),t}function sIe(e){return RK(na(e))}function RK(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new CR({publicKey:e});if(e.length===130){let n=BigInt(Oc(e,0,32)),o=BigInt(Oc(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(Oc(e,0,1)),o=BigInt(Oc(e,1,33)),s=BigInt(Oc(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(Oc(e,0,1)),r=BigInt(Oc(e,1,33));return{prefix:t,x:r}}function OK(e,t={}){return u8(d8(e,t))}function d8(e,t={}){NK(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return _A(s?oa(r,{size:1}):"0x",oa(n,{size:32}),typeof o=="bigint"?oa(o,{size:32}):"0x")}var vR=class extends nr{constructor({publicKey:t}){super(`Value \`${Qp(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},RA=class extends nr{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},ER=class extends nr{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},AR=class extends nr{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},CR=class extends nr{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Va(Ul(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};var iIe=/^0x[a-fA-F0-9]{40}$/;function OA(e,t={}){let{strict:r=!0}=t;if(!iIe.test(e))throw new BA({address:e,cause:new TR});if(r){if(e.toLowerCase()===e)return;if(BK(e)!==e)throw new BA({address:e,cause:new _R})}}function BK(e){if(NA.has(e))return NA.get(e);OA(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=xR(IK(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return NA.set(e,o),o}function aIe(e,t={}){let{checksum:r=!1}=t;return OA(e),r?BK(e):e}function kK(e,t={}){let r=xR(`0x${d8(e).slice(4)}`).substring(26);return aIe(`0x${r}`,t)}function UK(e,t){return OA(e,{strict:!1}),OA(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}var BA=class extends nr{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},TR=class extends nr{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},_R=class extends nr{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}};l();var Tot=2n**(8n-1n)-1n,_ot=2n**(16n-1n)-1n,Pot=2n**(24n-1n)-1n,Not=2n**(32n-1n)-1n,Rot=2n**(40n-1n)-1n,Oot=2n**(48n-1n)-1n,Bot=2n**(56n-1n)-1n,kot=2n**(64n-1n)-1n,Uot=2n**(72n-1n)-1n,Dot=2n**(80n-1n)-1n,Lot=2n**(88n-1n)-1n,Mot=2n**(96n-1n)-1n,Hot=2n**(104n-1n)-1n,$ot=2n**(112n-1n)-1n,Fot=2n**(120n-1n)-1n,zot=2n**(128n-1n)-1n,Vot=2n**(136n-1n)-1n,jot=2n**(144n-1n)-1n,qot=2n**(152n-1n)-1n,Wot=2n**(160n-1n)-1n,Kot=2n**(168n-1n)-1n,Zot=2n**(176n-1n)-1n,Got=2n**(184n-1n)-1n,Yot=2n**(192n-1n)-1n,Jot=2n**(200n-1n)-1n,Qot=2n**(208n-1n)-1n,Xot=2n**(216n-1n)-1n,est=2n**(224n-1n)-1n,tst=2n**(232n-1n)-1n,rst=2n**(240n-1n)-1n,nst=2n**(248n-1n)-1n,ost=2n**(256n-1n)-1n,sst=-(2n**(8n-1n)),ist=-(2n**(16n-1n)),ast=-(2n**(24n-1n)),cst=-(2n**(32n-1n)),lst=-(2n**(40n-1n)),ust=-(2n**(48n-1n)),dst=-(2n**(56n-1n)),fst=-(2n**(64n-1n)),pst=-(2n**(72n-1n)),hst=-(2n**(80n-1n)),mst=-(2n**(88n-1n)),gst=-(2n**(96n-1n)),yst=-(2n**(104n-1n)),wst=-(2n**(112n-1n)),bst=-(2n**(120n-1n)),xst=-(2n**(128n-1n)),vst=-(2n**(136n-1n)),Est=-(2n**(144n-1n)),Ast=-(2n**(152n-1n)),Cst=-(2n**(160n-1n)),Sst=-(2n**(168n-1n)),Ist=-(2n**(176n-1n)),Tst=-(2n**(184n-1n)),_st=-(2n**(192n-1n)),Pst=-(2n**(200n-1n)),Nst=-(2n**(208n-1n)),Rst=-(2n**(216n-1n)),Ost=-(2n**(224n-1n)),Bst=-(2n**(232n-1n)),kst=-(2n**(240n-1n)),Ust=-(2n**(248n-1n)),Dst=-(2n**(256n-1n)),Lst=2n**8n-1n,Mst=2n**16n-1n,Hst=2n**24n-1n,$st=2n**32n-1n,Fst=2n**40n-1n,zst=2n**48n-1n,Vst=2n**56n-1n,jst=2n**64n-1n,qst=2n**72n-1n,Wst=2n**80n-1n,Kst=2n**88n-1n,Zst=2n**96n-1n,Gst=2n**104n-1n,Yst=2n**112n-1n,Jst=2n**120n-1n,Qst=2n**128n-1n,Xst=2n**136n-1n,eit=2n**144n-1n,tit=2n**152n-1n,rit=2n**160n-1n,nit=2n**168n-1n,oit=2n**176n-1n,sit=2n**184n-1n,iit=2n**192n-1n,ait=2n**200n-1n,cit=2n**208n-1n,lit=2n**216n-1n,uit=2n**224n-1n,dit=2n**232n-1n,fit=2n**240n-1n,pit=2n**248n-1n,PR=2n**256n-1n;var zA={};Te(zA,{InvalidRError:()=>LA,InvalidSError:()=>MA,InvalidSerializedSizeError:()=>DA,InvalidVError:()=>HA,InvalidYParityError:()=>C1,MissingPropertiesError:()=>O2,assert:()=>$A,extract:()=>CIe,from:()=>WR,fromBytes:()=>nZ,fromDerBytes:()=>SIe,fromDerHex:()=>oZ,fromHex:()=>qR,fromLegacy:()=>sZ,fromRpc:()=>iZ,fromTuple:()=>IIe,toBytes:()=>TIe,toDerBytes:()=>_Ie,toDerHex:()=>PIe,toHex:()=>aZ,toLegacy:()=>NIe,toRpc:()=>RIe,toTuple:()=>OIe,vToYParity:()=>FA,validate:()=>BIe,yParityToV:()=>KR});l();l();l();l();var kA=class extends Ol{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,p1(t);let n=Qo(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew kA(e,t).update(r).digest();Xp.create=(e,t)=>new kA(e,t);l();l();l();var Ds=BigInt(0),ts=BigInt(1),A1=BigInt(2),cIe=BigInt(3),HK=BigInt(4),$K=BigInt(5),FK=BigInt(8);function es(e,t){let r=e%t;return r>=Ds?r:t+r}function sa(e,t,r){let n=e;for(;t-- >Ds;)n*=n,n%=r;return n}function UA(e,t){if(e===Ds)throw new Error("invert: expected non-zero number");if(t<=Ds)throw new Error("invert: expected positive modulus, got "+t);let r=es(e,t),n=t,o=Ds,s=ts,i=ts,a=Ds;for(;r!==Ds;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ts)throw new Error("invert: does not exist");return es(o,t)}function zK(e,t){let r=(e.ORDER+ts)/HK,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function lIe(e,t){let r=(e.ORDER-$K)/FK,n=e.mul(t,A1),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,A1),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function uIe(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return zK;let s=o.pow(n,t),i=(t+ts)/A1;return function(c,u){if(c.is0(u))return u;if(MK(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ts<(n[o]="function",n),t);return x1(e,r)}function pIe(e,t,r){if(rDs;)r&ts&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ts;return n}function RR(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function MK(e,t){let r=(e.ORDER-ts)/A1,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function OR(e,t){t!==void 0&&Jo(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function f8(e,t,r=!1,n={}){if(e<=Ds)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=OR(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:b1(o),ZERO:Ds,ONE:ts,create:c=>es(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ds<=c&&cc===Ds,isOdd:c=>(c&ts)===ts,neg:c=>es(-c,e),eql:(c,u)=>c===u,sqr:c=>es(c*c,e),add:(c,u)=>es(c+u,e),sub:(c,u)=>es(c-u,e),mul:(c,u)=>es(c*u,e),pow:(c,u)=>pIe(a,c,u),div:(c,u)=>es(c*UA(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>UA(c,e),sqrt:n.sqrt||(c=>(i||(i=dIe(e)),i(a,c))),toBytes:c=>r?dR(c,s):y1(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?uR(c):Yd(c)},invertBatch:c=>RR(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function VK(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function BR(e){let t=VK(e);return t+Math.ceil(t/2)}function jK(e,t,r=!1){let n=e.length,o=VK(t),s=BR(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?uR(e):Yd(e),a=es(i,t-ts)+ts;return r?dR(a,o):y1(a,o)}var qK=BigInt(0),MR=BigInt(1);function kR(e,t){let r=t.negate();return e?r:t}function KK(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function UR(e,t){KK(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=b1(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function WK(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=MR);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function hIe(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function mIe(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var DR=new WeakMap,ZK=new WeakMap;function LR(e){return ZK.get(e)||1}function GK(e,t){return{constTimeNegate:kR,hasPrecomputes(r){return LR(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>qK;)n&MR&&(o=o.add(s)),s=s.double(),n>>=MR;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=UR(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=b1(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{let{Err:r}=Qd;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=s8(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?s8(o.length/2|128):"";return s8(e)+s+o+t},decode(e,t){let{Err:r}=Qd,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Qd;if(e{let O=S.toAffine();return a8(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,FR),yIe),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return xA(E,po,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(T2(E)&&(E=P2(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:Yd(mi("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=es(M,D)),w1("private key",M,po,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=fR((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=fR(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=RR(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(mi("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return YK(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,FR),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,FR),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;w1("scalar",S,Xd,O);let D=w.ZERO;if(S===Xd)return D;if(this.is0()||S===po)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>Xd||P>Xd;)N&po&&(R=R.add(B)),P&po&&(I=I.add(B)),B=B.double(),N>>=po,P>>=po;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;w1("scalar",S,po,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===Xd||P===po||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===po)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===po?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return _2("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return _2("isCompressed",S),P2(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=GK(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function bIe(e){let t=HR(e);return x1(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function QK(e){let t=bIe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return es(C,n)}function u(C){return UA(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=wIe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=a8;return _2("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=Yd(H);if(!xA(k,po,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&po)===po;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>po;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>Yd(C.slice(A,U));class v{constructor(A,U,H){w1("r",A,po,n),w1("s",U,po,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=mi("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=Qd.toSig(mi("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(mi("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+$R(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return i8(this.toDERHex())}toDERHex(){return Qd.hexFromSig(this)}toCompactRawBytes(){return i8(this.toCompactHex())}toCompactHex(){let A=o;return $R(this.r,A)+$R(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=BR(t.n);return jK(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=mi("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=Yd(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=b1(s);function N(C){return w1("num < 2^"+s,C,Xd,M),y1(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=mi("msgHash",C),JK(U),j&&(C=mi("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(mi("extraEntropy",ye))}let pe=a8(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===Xd)return;let ur=c(Et*c(me+At*te));if(ur===Xd)return;let _r=(kt.x===At?0:2)|Number(kt.y&po),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return bK(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=mi("msgHash",A),U=mi("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(JK(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||T2(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof Qd.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}function xIe(e){return{hash:e,hmac:(t,...r)=>Xp(e,t,ko(...r)),randomBytes:Us}}function XK(e,t){let r=n=>QK({...e,...xIe(n)});return{...r(t),create:r}}var rZ=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),eZ=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),vIe=BigInt(0),EIe=BigInt(1),VR=BigInt(2),tZ=(e,t)=>(e+t/VR)/t;function AIe(e){let t=rZ,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=sa(d,r,t)*d%t,p=sa(f,r,t)*d%t,h=sa(p,VR,t)*u%t,y=sa(h,o,t)*h%t,w=sa(y,s,t)*y%t,x=sa(w,a,t)*w%t,v=sa(x,c,t)*x%t,T=sa(v,a,t)*w%t,E=sa(T,r,t)*d%t,S=sa(E,i,t)*y%t,_=sa(S,n,t)*u%t,O=sa(_,VR,t);if(!jR.eql(jR.sqr(O),e))throw new Error("Cannot find square root");return O}var jR=f8(rZ,void 0,void 0,{sqrt:AIe}),ia=XK({a:vIe,b:BigInt(7),Fp:jR,n:eZ,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=eZ,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-EIe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=tZ(s*e,t),c=tZ(-n*e,t),u=es(e-a*r-c*o,t),d=es(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},Zd);function $A(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new O2({signature:e});if(typeof e.s>"u")throw new O2({signature:e});if(r&&typeof e.yParity>"u")throw new O2({signature:e});if(e.r<0n||e.r>PR)throw new LA({value:e.r});if(e.s<0n||e.s>PR)throw new MA({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new C1({value:e.yParity})}function nZ(e){return qR(na(e))}function qR(e){if(e.length!==130&&e.length!==132)throw new DA({signature:e});let t=BigInt(Oc(e,0,32)),r=BigInt(Oc(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return FA(o)}catch{throw new C1({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function CIe(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return WR(e)}function WR(e){let t=typeof e=="string"?qR(e):e instanceof Uint8Array?nZ(e):typeof e.r=="string"?iZ(e):e.v?sZ(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return $A(t),t}function SIe(e){return oZ(na(e))}function oZ(e){let{r:t,s:r}=ia.Signature.fromDER(Ul(e).slice(2));return{r:t,s:r}}function sZ(e){return{r:e.r,s:e.s,yParity:FA(e.v)}}function iZ(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=FA(r)),typeof n!="number")throw new C1({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function IIe(e){let[t,r,n]=e;return WR({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function TIe(e){return u8(aZ(e))}function aZ(e){$A(e);let t=e.r,r=e.s;return _A(oa(t,{size:32}),oa(r,{size:32}),typeof e.yParity=="number"?oa(KR(e.yParity),{size:1}):"0x")}function _Ie(e){return new ia.Signature(e.r,e.s).toDERRawBytes()}function PIe(e){return`0x${new ia.Signature(e.r,e.s).toDERHex()}`}function NIe(e){return{r:e.r,s:e.s,v:KR(e.yParity)}}function RIe(e){let{r:t,s:r,yParity:n}=e;return{r:oa(t,{size:32}),s:oa(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function OIe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":wR(oa(t)),r===0n?"0x":wR(oa(r))]}function BIe(e,t={}){try{return $A(e,t),!0}catch{return!1}}function FA(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new HA({value:e})}function KR(e){if(e===0)return 27;if(e===1)return 28;throw new C1({value:e})}var DA=class extends nr{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Va(Ul(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},O2=class extends nr{constructor({signature:t}){super(`Signature \`${Qp(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},LA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},MA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},C1=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},HA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}};l();l();var cZ=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]);var Xn=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Be=new Uint32Array(32);function eh(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=Be[2*e],u=Be[2*e+1],d=Be[2*t],f=Be[2*t+1],p=Be[2*r],h=Be[2*r+1],y=Be[2*n],w=Be[2*n+1],x=Xx(c,d,i);u=e8(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:MW(w,y),Dl:HW(w,y)},{h,l:p}=ra(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:Nl(f,d,24),Bl:Rl(f,d,24)},Be[2*e]=c,Be[2*e+1]=u,Be[2*t]=d,Be[2*t+1]=f,Be[2*r]=p,Be[2*r+1]=h,Be[2*n]=y,Be[2*n+1]=w}function th(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=Be[2*e],u=Be[2*e+1],d=Be[2*t],f=Be[2*t+1],p=Be[2*r],h=Be[2*r+1],y=Be[2*n],w=Be[2*n+1],x=Xx(c,d,i);u=e8(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:Nl(w,y,16),Dl:Rl(w,y,16)},{h,l:p}=ra(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:u1(f,d,63),Bl:d1(f,d,63)},Be[2*e]=c,Be[2*e+1]=u,Be[2*t]=d,Be[2*t+1]=f,Be[2*r]=p,Be[2*r+1]=h,Be[2*n]=y,Be[2*n+1]=w}function kIe(e,t={},r,n,o){if(Jo(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");let{key:s,salt:i,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(i!==void 0&&i.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==o)throw new Error("personalization must be undefined or "+o)}var ZR=class extends Ol{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Jo(t),Jo(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=h1(this.buffer)}update(t){Fa(this),t=Qo(t),Cn(t);let{blockLen:r,buffer:n,buffer32:o}=this,s=t.length,i=t.byteOffset,a=t.buffer;for(let c=0;co[i]=Bl(s))}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){let{buffer:r,length:n,finished:o,destroyed:s,outputLen:i,pos:a}=this;return t||(t=new this.constructor({dkLen:i})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=o,t.length=n,t.pos=a,t.outputLen=i,t}clone(){return this._cloneInto()}},GR=class extends ZR{constructor(t={}){let r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=Xn[0]|0,this.v0h=Xn[1]|0,this.v1l=Xn[2]|0,this.v1h=Xn[3]|0,this.v2l=Xn[4]|0,this.v2h=Xn[5]|0,this.v3l=Xn[6]|0,this.v3h=Xn[7]|0,this.v4l=Xn[8]|0,this.v4h=Xn[9]|0,this.v5l=Xn[10]|0,this.v5h=Xn[11]|0,this.v6l=Xn[12]|0,this.v6h=Xn[13]|0,this.v7l=Xn[14]|0,this.v7h=Xn[15]|0,kIe(r,t,64,16,16);let{key:n,personalization:o,salt:s}=t,i=0;if(n!==void 0&&(n=Qo(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){s=Qo(s);let a=h1(s);this.v4l^=Bl(a[0]),this.v4h^=Bl(a[1]),this.v5l^=Bl(a[2]),this.v5h^=Bl(a[3])}if(o!==void 0){o=Qo(o);let a=h1(o);this.v6l^=Bl(a[0]),this.v6h^=Bl(a[1]),this.v7l^=Bl(a[2]),this.v7h^=Bl(a[3])}if(n!==void 0){let a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:u,v4h:d,v5l:f,v5h:p,v6l:h,v6h:y,v7l:w,v7h:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=d|0,this.v5l=f|0,this.v5h=p|0,this.v6l=h|0,this.v6h=y|0,this.v7l=w|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>Be[u]=c),Be.set(Xn,16);let{h:o,l:s}=QN(BigInt(this.length));Be[24]=Xn[8]^s,Be[25]=Xn[9]^o,n&&(Be[28]=~Be[28],Be[29]=~Be[29]);let i=0,a=cZ;for(let c=0;c<12;c++)eh(0,4,8,12,t,r+2*a[i++]),th(0,4,8,12,t,r+2*a[i++]),eh(1,5,9,13,t,r+2*a[i++]),th(1,5,9,13,t,r+2*a[i++]),eh(2,6,10,14,t,r+2*a[i++]),th(2,6,10,14,t,r+2*a[i++]),eh(3,7,11,15,t,r+2*a[i++]),th(3,7,11,15,t,r+2*a[i++]),eh(0,5,10,15,t,r+2*a[i++]),th(0,5,10,15,t,r+2*a[i++]),eh(1,6,11,12,t,r+2*a[i++]),th(1,6,11,12,t,r+2*a[i++]),eh(2,7,8,13,t,r+2*a[i++]),th(2,7,8,13,t,r+2*a[i++]),eh(3,4,9,14,t,r+2*a[i++]),th(3,4,9,14,t,r+2*a[i++]);this.v0l^=Be[0]^Be[16],this.v0h^=Be[1]^Be[17],this.v1l^=Be[2]^Be[18],this.v1h^=Be[3]^Be[19],this.v2l^=Be[4]^Be[20],this.v2h^=Be[5]^Be[21],this.v3l^=Be[6]^Be[22],this.v3h^=Be[7]^Be[23],this.v4l^=Be[8]^Be[24],this.v4h^=Be[9]^Be[25],this.v5l^=Be[10]^Be[26],this.v5h^=Be[11]^Be[27],this.v6l^=Be[12]^Be[28],this.v6h^=Be[13]^Be[29],this.v7l^=Be[14]^Be[30],this.v7h^=Be[15]^Be[31],fo(Be)}destroy(){this.destroyed=!0,fo(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},lZ=XW(e=>new GR(e));var ZA={};Te(ZA,{createKeyPair:()=>KIe,getPublicKey:()=>CZ,getSharedSecret:()=>ZIe,noble:()=>WIe,randomPrivateKey:()=>SZ,recoverAddress:()=>IZ,recoverPublicKey:()=>TZ,sign:()=>GIe,verify:()=>YIe});l();l();var AZ=!1;var WIe=ia;function KIe(e={}){let{as:t="Hex"}=e,r=SZ({as:t}),n=CZ({privateKey:r});return{privateKey:r,publicKey:n}}function CZ(e){let{privateKey:t}=e,r=ia.ProjectivePoint.fromPrivateKey(Ul(t).slice(2));return SR(r)}function ZIe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,i=ia.ProjectivePoint.fromHex(d8(n).slice(2)).multiply(ia.utils.normPrivateKeyToScalar(Ul(r).slice(2))).toRawBytes(!0);return t==="Hex"?na(i):i}function SZ(e={}){let{as:t="Hex"}=e,r=ia.utils.randomPrivateKey();return t==="Hex"?na(r):r}function IZ(e){return kK(TZ(e))}function TZ(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new ia.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Ul(t).substring(2));return SR(a)}function GIe(e){let{extraEntropy:t=AZ,hash:r,payload:n,privateKey:o}=e,{r:s,s:i,recovery:a}=ia.sign(R2(n),R2(o),{extraEntropy:typeof t=="boolean"?t:Ul(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function YIe(e){let{address:t,hash:r,payload:n,publicKey:o,signature:s}=e;return t?UK(t,IZ({payload:n,signature:s})):ia.verify(s,R2(n),OK(o),...r?[{prehash:!0,lowS:!0}]:[])}l();l();l();l();function HZ(e){let t=e.length,r=0,n=0;for(;n=55296&&o<=56319&&n>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}var o9e=new TextEncoder,s9e=50;function i9e(e,t,r){o9e.encodeInto(e,t.subarray(r))}function $Z(e,t,r){e.length>s9e?i9e(e,t,r):n9e(e,t,r)}var a9e=4096;function rO(e,t,r){let n=t,o=n+r,s=[],i="";for(;n65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=a9e&&(i+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(i+=String.fromCharCode(...s)),i}var c9e=new TextDecoder,l9e=200;function u9e(e,t,r){let n=e.subarray(t,t+r);return c9e.decode(n)}function FZ(e,t,r){return r>l9e?u9e(e,t,r):rO(e,t,r)}l();l();var S1=class{type;data;constructor(t,r){this.type=t,this.data=r}};l();l();var gi=class e extends Error{constructor(t){super(t);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};l();function zZ(e,t,r){let n=r/4294967296,o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function tC(e,t,r){let n=Math.floor(r/4294967296),o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function rC(e,t){let r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function VZ(e,t){let r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}var d9e=-1,f9e=4294967296-1,p9e=17179869184-1;function h9e({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=p9e)if(t===0&&e<=f9e){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|r&3),s.setUint32(4,n),o}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),tC(n,4,e),r}}function m9e(e){let t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,o=Math.floor(n/1e9);return{sec:r+o,nsec:n-o*1e9}}function g9e(e){if(e instanceof Date){let t=m9e(e);return h9e(t)}else return null}function y9e(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let r=t.getUint32(0),n=t.getUint32(4),o=(r&3)*4294967296+n,s=r>>>2;return{sec:o,nsec:s}}case 12:{let r=rC(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new gi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function w9e(e){let t=y9e(e);return new Date(t.sec*1e3+t.nsec/1e6)}var jZ={type:d9e,encode:g9e,decode:w9e};var k2=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(jZ)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{let o=-1-t;this.builtInEncoders[o]=r,this.builtInDecoders[o]=n}}tryToEncode(t,r){for(let n=0;nthis.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){let r=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let n=HZ(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),$Z(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){let n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let n=m8(t);this.writeU8a(n)}encodeArray(t,r){let n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let o of t)this.doEncode(o,r+1)}countWithoutUndefined(t,r){let n=0;for(let o of r)t[o]!==void 0&&n++;return n}encodeMap(t,r){let n=Object.keys(t);this.sortKeys&&n.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of n){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){let n=t.data(this.pos+6),o=n.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(n);return}let r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),zZ(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),tC(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}};function nO(e,t){return new nC(t).encodeSharedRef(e)}l();l();l();function oC(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}l();var E9e=16,A9e=16,sC=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=E9e,r=A9e){this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n0&&t<=this.maxKeyLength}find(t,r,n){let o=this.caches[n-1];e:for(let s of o){let i=s.bytes;for(let a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)}decode(t,r,n){let o=this.find(t,r,n);if(o!=null)return this.hit++,o;this.miss++;let s=rO(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,s),s}};var oO="array",w8="map_key",WZ="map_value",C9e=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new gi("The type of key must be string or number but "+typeof e)},sO=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let r=this.getUninitializedStateFromPool();r.type=oO,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){let r=this.getUninitializedStateFromPool();r.type=w8,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===oO){let n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===w8||t.type===WZ){let n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},y8=-1,iO=new DataView(new ArrayBuffer(0)),S9e=new Uint8Array(iO.buffer);try{iO.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var qZ=new RangeError("Insufficient data"),I9e=new sC,iC=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=iO;bytes=S9e;headByte=y8;stack=new sO;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??k2.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??4294967295,this.maxBinLength=t?.maxBinLength??4294967295,this.maxArrayLength=t?.maxArrayLength??4294967295,this.maxMapLength=t?.maxMapLength??4294967295,this.maxExtLength=t?.maxExtLength??4294967295,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:I9e,this.mapKeyConverter=t?.mapKeyConverter??C9e}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=y8,this.stack.reset()}setBuffer(t){let r=m8(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===y8&&!this.hasRemaining(1))this.setBuffer(t);else{let r=this.bytes.subarray(this.pos),n=m8(t),o=new Uint8Array(r.length+n.length);o.set(r),o.set(n,r.length),this.setBuffer(o)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(let a of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:o,pos:s,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${oC(o)} at ${i} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,o=-1;for await(let s of t){if(r&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){let o=t-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t<160){let o=t-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else{let o=t-160;r=this.decodeString(o,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){let o=this.lookU8();r=this.decodeString(o,1)}else if(t===218){let o=this.lookU16();r=this.decodeString(o,2)}else if(t===219){let o=this.lookU32();r=this.decodeString(o,4)}else if(t===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===196){let o=this.lookU8();r=this.decodeBinary(o,1)}else if(t===197){let o=this.lookU16();r=this.decodeBinary(o,2)}else if(t===198){let o=this.lookU32();r=this.decodeBinary(o,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){let o=this.lookU8();r=this.decodeExtension(o,1)}else if(t===200){let o=this.lookU16();r=this.decodeExtension(o,2)}else if(t===201){let o=this.lookU32();r=this.decodeExtension(o,4)}else throw new gi(`Unrecognized type byte: ${oC(t)}`);this.complete();let n=this.stack;for(;n.length>0;){let o=n.top();if(o.type===oO)if(o.array[o.position]=r,o.position++,o.position===o.size)r=o.array,n.release(o);else continue e;else if(o.type===w8){if(r==="__proto__")throw new gi("The key __proto__ is not allowed");o.key=this.mapKeyConverter(r),o.type=WZ;continue e}else if(o.map[o.key]=r,o.readCount++,o.readCount===o.size)r=o.map,n.release(o);else{o.key=null,o.type=w8;continue e}}return r}}readHeadByte(){return this.headByte===y8&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=y8}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new gi(`Unrecognized array type byte: ${oC(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new gi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new gi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new gi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===w8:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new gi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw qZ;let n=this.pos+r,o=this.bytes.subarray(n,n+t);return this.pos+=r+t,o}decodeExtension(t,r){if(t>this.maxExtLength)throw new gi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+r),o=this.decodeBinary(t,r+1);return this.extensionCodec.decode(o,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){let t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){let t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){let t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){let t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){let t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){let t=VZ(this.view,this.pos);return this.pos+=8,t}readI64(){let t=rC(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){let t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){let t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){let t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){let t=this.view.getFloat64(this.pos);return this.pos+=8,t}};function aO(e,t){return new iC(t).decode(e)}JR();I8();l();l();XA();var DG=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),LTe=DG("expand 16-byte k"),MTe=DG("expand 32-byte k"),HTe=ef(LTe),$Te=ef(MTe);function je(e,t){return e<>>32-t}function kO(e){return e.byteOffset%4===0}var hC=64,FTe=16,LG=2**32-1,UG=new Uint32Array;function zTe(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(hC),d=ef(u),f=kO(o)&&kO(s),p=f?ef(o):UG,h=f?ef(s):UG;for(let y=0;y=LG)throw new Error("arx: counter overflow");let w=Math.min(hC,c-y);if(f&&w===hC){let x=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,T;v{rs(a),rs(c),rs(u);let p=u.length;if(d===void 0&&(d=new Uint8Array(p)),rs(d),YA(f),f<0||f>=LG)throw new Error("arx: counter overflow");if(d.lengthe[t++]&255|(e[t++]&255)<<8,DO=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=JA(t),rs(t,32);let r=Lo(t,0),n=Lo(t,2),o=Lo(t,4),s=Lo(t,6),i=Lo(t,8),a=Lo(t,10),c=Lo(t,12),u=Lo(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Lo(t,16+2*d)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],d=i[3],f=i[4],p=i[5],h=i[6],y=i[7],w=i[8],x=i[9],v=Lo(t,r+0),T=Lo(t,r+2),E=Lo(t,r+4),S=Lo(t,r+6),_=Lo(t,r+8),O=Lo(t,r+10),D=Lo(t,r+12),M=Lo(t,r+14),N=s[0]+(v&8191),L=s[1]+((v>>>13|T<<3)&8191),P=s[2]+((T>>>10|E<<6)&8191),R=s[3]+((E>>>7|S<<9)&8191),I=s[4]+((S>>>4|_<<12)&8191),B=s[5]+(_>>>1&8191),C=s[6]+((_>>>14|O<<2)&8191),A=s[7]+((O>>>11|D<<5)&8191),U=s[8]+((D>>>8|M<<8)&8191),H=s[9]+(M>>>5|o),k=0,F=k+N*a+L*(5*x)+P*(5*w)+R*(5*y)+I*(5*h);k=F>>>13,F&=8191,F+=B*(5*p)+C*(5*f)+A*(5*d)+U*(5*u)+H*(5*c),k+=F>>>13,F&=8191;let j=k+N*c+L*a+P*(5*x)+R*(5*w)+I*(5*y);k=j>>>13,j&=8191,j+=B*(5*h)+C*(5*p)+A*(5*f)+U*(5*d)+H*(5*u),k+=j>>>13,j&=8191;let W=k+N*u+L*c+P*a+R*(5*x)+I*(5*w);k=W>>>13,W&=8191,W+=B*(5*y)+C*(5*h)+A*(5*p)+U*(5*f)+H*(5*d),k+=W>>>13,W&=8191;let ae=k+N*d+L*u+P*c+R*a+I*(5*x);k=ae>>>13,ae&=8191,ae+=B*(5*w)+C*(5*y)+A*(5*h)+U*(5*p)+H*(5*f),k+=ae>>>13,ae&=8191;let te=k+N*f+L*d+P*u+R*c+I*a;k=te>>>13,te&=8191,te+=B*(5*x)+C*(5*w)+A*(5*y)+U*(5*h)+H*(5*p),k+=te>>>13,te&=8191;let X=k+N*p+L*f+P*d+R*u+I*c;k=X>>>13,X&=8191,X+=B*a+C*(5*x)+A*(5*w)+U*(5*y)+H*(5*h),k+=X>>>13,X&=8191;let pe=k+N*h+L*p+P*f+R*d+I*u;k=pe>>>13,pe&=8191,pe+=B*c+C*a+A*(5*x)+U*(5*w)+H*(5*y),k+=pe>>>13,pe&=8191;let me=k+N*y+L*h+P*p+R*f+I*d;k=me>>>13,me&=8191,me+=B*u+C*c+A*a+U*(5*x)+H*(5*w),k+=me>>>13,me&=8191;let Ne=k+N*w+L*y+P*h+R*p+I*f;k=Ne>>>13,Ne&=8191,Ne+=B*d+C*u+A*c+U*a+H*(5*x),k+=Ne>>>13,Ne&=8191;let ye=k+N*x+L*w+P*y+R*h+I*p;k=ye>>>13,ye&=8191,ye+=B*f+C*d+A*u+U*c+H*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+F|0,F=k&8191,k=k>>>13,j+=k,s[0]=F,s[1]=j,s[2]=W,s[3]=ae,s[4]=te,s[5]=X,s[6]=pe,s[7]=me,s[8]=Ne,s[9]=ye}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;tf(n)}update(t){QR(this),t=JA(t),rs(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function VTe(e){let t=(n,o)=>e(o).update(JA(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var MG=VTe(e=>new DO(e));XA();function FG(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],p=t[2],h=t[3],y=t[4],w=t[5],x=t[6],v=t[7],T=o,E=r[0],S=r[1],_=r[2],O=i,D=a,M=c,N=u,L=d,P=f,R=p,I=h,B=y,C=w,A=x,U=v,H=T,k=E,F=S,j=_;for(let ae=0;ae{e.update(t);let r=t.length%16;r&&e.update(KTe.subarray(r))},ZTe=new Uint8Array(32);function $G(e,t,r,n,o){let s=e(t,r,ZTe),i=MG.create(s);o&&HG(i,o),HG(i,n);let a=BZ(n.length,o?o.length:0,!0);i.update(a);let c=i.digest();return tf(s,a),c}var zG=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=eO(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let u=$G(e,t,r,c,n);return i.set(u,a),tf(u),i},decrypt(s,i){i=eO(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=$G(e,t,r,a,n);if(!OZ(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),tf(u),i}}),LO=XR({blockSize:64,nonceLength:12,tagLength:16},zG(qTe)),hdt=XR({blockSize:64,nonceLength:24,tagLength:16},zG(WTe));l();function GTe(e,t,r){return p1(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Xp(e,Qo(r),Qo(t))}var MO=Uint8Array.from([0]),VG=Uint8Array.of();function YTe(e,t,r,n=32){p1(e),Jo(n);let o=e.outputLen;if(n>255*o)throw new Error("Length should be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0&&(r=VG);let i=new Uint8Array(s*o),a=Xp.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;dYTe(e,GTe(e,t,r),n,o);l();l();l();var FO=BigInt(0),$O=BigInt(1);function nf(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function aa(e,t,r=""){let n=Wd(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function T8(e){let t=e.toString(16);return t.length&1?"0"+t:t}function qG(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?FO:BigInt("0x"+e)}function $2(e){return qG(za(e))}function ja(e){return Cn(e),qG(za(Uint8Array.from(e).reverse()))}function mC(e,t){return m1(e.toString(16).padStart(t*2,"0"))}function _8(e,t){return mC(e,t).reverse()}function or(e,t,r){let n;if(typeof t=="string")try{n=m1(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Wd(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function WG(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;ntypeof e=="bigint"&&FO<=e;function KG(e,t,r){return HO(e)&&HO(t)&&HO(r)&&t<=e&&eFO;e>>=$O,t+=1);return t}var sh=e=>($O<new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(e),i=n(e),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...h)=>r(i,s,...h),d=(h=n(0))=>{i=u(o(0),h),s=u(),h.length!==0&&(i=u(o(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,y=[];for(;h{c(),d(h);let w;for(;!(w=y(f()));)d();return c(),w}}function Ll(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var VO=()=>{throw new Error("not implemented")};function F2(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}l();var Hs=BigInt(0),ho=BigInt(1),_1=BigInt(2),JG=BigInt(3),QG=BigInt(4),XG=BigInt(5),JTe=BigInt(7),eY=BigInt(8),QTe=BigInt(9),tY=BigInt(16);function Yr(e,t){let r=e%t;return r>=Hs?r:t+r}function qa(e,t,r){let n=e;for(;t-- >Hs;)n*=n,n%=r;return n}function GG(e,t){if(e===Hs)throw new Error("invert: expected non-zero number");if(t<=Hs)throw new Error("invert: expected positive modulus, got "+t);let r=Yr(e,t),n=t,o=Hs,s=ho,i=ho,a=Hs;for(;r!==Hs;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ho)throw new Error("invert: does not exist");return Yr(o,t)}function jO(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function rY(e,t){let r=(e.ORDER+ho)/QG,n=e.pow(t,r);return jO(e,n,t),n}function XTe(e,t){let r=(e.ORDER-XG)/eY,n=e.mul(t,_1),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,_1),o),a=e.mul(s,e.sub(i,e.ONE));return jO(e,a,t),a}function e_e(e){let t=$s(e),r=nY(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+JTe)/tY;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),h=a.eql(a.sqr(d),c),y=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(p,f,y);let w=a.eql(a.sqr(d),c),x=a.cmov(u,d,w);return jO(a,x,c),x}}function nY(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return rY;let s=o.pow(n,t),i=(t+ho)/_1;return function(c,u){if(c.is0(u))return u;if(YG(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ho<(Yr(e,t)&ho)===ho,r_e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qO(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=r_e.reduce((n,o)=>(n[o]="function",n),t);return Ll(e,r),e}function n_e(e,t,r){if(rHs;)r&ho&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ho;return n}function P8(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function YG(e,t){let r=(e.ORDER-ho)/_1,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function yC(e,t){t!==void 0&&Jo(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function $s(e,t,r=!1,n={}){if(e<=Hs)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(r=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=yC(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:sh(c),ZERO:Hs,ONE:ho,allowedLengths:a,create:p=>Yr(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return Hs<=p&&pp===Hs,isValidNot0:p=>!f.is0(p)&&f.isValid(p),isOdd:p=>(p&ho)===ho,neg:p=>Yr(-p,e),eql:(p,h)=>p===h,sqr:p=>Yr(p*p,e),add:(p,h)=>Yr(p+h,e),sub:(p,h)=>Yr(p-h,e),mul:(p,h)=>Yr(p*h,e),pow:(p,h)=>n_e(f,p,h),div:(p,h)=>Yr(p*GG(h,e),e),sqrN:p=>p*p,addN:(p,h)=>p+h,subN:(p,h)=>p-h,mulN:(p,h)=>p*h,inv:p=>GG(p,e),sqrt:s||(p=>(d||(d=t_e(e)),d(f,p))),toBytes:p=>r?_8(p,u):mC(p,u),fromBytes:(p,h=!0)=>{if(a){if(!a.includes(p.length)||p.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let w=new Uint8Array(u);w.set(p,r?0:w.length-p.length),p=w}if(p.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+p.length);let y=r?ja(p):$2(p);if(i&&(y=Yr(y,e)),!h&&!f.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:p=>P8(f,p),cmov:(p,h,y)=>y?h:p});return Object.freeze(f)}function oY(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function WO(e){let t=oY(e);return t+Math.ceil(t/2)}function sY(e,t,r=!1){let n=e.length,o=oY(t),s=WO(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?ja(e):$2(e),a=Yr(i,t-ho)+ho;return r?_8(a,o):mC(a,o)}var z2=BigInt(0),P1=BigInt(1);function N8(e,t){let r=t.negate();return e?r:t}function sf(e,t){let r=P8(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function lY(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function KO(e,t){lY(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=sh(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function iY(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=P1);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function o_e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function s_e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var ZO=new WeakMap,uY=new WeakMap;function GO(e){return uY.get(e)||1}function aY(e){if(e!==z2)throw new Error("invalid wNAF")}var V2=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>z2;)r&P1&&(n=n.add(o)),o=o.double(),r>>=P1;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=KO(r,this.bits),s=[],i=t,a=i;for(let c=0;cz2||n>z2;)r&P1&&(s=s.add(o)),n&P1&&(i=i.add(o)),o=o.double(),r>>=P1,n>>=P1;return{p1:s,p2:i}}function j2(e,t,r,n){o_e(r,e),s_e(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=gC(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=sh(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;wz2))throw new Error(`CURVE.${c} must be positive bigint`)}let o=cY(t.p,r.Fp,n),s=cY(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}l();var ih=BigInt(0),mo=BigInt(1),YO=BigInt(2),i_e=BigInt(8);function a_e(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function c_e(e,t={}){let r=wC("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Ll(t,{},{uvRatio:"function"});let a=YO<n.create(x),u=t.uvRatio||((x,v)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,v))}}catch{return{isValid:!1,value:ih}}});if(!a_e(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(x,v,T=!1){let E=T?mo:ih;return oh("coordinate "+x,v,E,a),v}function f(x){if(!(x instanceof y))throw new Error("ExtendedPoint expected")}let p=F2((x,v)=>{let{X:T,Y:E,Z:S}=x,_=x.is0();v==null&&(v=_?i_e:n.inv(S));let O=c(T*v),D=c(E*v),M=n.mul(S,v);if(_)return{x:ih,y:mo};if(M!==mo)throw new Error("invZ was invalid");return{x:O,y:D}}),h=F2(x=>{let{a:v,d:T}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:E,Y:S,Z:_,T:O}=x,D=c(E*E),M=c(S*S),N=c(_*_),L=c(N*N),P=c(D*v),R=c(N*c(P+M)),I=c(L+c(T*c(D*M)));if(R!==I)throw new Error("bad point: equation left != right (1)");let B=c(E*S),C=c(_*O);if(B!==C)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,T,E,S){this.X=d("x",v),this.Y=d("y",T),this.Z=d("z",E,!0),this.T=d("t",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:T,y:E}=v||{};return d("x",T),d("y",E),new y(T,E,mo,c(T*E))}static fromBytes(v,T=!1){let E=n.BYTES,{a:S,d:_}=s;v=zO(aa(v,E,"point")),nf(T,"zip215");let O=zO(v),D=v[E-1];O[E-1]=D&-129;let M=ja(O),N=T?a:n.ORDER;oh("point.y",M,ih,N);let L=c(M*M),P=c(L-mo),R=c(_*L-S),{isValid:I,value:B}=u(P,R);if(!I)throw new Error("bad point: invalid y coordinate");let C=(B&mo)===mo,A=(D&128)!==0;if(!T&&B===ih&&A)throw new Error("bad point: x=0 and x_0=1");return A!==C&&(B=c(-B)),y.fromAffine({x:B,y:M})}static fromHex(v,T=!1){return y.fromBytes(or("point",v),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,T=!0){return w.createCache(this,v),T||this.multiply(YO),this}assertValidity(){h(this)}equals(v){f(v);let{X:T,Y:E,Z:S}=this,{X:_,Y:O,Z:D}=v,M=c(T*D),N=c(_*S),L=c(E*D),P=c(O*S);return M===N&&L===P}is0(){return this.equals(y.ZERO)}negate(){return new y(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:v}=s,{X:T,Y:E,Z:S}=this,_=c(T*T),O=c(E*E),D=c(YO*c(S*S)),M=c(v*_),N=T+E,L=c(c(N*N)-_-O),P=M+O,R=P-D,I=M-O,B=c(L*R),C=c(P*I),A=c(L*I),U=c(R*P);return new y(B,C,U,A)}add(v){f(v);let{a:T,d:E}=s,{X:S,Y:_,Z:O,T:D}=this,{X:M,Y:N,Z:L,T:P}=v,R=c(S*M),I=c(_*N),B=c(D*E*P),C=c(O*L),A=c((S+_)*(M+N)-R-I),U=C-B,H=C+B,k=c(I-T*R),F=c(A*U),j=c(H*k),W=c(A*k),ae=c(U*H);return new y(F,j,ae,W)}subtract(v){return this.add(v.negate())}multiply(v){if(!o.isValidNot0(v))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:T,f:E}=w.cached(this,v,S=>sf(y,S));return sf(y,[T,E])[0]}multiplyUnsafe(v,T=y.ZERO){if(!o.isValid(v))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return v===ih?y.ZERO:this.is0()||v===mo?this:w.unsafe(this,v,E=>sf(y,E),T)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,s.n).is0()}toAffine(v){return p(this,v)}clearCofactor(){return i===mo?this:this.multiplyUnsafe(i)}toBytes(){let{x:v,y:T}=this.toAffine(),E=n.toBytes(T);return E[E.length-1]|=v&mo?128:0,E}toHex(){return za(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(v){return sf(y,v)}static msm(v,T){return j2(y,o,v,T)}_setWindowSize(v){this.precompute(v)}toRawBytes(){return this.toBytes()}}y.BASE=new y(s.Gx,s.Gy,mo,c(s.Gx*s.Gy)),y.ZERO=new y(ih,mo,mo,ih),y.Fp=n,y.Fn=o;let w=new V2(y,o.BITS);return y.BASE.precompute(8),y}var bC=class{constructor(t){this.ep=t}static fromBytes(t){VO()}static fromHex(t){VO()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return za(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function l_e(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ll(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||Us,c=r.adjustScalarBytes||(N=>N),u=r.domain||((N,L,P)=>{if(nf(P,"phflag"),L.length||P)throw new Error("Contexts/pre-hash are not supported");return N});function d(N){return i.create(ja(N))}function f(N){let L=E.secretKey;N=or("private key",N,L);let P=or("hashed private key",t(N),2*L),R=c(P.slice(0,L)),I=P.slice(L,2*L),B=d(R);return{head:R,prefix:I,scalar:B}}function p(N){let{head:L,prefix:P,scalar:R}=f(N),I=o.multiply(R),B=I.toBytes();return{head:L,prefix:P,scalar:R,point:I,pointBytes:B}}function h(N){return p(N).pointBytes}function y(N=Uint8Array.of(),...L){let P=ko(...L);return d(t(u(P,or("context",N),!!n)))}function w(N,L,P={}){N=or("message",N),n&&(N=n(N));let{prefix:R,scalar:I,pointBytes:B}=p(L),C=y(P.context,R,N),A=o.multiply(C).toBytes(),U=y(P.context,A,B,N),H=i.create(C+U*I);if(!i.isValid(H))throw new Error("sign failed: invalid s");let k=ko(A,i.toBytes(H));return aa(k,E.signature,"result")}let x={zip215:!0};function v(N,L,P,R=x){let{context:I,zip215:B}=R,C=E.signature;N=or("signature",N,C),L=or("message",L),P=or("publicKey",P,E.publicKey),B!==void 0&&nf(B,"zip215"),n&&(L=n(L));let A=C/2,U=N.subarray(0,A),H=ja(N.subarray(A,C)),k,F,j;try{k=e.fromBytes(P,B),F=e.fromBytes(U,B),j=o.multiplyUnsafe(H)}catch{return!1}if(!B&&k.isSmallOrder())return!1;let W=y(I,F.toBytes(),k.toBytes(),L);return F.add(k.multiplyUnsafe(W)).subtract(j).clearCofactor().is0()}let T=s.BYTES,E={secretKey:T,publicKey:T,signature:2*T,seed:T};function S(N=a(E.seed)){return aa(N,E.seed,"seed")}function _(N){let L=M.randomSecretKey(N);return{secretKey:L,publicKey:h(L)}}function O(N){return Wd(N)&&N.length===i.BYTES}function D(N,L){try{return!!e.fromBytes(N,L)}catch{return!1}}let M={getExtendedPublicKey:p,randomSecretKey:S,isValidSecretKey:O,isValidPublicKey:D,toMontgomery(N){let{y:L}=e.fromBytes(N),P=E.publicKey,R=P===32;if(!R&&P!==57)throw new Error("only defined for 25519 and 448");let I=R?s.div(mo+L,mo-L):s.div(L-mo,L+mo);return s.toBytes(I)},toMontgomerySecret(N){let L=E.secretKey;aa(N,L);let P=t(N.subarray(0,L));return c(P).subarray(0,L)},randomPrivateKey:S,precompute(N=8,L=e.BASE){return L.precompute(N,!1)}};return Object.freeze({keygen:_,getPublicKey:h,sign:w,verify:v,utils:M,Point:e,lengths:E})}function u_e(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=$s(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:s}}function d_e(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function fY(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=u_e(e),s=c_e(t,r),i=l_e(s,n,o);return d_e(e,i)}l();var R8=BigInt(0),q2=BigInt(1),xC=BigInt(2);function f_e(e){return Ll(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function pY(e){let t=f_e(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Us,u=a?255:448,d=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),h=a?xC**BigInt(254):xC**BigInt(447),y=a?BigInt(8)*xC**BigInt(251)-q2:BigInt(4)*xC**BigInt(445)-q2,w=h+y+q2,x=I=>Yr(I,r),v=T(f);function T(I){return _8(x(I),d)}function E(I){let B=or("u coordinate",I,d);return a&&(B[31]&=127),x(ja(B))}function S(I){return ja(o(or("scalar",I,d)))}function _(I,B){let C=M(E(B),S(I));if(C===R8)throw new Error("invalid private or public key received");return T(C)}function O(I){return _(I,v)}function D(I,B,C){let A=x(I*(B-C));return B=x(B-A),C=x(C+A),{x_2:B,x_3:C}}function M(I,B){oh("u",I,R8,r),oh("scalar",B,h,w);let C=B,A=I,U=q2,H=R8,k=I,F=q2,j=R8;for(let ae=BigInt(u-1);ae>=R8;ae--){let te=C>>ae&q2;j^=te,{x_2:U,x_3:k}=D(j,U,k),{x_2:H,x_3:F}=D(j,H,F),j=te;let X=U+H,pe=x(X*X),me=U-H,Ne=x(me*me),ye=pe-Ne,Re=k+F,Et=k-F,kt=x(Et*X),At=x(Re*me),ur=kt+At,_r=kt-At;k=x(ur*ur),F=x(A*x(_r*_r)),U=x(pe*Ne),H=x(ye*(pe+x(p*ye)))}({x_2:U,x_3:k}=D(j,U,k)),{x_2:H,x_3:F}=D(j,H,F);let W=s(H);return x(U*W)}let N={secretKey:d,publicKey:d,seed:d},L=(I=c(d))=>(Cn(I,N.seed),I);function P(I){let B=L(I);return{secretKey:B,publicKey:O(B)}}return{keygen:P,getSharedSecret:(I,B)=>_(I,B),getPublicKey:I=>O(I),scalarMult:_,scalarMultBase:O,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:v.slice(),lengths:N}}var p_e=BigInt(0),cf=BigInt(1),hY=BigInt(2),h_e=BigInt(3),m_e=BigInt(5),g_e=BigInt(8),W2=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),O8={p:W2,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:g_e,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yY(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=W2,a=e*e%s*e%s,c=qa(a,hY,s)*a%s,u=qa(c,cf,s)*e%s,d=qa(u,m_e,s)*u%s,f=qa(d,t,s)*d%s,p=qa(f,r,s)*f%s,h=qa(p,n,s)*p%s,y=qa(h,o,s)*h%s,w=qa(y,o,s)*h%s,x=qa(w,t,s)*d%s;return{pow_p_5_8:qa(x,hY,s)*e%s,b2:a}}function wY(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var JO=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function eB(e,t){let r=W2,n=Yr(t*t*t,r),o=Yr(n*n*t,r),s=yY(e*o).pow_p_5_8,i=Yr(e*n*s,r),a=Yr(t*i*i,r),c=i,u=Yr(i*JO,r),d=a===e,f=a===Yr(-e,r),p=a===Yr(-e*JO,r);return d&&(i=c),(f||p)&&(i=u),of(i,r)&&(i=Yr(-i,r)),{isValid:d||f,value:i}}var af=$s(O8.p,{isLE:!0}),y_e=$s(O8.n,{isLE:!0}),w_e={...O8,Fp:af,hash:bA,adjustScalarBytes:wY,uvRatio:eB},N1=fY(w_e);var vC=(()=>{let e=af.ORDER;return pY({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=yY(t);return Yr(qa(r,h_e,e)*n,e)},adjustScalarBytes:wY})})();var QO=JO,b_e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x_e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),v_e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),E_e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),mY=e=>eB(cf,e),A_e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),XO=e=>N1.Point.Fp.create(ja(e)&A_e);function gY(e){let{d:t}=O8,r=W2,n=v=>af.create(v),o=n(QO*e*e),s=n((o+cf)*v_e),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=eB(s,a),d=n(u*e);of(d,r)||(d=n(-d)),c||(u=d),c||(i=o);let f=n(i*(o-cf)*E_e-a),p=u*u,h=n((u+u)*a),y=n(f*b_e),w=n(cf-p),x=n(cf+p);return new N1.Point(n(h*x),n(w*y),n(y*x),n(h*w))}function C_e(e){Cn(e,64);let t=XO(e.subarray(0,32)),r=gY(t),n=XO(e.subarray(32,64)),o=gY(n);return new lf(r.add(o))}var lf=class e extends bC{constructor(t){super(t)}static fromAffine(t){return new e(N1.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return C_e(or("ristrettoHash",t,64))}static fromBytes(t){Cn(t,32);let{a:r,d:n}=O8,o=W2,s=S=>af.create(S),i=XO(t);if(!WG(af.toBytes(i),t)||of(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(cf+r*a),u=s(cf-r*a),d=s(c*c),f=s(u*u),p=s(r*n*d-f),{isValid:h,value:y}=mY(s(p*f)),w=s(y*u),x=s(y*w*p),v=s((i+i)*w);of(v,o)&&(v=s(-v));let T=s(c*x),E=s(v*T);if(!h||of(E,o)||T===p_e)throw new Error("invalid ristretto255 encoding 2");return new e(new N1.Point(v,T,cf,E))}static fromHex(t){return e.fromBytes(or("ristrettoHex",t,32))}static msm(t,r){return j2(e,N1.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=W2,i=x=>af.create(x),a=i(i(n+r)*i(n-r)),c=i(t*r),u=i(c*c),{value:d}=mY(i(a*u)),f=i(d*a),p=i(d*c),h=i(f*p*o),y;if(of(o*h,s)){let x=i(r*QO),v=i(t*QO);t=x,r=v,y=i(f*x_e)}else y=p;of(t*h,s)&&(r=i(-r));let w=i((n-r)*y);return of(w,s)&&(w=i(-w)),af.toBytes(w)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>af.create(u),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};lf.BASE=new lf(N1.Point.BASE);lf.ZERO=new lf(N1.Point.ZERO);lf.Fp=af;lf.Fn=y_e;l();l();l();l();var bY=(e,t)=>(e+(e>=0?t:-t)/xY)/t;function S_e(e,t,r){let[[n,o],[s,i]]=t,a=bY(i*e,r),c=bY(-o*e,r),u=e-a*n-c*s,d=-a*o-c*i,f=u=h||d=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function rB(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function tB(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return nf(r.lowS,"lowS"),nf(r.prehash,"prehash"),r.format!==void 0&&rB(r.format),r}var nB=class extends Error{constructor(t=""){super(t)}},uf={Err:nB,_tlv:{encode:(e,t)=>{let{Err:r}=uf;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=T8(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?T8(o.length/2|128):"";return T8(e)+s+o+t},decode(e,t){let{Err:r}=uf,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=uf;if(e{let{X:B,Y:C,Z:A}=R;if(n.eql(A,n.ONE))return{x:B,y:C};let U=R.is0();I==null&&(I=U?n.ONE:n.inv(A));let H=n.mul(B,I),k=n.mul(C,I),F=n.mul(A,I);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:k}}),D=F2(R=>{if(R.is0()){if(t.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:B}=R.toAffine();if(!n.isValid(I)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!x(I,B))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,I,B,C,A){return B=new N(n.mul(B.X,R),B.Y,B.Z),I=N8(C,I),B=N8(A,B),I.add(B)}class N{constructor(I,B,C){this.X=E("x",I),this.Y=E("y",B,!0),this.Z=E("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){let{x:B,y:C}=I||{};if(!I||!n.isValid(B)||!n.isValid(C))throw new Error("invalid affine point");if(I instanceof N)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(C)?N.ZERO:new N(B,C,n.ONE)}static fromBytes(I){let B=N.fromAffine(y(aa(I,void 0,"point")));return B.assertValidity(),B}static fromHex(I){return N.fromBytes(or("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,B=!0){return P.createCache(this,I),B||this.multiply(EC),this}assertValidity(){D(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.eql(n.mul(B,k),n.mul(U,A)),j=n.eql(n.mul(C,k),n.mul(H,A));return F&&j}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:B}=s,C=n.mul(B,EC),{X:A,Y:U,Z:H}=this,k=n.ZERO,F=n.ZERO,j=n.ZERO,W=n.mul(A,A),ae=n.mul(U,U),te=n.mul(H,H),X=n.mul(A,U);return X=n.add(X,X),j=n.mul(A,H),j=n.add(j,j),k=n.mul(I,j),F=n.mul(C,te),F=n.add(k,F),k=n.sub(ae,F),F=n.add(ae,F),F=n.mul(k,F),k=n.mul(X,k),j=n.mul(C,j),te=n.mul(I,te),X=n.sub(W,te),X=n.mul(I,X),X=n.add(X,j),j=n.add(W,W),W=n.add(j,W),W=n.add(W,te),W=n.mul(W,X),F=n.add(F,W),te=n.mul(U,H),te=n.add(te,te),W=n.mul(te,X),k=n.sub(k,W),j=n.mul(te,ae),j=n.add(j,j),j=n.add(j,j),new N(k,F,j)}add(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.ZERO,j=n.ZERO,W=n.ZERO,ae=s.a,te=n.mul(s.b,EC),X=n.mul(B,U),pe=n.mul(C,H),me=n.mul(A,k),Ne=n.add(B,C),ye=n.add(U,H);Ne=n.mul(Ne,ye),ye=n.add(X,pe),Ne=n.sub(Ne,ye),ye=n.add(B,A);let Re=n.add(U,k);return ye=n.mul(ye,Re),Re=n.add(X,me),ye=n.sub(ye,Re),Re=n.add(C,A),F=n.add(H,k),Re=n.mul(Re,F),F=n.add(pe,me),Re=n.sub(Re,F),W=n.mul(ae,ye),F=n.mul(te,me),W=n.add(F,W),F=n.sub(pe,W),W=n.add(pe,W),j=n.mul(F,W),pe=n.add(X,X),pe=n.add(pe,X),me=n.mul(ae,me),ye=n.mul(te,ye),pe=n.add(pe,me),me=n.sub(X,me),me=n.mul(ae,me),ye=n.add(ye,me),X=n.mul(pe,ye),j=n.add(j,X),X=n.mul(Re,ye),F=n.mul(Ne,F),F=n.sub(F,X),X=n.mul(Ne,pe),W=n.mul(Re,W),W=n.add(W,X),new N(F,j,W)}subtract(I){return this.add(I.negate())}is0(){return this.equals(N.ZERO)}multiply(I){let{endo:B}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let C,A,U=H=>P.cached(this,H,k=>sf(N,k));if(B){let{k1neg:H,k1:k,k2neg:F,k2:j}=_(I),{p:W,f:ae}=U(k),{p:te,f:X}=U(j);A=ae.add(X),C=M(B.beta,W,te,H,F)}else{let{p:H,f:k}=U(I);C=H,A=k}return sf(N,[C,A])[0]}multiplyUnsafe(I){let{endo:B}=t,C=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===df||C.is0())return N.ZERO;if(I===Z2)return C;if(P.hasCache(this))return this.multiply(I);if(B){let{k1neg:A,k1:U,k2neg:H,k2:k}=_(I),{p1:F,p2:j}=dY(N,C,U,k);return M(B.beta,F,j,A,H)}else return P.unsafe(C,I)}multiplyAndAddUnsafe(I,B,C){let A=this.multiplyUnsafe(B).add(I.multiplyUnsafe(C));return A.is0()?void 0:A}toAffine(I){return O(this,I)}isTorsionFree(){let{isTorsionFree:I}=t;return i===Z2?!0:I?I(N,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=t;return i===Z2?this:I?I(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return nf(I,"isCompressed"),this.assertValidity(),h(N,this,I)}toHex(I=!0){return za(this.toBytes(I))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return sf(N,I)}static msm(I,B){return j2(N,o,I,B)}static fromPrivateKey(I){return N.BASE.multiply(K2(o,I))}}N.BASE=new N(s.Gx,s.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=o;let L=o.BITS,P=new V2(N,t.endo?Math.ceil(L/2):L);return N.BASE.precompute(8),N}function vY(e){return Uint8Array.of(e?2:3)}function EY(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function __e(e,t={}){let{Fn:r}=e,n=t.randomBytes||Us,o=Object.assign(EY(e.Fp,r),{seed:WO(r.ORDER)});function s(h){try{return!!K2(r,h)}catch{return!1}}function i(h,y){let{publicKey:w,publicKeyUncompressed:x}=o;try{let v=h.length;return y===!0&&v!==w||y===!1&&v!==x?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return sY(aa(h,o.seed,"seed"),r.ORDER)}function c(h,y=!0){return e.BASE.multiply(K2(r,h)).toBytes(y)}function u(h){let y=a(h);return{secretKey:y,publicKey:c(y)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;let{secretKey:y,publicKey:w,publicKeyUncompressed:x}=o;if(r.allowedLengths||y===w)return;let v=or("key",h).length;return v===w||v===x}function f(h,y,w=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let x=K2(r,h);return e.fromHex(y).multiply(x).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>K2(r,h),precompute(h=8,y=e.BASE){return y.precompute(h,!1)}},lengths:o})}function P_e(e,t,r={}){p1(t),Ll(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Us,o=r.hmac||((B,...C)=>Xp(t,B,ko(...C))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h}=__e(e,r),y={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function x(B){let C=a>>Z2;return B>C}function v(B,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${B}: out of range 1..Point.Fn.ORDER`);return C}function T(B,C){rB(C);let A=h.signature,U=C==="compact"?A:C==="recovered"?A+1:void 0;return aa(B,U,`${C} signature`)}class E{constructor(C,A,U){this.r=v("r",C),this.s=v("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(C,A=w){T(C,A);let U;if(A==="der"){let{r:j,s:W}=uf.toSig(aa(C));return new E(j,W)}A==="recovered"&&(U=C[0],A="compact",C=C.subarray(1));let H=i.BYTES,k=C.subarray(0,H),F=C.subarray(H,H*2);return new E(i.fromBytes(k),i.fromBytes(F),U)}static fromHex(C,A){return this.fromBytes(m1(C),A)}addRecoveryBit(C){return new E(this.r,this.s,C)}recoverPublicKey(C){let A=s.ORDER,{r:U,s:H,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*xY1)throw new Error("recovery id is ambiguous for h>1 curve");let j=k===2||k===3?U+a:U;if(!s.isValid(j))throw new Error("recovery id 2 or 3 invalid");let W=s.toBytes(j),ae=e.fromBytes(ko(vY((k&1)===0),W)),te=i.inv(j),X=_(or("msgHash",C)),pe=i.create(-X*te),me=i.create(H*te),Ne=e.BASE.multiplyUnsafe(pe).add(ae.multiplyUnsafe(me));if(Ne.is0())throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return x(this.s)}toBytes(C=w){if(rB(C),C==="der")return m1(uf.hexFromSig(this));let A=i.toBytes(this.r),U=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ko(Uint8Array.of(this.recovery),A,U)}return ko(A,U)}toHex(C){return za(this.toBytes(C))}assertValidity(){}static fromCompact(C){return E.fromBytes(or("sig",C),"compact")}static fromDER(C){return E.fromBytes(or("sig",C),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return za(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return za(this.toBytes("compact"))}}let S=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=$2(C),U=C.length*8-c;return U>0?A>>BigInt(U):A},_=r.bits2int_modN||function(C){return i.create(S(C))},O=sh(c);function D(B){return oh("num < 2^"+c,B,df,O),i.toBytes(B)}function M(B,C){return aa(B,void 0,"message"),C?aa(t(B),void 0,"prehashed message"):B}function N(B,C,A){if(["recovered","canonical"].some(pe=>pe in A))throw new Error("sign() legacy options not supported");let{lowS:U,prehash:H,extraEntropy:k}=tB(A,y);B=M(B,H);let F=_(B),j=K2(i,C),W=[D(j),D(F)];if(k!=null&&k!==!1){let pe=k===!0?n(h.secretKey):k;W.push(or("extraEntropy",pe))}let ae=ko(...W),te=F;function X(pe){let me=S(pe);if(!i.isValidNot0(me))return;let Ne=i.inv(me),ye=e.BASE.multiply(me).toAffine(),Re=i.create(ye.x);if(Re===df)return;let Et=i.create(Ne*i.create(te+Re*j));if(Et===df)return;let kt=(ye.x===Re?0:2)|Number(ye.y&Z2),At=Et;return U&&x(Et)&&(At=i.neg(Et),kt^=1),new E(Re,At,kt)}return{seed:ae,k2sig:X}}function L(B,C,A={}){B=or("message",B);let{seed:U,k2sig:H}=N(B,C,A);return ZG(t.outputLen,i.BYTES,o)(U,H)}function P(B){let C,A=typeof B=="string"||Wd(B),U=!A&&B!==null&&typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)C=new E(B.r,B.s);else if(A){try{C=E.fromBytes(or("sig",B),"der")}catch(H){if(!(H instanceof uf.Err))throw H}if(!C)try{C=E.fromBytes(or("sig",B),"compact")}catch{return!1}}return C||!1}function R(B,C,A,U={}){let{lowS:H,prehash:k,format:F}=tB(U,y);if(A=or("publicKey",A),C=M(or("message",C),k),"strict"in U)throw new Error("options.strict was renamed to lowS");let j=F===void 0?P(B):E.fromBytes(or("sig",B),F);if(j===!1)return!1;try{let W=e.fromBytes(A);if(H&&j.hasHighS())return!1;let{r:ae,s:te}=j,X=_(C),pe=i.inv(te),me=i.create(X*pe),Ne=i.create(ae*pe),ye=e.BASE.multiplyUnsafe(me).add(W.multiplyUnsafe(Ne));return ye.is0()?!1:i.create(ye.x)===ae}catch{return!1}}function I(B,C,A={}){let{prehash:U}=tB(A,y);return C=M(C,U),E.fromBytes(B,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h,Point:e,sign:L,verify:R,recoverPublicKey:I,Signature:E,hash:t})}function N_e(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$s(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function R_e(e){let{CURVE:t,curveOpts:r}=N_e(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function O_e(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,yC(r.Fn.ORDER,r.Fn.BITS))})}function AY(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:o}=R_e(e),s=T_e(t,r),i=P_e(s,n,o);return O_e(e,i)}function AC(e,t){let r=n=>AY({...e,hash:n});return{...r(t),create:r}}var CY={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},SY={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},IY={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},B_e=$s(CY.p),k_e=$s(SY.p),U_e=$s(IY.p);var TY=AC({...CY,Fp:B_e,lowS:!1},Zd);var fft=AC({...SY,Fp:k_e,lowS:!1},fK);var pft=AC({...IY,Fp:U_e,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},bA);var _Y=TY;B1();BB();var tQ=Ht(LB(),1);gh();var pRe=":";function Lc(e){let[t,r]=e.split(pRe);return{namespace:t,reference:r}}function GB(e,t=[]){let r=[];return Object.keys(e).forEach(n=>{if(t.length&&!t.includes(n))return;let o=e[n];r.push(...o.accounts)}),r}function rQ(e,t){return e.includes(":")?[e]:t.chains||[]}var hRe={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},mRe={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Se(e,t){let{message:r,code:n}=mRe[e];return{message:t?`${r} ${t}`:r,code:n}}function Sr(e,t){let{message:r,code:n}=hRe[e];return{message:t?`${r} ${t}`:r,code:n}}var gRe="ReactNative",bi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"};var yRe="js";function z8(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function gf(){return!(0,Dc.getDocument)()&&!!(0,Dc.getNavigator)()&&navigator.product===gRe}function nQ(){return gf()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="android"}function oQ(){return gf()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="ios"}function L1(){return!z8()&&!!(0,Dc.getNavigator)()&&!!(0,Dc.getDocument)()}function V8(){return gf()?bi.reactNative:z8()?bi.node:L1()?bi.browser:bi.unknown}function YB(){try{return gf()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function wRe(e,t){let r=new URLSearchParams(e);return Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!=null&&r.set(n,String(o))}),r.toString()}function sQ(e){let t=JB();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter(r=>r!=="")),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(r){return console.warn("Error populating app metadata",r),e||t}}function JB(){return(0,eQ.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function bRe(){if(V8()===bi.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let e=iA();if(e===null)return"unknown";let t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function xRe(){let e=V8();return e===bi.browser?[e,(0,Dc.getLocation)()?.host||"unknown"].join(":"):e}function QB(e,t,r){let n=bRe(),o=xRe();return[[e,t].join("-"),[yRe,r].join("-"),n,o].join("/")}function iQ({protocol:e,version:t,relayUrl:r,sdkVersion:n,auth:o,projectId:s,useOnCloseEvent:i,bundleId:a,packageName:c}){let u=r.split("?"),d=QB(e,t,n),f={auth:o,ua:d,projectId:s,useOnCloseEvent:i||void 0,packageName:c||void 0,bundleId:a||void 0},p=wRe(u[1]||"",f);return u[0]+"?"+p}function U1(e,t){return e.filter(r=>t.includes(r)).length===e.length}function ZC(e){return Object.fromEntries(e.entries())}function GC(e){return new Map(Object.entries(e))}function yf(e=mf.FIVE_MINUTES,t){let r=(0,mf.toMiliseconds)(e||mf.FIVE_MINUTES),n,o,s,i;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),i=Promise.resolve(a))},reject:a=>{s&&o&&(clearTimeout(s),o(a))},done:()=>new Promise((a,c)=>{if(i)return a(i);s=setTimeout(()=>{let u=Se("EXPIRED"),d=new Error(t||u.message);d.code=u.code,c(d)},r),n=a,o=c})}}function Wa(e,t,r){return new Promise(async(n,o)=>{let s=setTimeout(()=>o(new Error(r)),t);try{let i=await e;n(i)}catch(i){o(i)}clearTimeout(s)})}function aQ(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function cQ(e){return aQ("topic",e)}function lQ(e){return aQ("id",e)}function YC(e){let[t,r]=e.split(":"),n={id:void 0,topic:void 0};if(t==="topic"&&typeof r=="string")n.topic=r;else if(t==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);return n}function ln(e,t){return(0,mf.fromMiliseconds)((t||Date.now())+(0,mf.toMiliseconds)(e))}function ca(e){return Date.now()>=(0,mf.toMiliseconds)(e)}function ir(e,t){return`${e}${t?`:${t}`:""}`}function Uc(e=[],t=[]){return[...new Set([...e,...t])]}async function uQ({id:e,topic:t,wcDeepLink:r}){try{if(!r)return;let n=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof n!="string")return;let o=vRe(n,e,t),s=V8();if(s===bi.browser){if(!(0,Dc.getDocument)()?.hasFocus()){console.warn("Document does not have focus, skipping deeplink.");return}ERe(o)}else s===bi.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(o)}catch(n){console.error(n)}}function vRe(e,t,r){let n=`requestId=${t}&sessionTopic=${r}`;e.endsWith("/")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith("https://t.me")){let s=e.includes("?")?"&startapp=":"?startapp=";o=`${o}${s}${SRe(n,!0)}`}else o=`${o}/wc?${n}`;return o}function ERe(e){let t="_self";CRe()?t="_top":(ARe()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function dQ(e,t){let r="";try{if(L1()&&(r=localStorage.getItem(t),r))return r;r=await e.getItem(t)}catch(n){console.error(n)}return r}function XB(e,t){if(!e.includes(t))return null;let r=e.split(/([&,?,=])/),n=r.indexOf(t);return r[n+2]}function ek(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function j8(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function ARe(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function CRe(){try{return window.self!==window.top}catch{return!1}}function SRe(e,t=!1){let r=new TextEncoder().encode(e),n=new Array(r.length);for(let s=0;ssetTimeout(t,e))}var jC=class{constructor({limit:t}){this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){let r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(t)}}has(t){return this.set.has(t)}},IRe="https://rpc.walletconnect.org/v1";function ew(e){let t=e+"=".repeat((4-e.length%4)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o>o&s),a=Number(r&s),c=n?4:0,u=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+u,a,n)}function lK(e,t,r){return e&t^~e&r}function uK(e,t,r){return e&t^e&r^t&r}var r8=class extends Ol{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=gA(this.buffer)}update(t){Fa(this),t=Qo(t),Cn(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;io-i&&(this.process(n,0),i=0);for(let f=i;fd.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f>>3,w=Rc(h,17)^Rc(h,19)^h>>>10;Gp[f]=w+Gp[f-7]+y+Gp[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:d}=this;for(let f=0;f<64;f++){let p=Rc(a,6)^Rc(a,11)^Rc(a,25),h=d+p+lK(a,c,u)+jSe[f]+Gp[f]|0,w=(Rc(n,2)^Rc(n,13)^Rc(n,22))+uK(n,o,s)|0;d=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,u,d)}roundClean(){fo(Gp)}destroy(){this.set(0,0,0,0,0,0,0,0),fo(this.buffer)}};var dK=mA(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),qSe=dK[0],WSe=dK[1],Yp=new Uint32Array(80),Jp=new Uint32Array(80),n8=class extends r8{constructor(t=64){super(128,t,16,!1),this.Ah=Do[0]|0,this.Al=Do[1]|0,this.Bh=Do[2]|0,this.Bl=Do[3]|0,this.Ch=Do[4]|0,this.Cl=Do[5]|0,this.Dh=Do[6]|0,this.Dl=Do[7]|0,this.Eh=Do[8]|0,this.El=Do[9]|0,this.Fh=Do[10]|0,this.Fl=Do[11]|0,this.Gh=Do[12]|0,this.Gl=Do[13]|0,this.Hh=Do[14]|0,this.Hl=Do[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:d,Fh:f,Fl:p,Gh:h,Gl:y,Hh:w,Hl:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=y|0,this.Hh=w|0,this.Hl=x|0}process(t,r){for(let E=0;E<16;E++,r+=4)Yp[E]=t.getUint32(r),Jp[E]=t.getUint32(r+=4);for(let E=16;E<80;E++){let S=Yp[E-15]|0,_=Jp[E-15]|0,O=Nl(S,_,1)^Nl(S,_,8)^XN(S,_,7),D=Rl(S,_,1)^Rl(S,_,8)^eR(S,_,7),M=Yp[E-2]|0,N=Jp[E-2]|0,L=Nl(M,N,19)^u1(M,N,61)^XN(M,N,6),P=Rl(M,N,19)^d1(M,N,61)^eR(M,N,6),R=jW(D,P,Jp[E-7],Jp[E-16]),I=qW(R,O,L,Yp[E-7],Yp[E-16]);Yp[E]=I|0,Jp[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:d,Eh:f,El:p,Fh:h,Fl:y,Gh:w,Gl:x,Hh:v,Hl:T}=this;for(let E=0;E<80;E++){let S=Nl(f,p,14)^Nl(f,p,18)^u1(f,p,41),_=Rl(f,p,14)^Rl(f,p,18)^d1(f,p,41),O=f&h^~f&w,D=p&y^~p&x,M=WW(T,_,D,WSe[E],Jp[E]),N=KW(M,v,S,O,qSe[E],Yp[E]),L=M|0,P=Nl(n,o,28)^u1(n,o,34)^u1(n,o,39),R=Rl(n,o,28)^d1(n,o,34)^d1(n,o,39),I=n&s^n&a^s&a,B=o&i^o&c^i&c;v=w|0,T=x|0,w=h|0,x=y|0,h=f|0,y=p|0,{h:f,l:p}=ra(u|0,d|0,N|0,L|0),u=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Xx(L,R,B);n=e8(C,N,P,I),o=C|0}({h:n,l:o}=ra(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ra(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ra(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=ra(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:p}=ra(this.Eh|0,this.El|0,f|0,p|0),{h,l:y}=ra(this.Fh|0,this.Fl|0,h|0,y|0),{h:w,l:x}=ra(this.Gh|0,this.Gl|0,w|0,x|0),{h:v,l:T}=ra(this.Hh|0,this.Hl|0,v|0,T|0),this.set(n,o,s,i,a,c,u,d,f,p,h,y,w,x,v,T)}roundClean(){fo(Yp,Jp)}destroy(){fo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},nR=class extends n8{constructor(){super(48),this.Ah=Uo[0]|0,this.Al=Uo[1]|0,this.Bh=Uo[2]|0,this.Bl=Uo[3]|0,this.Ch=Uo[4]|0,this.Cl=Uo[5]|0,this.Dh=Uo[6]|0,this.Dl=Uo[7]|0,this.Eh=Uo[8]|0,this.El=Uo[9]|0,this.Fh=Uo[10]|0,this.Fl=Uo[11]|0,this.Gh=Uo[12]|0,this.Gl=Uo[13]|0,this.Hh=Uo[14]|0,this.Hl=Uo[15]|0}};var Xo=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);var oR=class extends n8{constructor(){super(32),this.Ah=Xo[0]|0,this.Al=Xo[1]|0,this.Bh=Xo[2]|0,this.Bl=Xo[3]|0,this.Ch=Xo[4]|0,this.Cl=Xo[5]|0,this.Dh=Xo[6]|0,this.Dl=Xo[7]|0,this.Eh=Xo[8]|0,this.El=Xo[9]|0,this.Fh=Xo[10]|0,this.Fl=Xo[11]|0,this.Gh=Xo[12]|0,this.Gl=Xo[13]|0,this.Hh=Xo[14]|0,this.Hl=Xo[15]|0}},Zd=g1(()=>new wA);var bA=g1(()=>new n8),fK=g1(()=>new nR),pK=g1(()=>new oR);var o8=Zd;l();l();var cR=BigInt(0),aR=BigInt(1);function T2(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function lR(e){if(!T2(e))throw new Error("Uint8Array expected")}function _2(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function s8(e){let t=e.toString(16);return t.length&1?"0"+t:t}function gK(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?cR:BigInt("0x"+e)}var yK=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",KSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function P2(e){if(lR(e),yK)return e.toHex();let t="";for(let r=0;r=Gd._0&&e<=Gd._9)return e-Gd._0;if(e>=Gd.A&&e<=Gd.F)return e-(Gd.A-10);if(e>=Gd.a&&e<=Gd.f)return e-(Gd.a-10)}function i8(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(yK)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;otypeof e=="bigint"&&cR<=e;function xA(e,t,r){return sR(e)&&sR(t)&&sR(r)&&t<=e&&ecR;e>>=aR,t+=1);return t}var b1=e=>(aR<new Uint8Array(e),mK=e=>Uint8Array.from(e);function bK(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=iR(e),o=iR(e),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>r(o,n,...f),c=(f=iR(0))=>{o=a(mK([0]),f),n=a(),f.length!==0&&(o=a(mK([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f{i(),c(f);let h;for(;!(h=p(u()));)c();return i(),h}}var ZSe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||T2(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function x1(e,t,r={}){let n=(o,s,i)=>{let a=ZSe[s];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(i&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return e}function fR(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}l();l();function xK(e,t){if(pR(e)>t)throw new vA({givenSize:pR(e),maxSize:t})}var Jd={zero:48,nine:57,A:65,F:70,a:97,f:102};function hR(e){if(e>=Jd.zero&&e<=Jd.nine)return e-Jd.zero;if(e>=Jd.A&&e<=Jd.F)return e-(Jd.A-10);if(e>=Jd.a&&e<=Jd.f)return e-(Jd.a-10)}function vK(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new EA({size:e.length,targetSize:n,type:"Bytes"});let o=new Uint8Array(n);for(let s=0;st)throw new CA({givenSize:Va(e),maxSize:t})}function EK(e,t){if(typeof t=="number"&&t>0&&t>Va(e)-1)throw new c8({offset:t,position:"start",size:Va(e)})}function AK(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Va(e)!==r-t)throw new c8({offset:r,position:"end",size:Va(e)})}function mR(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new SA({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}function CK(e,t={}){let{dir:r="left"}=t,n=e.replace("0x",""),o=0;for(let s=0;stypeof t=="function"?t(n,o):typeof o=="bigint"?o.toString()+YSe:o,r)}var JSe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function QSe(e,t={}){let{strict:r=!1}=t;if(!e)throw new IA(e);if(typeof e!="string")throw new IA(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new TA(e);if(!e.startsWith("0x"))throw new TA(e)}function _A(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function Ul(e){return e instanceof Uint8Array?na(e):Array.isArray(e)?na(new Uint8Array(e)):e}function na(e,t={}){let r="";for(let o=0;os||othis.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}};var oIe={checksum:new PA(8192)},NA=oIe.checksum;l();function NK(e,t={}){let{compressed:r}=t,{prefix:n,x:o,y:s}=e;if(r===!1||typeof o=="bigint"&&typeof s=="bigint"){if(n!==4)throw new RA({prefix:n,cause:new AR});return}if(r===!0||typeof o=="bigint"&&typeof s>"u"){if(n!==3&&n!==2)throw new RA({prefix:n,cause:new ER});return}throw new vR({publicKey:e})}function SR(e){let t=(()=>{if(bR(e))return RK(e);if(TK(e))return sIe(e);let{prefix:r,x:n,y:o}=e;return typeof n=="bigint"&&typeof o=="bigint"?{prefix:r??4,x:n,y:o}:{prefix:r,x:n}})();return NK(t),t}function sIe(e){return RK(na(e))}function RK(e){if(e.length!==132&&e.length!==130&&e.length!==68)throw new CR({publicKey:e});if(e.length===130){let n=BigInt(Oc(e,0,32)),o=BigInt(Oc(e,32,64));return{prefix:4,x:n,y:o}}if(e.length===132){let n=Number(Oc(e,0,1)),o=BigInt(Oc(e,1,33)),s=BigInt(Oc(e,33,65));return{prefix:n,x:o,y:s}}let t=Number(Oc(e,0,1)),r=BigInt(Oc(e,1,33));return{prefix:t,x:r}}function OK(e,t={}){return u8(d8(e,t))}function d8(e,t={}){NK(e);let{prefix:r,x:n,y:o}=e,{includePrefix:s=!0}=t;return _A(s?oa(r,{size:1}):"0x",oa(n,{size:32}),typeof o=="bigint"?oa(o,{size:32}):"0x")}var vR=class extends nr{constructor({publicKey:t}){super(`Value \`${Qp(t)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}},RA=class extends nr{constructor({prefix:t,cause:r}){super(`Prefix "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}},ER=class extends nr{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}},AR=class extends nr{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}},CR=class extends nr{constructor({publicKey:t}){super(`Value \`${t}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Va(Ul(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};var iIe=/^0x[a-fA-F0-9]{40}$/;function OA(e,t={}){let{strict:r=!0}=t;if(!iIe.test(e))throw new BA({address:e,cause:new TR});if(r){if(e.toLowerCase()===e)return;if(BK(e)!==e)throw new BA({address:e,cause:new _R})}}function BK(e){if(NA.has(e))return NA.get(e);OA(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=xR(IK(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());let o=`0x${n.join("")}`;return NA.set(e,o),o}function aIe(e,t={}){let{checksum:r=!1}=t;return OA(e),r?BK(e):e}function kK(e,t={}){let r=xR(`0x${d8(e).slice(4)}`).substring(26);return aIe(`0x${r}`,t)}function UK(e,t){return OA(e,{strict:!1}),OA(t,{strict:!1}),e.toLowerCase()===t.toLowerCase()}var BA=class extends nr{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}},TR=class extends nr{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}},_R=class extends nr{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}};l();var Tot=2n**(8n-1n)-1n,_ot=2n**(16n-1n)-1n,Pot=2n**(24n-1n)-1n,Not=2n**(32n-1n)-1n,Rot=2n**(40n-1n)-1n,Oot=2n**(48n-1n)-1n,Bot=2n**(56n-1n)-1n,kot=2n**(64n-1n)-1n,Uot=2n**(72n-1n)-1n,Dot=2n**(80n-1n)-1n,Lot=2n**(88n-1n)-1n,Mot=2n**(96n-1n)-1n,Hot=2n**(104n-1n)-1n,$ot=2n**(112n-1n)-1n,Fot=2n**(120n-1n)-1n,zot=2n**(128n-1n)-1n,Vot=2n**(136n-1n)-1n,jot=2n**(144n-1n)-1n,qot=2n**(152n-1n)-1n,Wot=2n**(160n-1n)-1n,Kot=2n**(168n-1n)-1n,Zot=2n**(176n-1n)-1n,Got=2n**(184n-1n)-1n,Yot=2n**(192n-1n)-1n,Jot=2n**(200n-1n)-1n,Qot=2n**(208n-1n)-1n,Xot=2n**(216n-1n)-1n,est=2n**(224n-1n)-1n,tst=2n**(232n-1n)-1n,rst=2n**(240n-1n)-1n,nst=2n**(248n-1n)-1n,ost=2n**(256n-1n)-1n,sst=-(2n**(8n-1n)),ist=-(2n**(16n-1n)),ast=-(2n**(24n-1n)),cst=-(2n**(32n-1n)),lst=-(2n**(40n-1n)),ust=-(2n**(48n-1n)),dst=-(2n**(56n-1n)),fst=-(2n**(64n-1n)),pst=-(2n**(72n-1n)),hst=-(2n**(80n-1n)),mst=-(2n**(88n-1n)),gst=-(2n**(96n-1n)),yst=-(2n**(104n-1n)),wst=-(2n**(112n-1n)),bst=-(2n**(120n-1n)),xst=-(2n**(128n-1n)),vst=-(2n**(136n-1n)),Est=-(2n**(144n-1n)),Ast=-(2n**(152n-1n)),Cst=-(2n**(160n-1n)),Sst=-(2n**(168n-1n)),Ist=-(2n**(176n-1n)),Tst=-(2n**(184n-1n)),_st=-(2n**(192n-1n)),Pst=-(2n**(200n-1n)),Nst=-(2n**(208n-1n)),Rst=-(2n**(216n-1n)),Ost=-(2n**(224n-1n)),Bst=-(2n**(232n-1n)),kst=-(2n**(240n-1n)),Ust=-(2n**(248n-1n)),Dst=-(2n**(256n-1n)),Lst=2n**8n-1n,Mst=2n**16n-1n,Hst=2n**24n-1n,$st=2n**32n-1n,Fst=2n**40n-1n,zst=2n**48n-1n,Vst=2n**56n-1n,jst=2n**64n-1n,qst=2n**72n-1n,Wst=2n**80n-1n,Kst=2n**88n-1n,Zst=2n**96n-1n,Gst=2n**104n-1n,Yst=2n**112n-1n,Jst=2n**120n-1n,Qst=2n**128n-1n,Xst=2n**136n-1n,eit=2n**144n-1n,tit=2n**152n-1n,rit=2n**160n-1n,nit=2n**168n-1n,oit=2n**176n-1n,sit=2n**184n-1n,iit=2n**192n-1n,ait=2n**200n-1n,cit=2n**208n-1n,lit=2n**216n-1n,uit=2n**224n-1n,dit=2n**232n-1n,fit=2n**240n-1n,pit=2n**248n-1n,PR=2n**256n-1n;var zA={};Te(zA,{InvalidRError:()=>LA,InvalidSError:()=>MA,InvalidSerializedSizeError:()=>DA,InvalidVError:()=>HA,InvalidYParityError:()=>C1,MissingPropertiesError:()=>O2,assert:()=>$A,extract:()=>CIe,from:()=>WR,fromBytes:()=>nZ,fromDerBytes:()=>SIe,fromDerHex:()=>oZ,fromHex:()=>qR,fromLegacy:()=>sZ,fromRpc:()=>iZ,fromTuple:()=>IIe,toBytes:()=>TIe,toDerBytes:()=>_Ie,toDerHex:()=>PIe,toHex:()=>aZ,toLegacy:()=>NIe,toRpc:()=>RIe,toTuple:()=>OIe,vToYParity:()=>FA,validate:()=>BIe,yParityToV:()=>KR});l();l();l();l();var kA=class extends Ol{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,p1(t);let n=Qo(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;inew kA(e,t).update(r).digest();Xp.create=(e,t)=>new kA(e,t);l();l();l();var Ds=BigInt(0),ts=BigInt(1),A1=BigInt(2),cIe=BigInt(3),HK=BigInt(4),$K=BigInt(5),FK=BigInt(8);function es(e,t){let r=e%t;return r>=Ds?r:t+r}function sa(e,t,r){let n=e;for(;t-- >Ds;)n*=n,n%=r;return n}function UA(e,t){if(e===Ds)throw new Error("invert: expected non-zero number");if(t<=Ds)throw new Error("invert: expected positive modulus, got "+t);let r=es(e,t),n=t,o=Ds,s=ts,i=ts,a=Ds;for(;r!==Ds;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ts)throw new Error("invert: does not exist");return es(o,t)}function zK(e,t){let r=(e.ORDER+ts)/HK,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function lIe(e,t){let r=(e.ORDER-$K)/FK,n=e.mul(t,A1),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,A1),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function uIe(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return zK;let s=o.pow(n,t),i=(t+ts)/A1;return function(c,u){if(c.is0(u))return u;if(MK(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ts<(n[o]="function",n),t);return x1(e,r)}function pIe(e,t,r){if(rDs;)r&ts&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ts;return n}function RR(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function MK(e,t){let r=(e.ORDER-ts)/A1,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function OR(e,t){t!==void 0&&Jo(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function f8(e,t,r=!1,n={}){if(e<=Ds)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:s}=OR(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:b1(o),ZERO:Ds,ONE:ts,create:c=>es(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ds<=c&&cc===Ds,isOdd:c=>(c&ts)===ts,neg:c=>es(-c,e),eql:(c,u)=>c===u,sqr:c=>es(c*c,e),add:(c,u)=>es(c+u,e),sub:(c,u)=>es(c-u,e),mul:(c,u)=>es(c*u,e),pow:(c,u)=>pIe(a,c,u),div:(c,u)=>es(c*UA(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>UA(c,e),sqrt:n.sqrt||(c=>(i||(i=dIe(e)),i(a,c))),toBytes:c=>r?dR(c,s):y1(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?uR(c):Yd(c)},invertBatch:c=>RR(a,c),cmov:(c,u,d)=>d?u:c});return Object.freeze(a)}function VK(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function BR(e){let t=VK(e);return t+Math.ceil(t/2)}function jK(e,t,r=!1){let n=e.length,o=VK(t),s=BR(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?uR(e):Yd(e),a=es(i,t-ts)+ts;return r?dR(a,o):y1(a,o)}var qK=BigInt(0),MR=BigInt(1);function kR(e,t){let r=t.negate();return e?r:t}function KK(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function UR(e,t){KK(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=b1(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function WK(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=MR);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function hIe(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function mIe(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var DR=new WeakMap,ZK=new WeakMap;function LR(e){return ZK.get(e)||1}function GK(e,t){return{constTimeNegate:kR,hasPrecomputes(r){return LR(r)!==1},unsafeLadder(r,n,o=e.ZERO){let s=r;for(;n>qK;)n&MR&&(o=o.add(s)),s=s.double(),n>>=MR;return o},precomputeWindow(r,n){let{windows:o,windowSize:s}=UR(n,t),i=[],a=r,c=a;for(let u=0;u12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=b1(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;w{let{Err:r}=Qd;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=s8(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?s8(o.length/2|128):"";return s8(e)+s+o+t},decode(e,t){let{Err:r}=Qd,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Qd;if(e{let O=S.toAffine();return a8(Uint8Array.from([4]),r.toBytes(O.x),r.toBytes(O.y))}),s=t.fromBytes||(E=>{let S=E.subarray(1),_=r.fromBytes(S.subarray(0,r.BYTES)),O=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:_,y:O}});function i(E){let{a:S,b:_}=t,O=r.sqr(E),D=r.mul(O,E);return r.add(r.add(D,r.mul(E,S)),_)}function a(E,S){let _=r.sqr(S),O=i(E);return r.eql(_,O)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,FR),yIe),u=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function d(E){return xA(E,po,t.n)}function f(E){let{allowedPrivateKeyLengths:S,nByteLength:_,wrapPrivateKey:O,n:D}=t;if(S&&typeof E!="bigint"){if(T2(E)&&(E=P2(E)),typeof E!="string"||!S.includes(E.length))throw new Error("invalid private key");E=E.padStart(_*2,"0")}let M;try{M=typeof E=="bigint"?E:Yd(gi("private key",E,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof E)}return O&&(M=es(M,D)),w1("private key",M,po,D),M}function p(E){if(!(E instanceof w))throw new Error("ProjectivePoint expected")}let h=fR((E,S)=>{let{px:_,py:O,pz:D}=E;if(r.eql(D,r.ONE))return{x:_,y:O};let M=E.is0();S==null&&(S=M?r.ONE:r.inv(D));let N=r.mul(_,S),L=r.mul(O,S),P=r.mul(D,S);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),y=fR(E=>{if(E.is0()){if(t.allowInfinityPoint&&!r.is0(E.py))return;throw new Error("bad point: ZERO")}let{x:S,y:_}=E.toAffine();if(!r.isValid(S)||!r.isValid(_))throw new Error("bad point: x or y not FE");if(!a(S,_))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(S,_,O){if(S==null||!r.isValid(S))throw new Error("x required");if(_==null||!r.isValid(_)||r.is0(_))throw new Error("y required");if(O==null||!r.isValid(O))throw new Error("z required");this.px=S,this.py=_,this.pz=O,Object.freeze(this)}static fromAffine(S){let{x:_,y:O}=S||{};if(!S||!r.isValid(_)||!r.isValid(O))throw new Error("invalid affine point");if(S instanceof w)throw new Error("projective point not allowed");let D=M=>r.eql(M,r.ZERO);return D(_)&&D(O)?w.ZERO:new w(_,O,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){let _=RR(r,S.map(O=>O.pz));return S.map((O,D)=>O.toAffine(_[D])).map(w.fromAffine)}static fromHex(S){let _=w.fromAffine(s(gi("pointHex",S)));return _.assertValidity(),_}static fromPrivateKey(S){return w.BASE.multiply(f(S))}static msm(S,_){return YK(w,n,S,_)}_setWindowSize(S){T.setWindowSize(this,S)}assertValidity(){y(this)}hasEvenY(){let{y:S}=this.toAffine();if(r.isOdd)return!r.isOdd(S);throw new Error("Field doesn't support isOdd")}equals(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.eql(r.mul(_,L),r.mul(M,D)),R=r.eql(r.mul(O,L),r.mul(N,D));return P&&R}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){let{a:S,b:_}=t,O=r.mul(_,FR),{px:D,py:M,pz:N}=this,L=r.ZERO,P=r.ZERO,R=r.ZERO,I=r.mul(D,D),B=r.mul(M,M),C=r.mul(N,N),A=r.mul(D,M);return A=r.add(A,A),R=r.mul(D,N),R=r.add(R,R),L=r.mul(S,R),P=r.mul(O,C),P=r.add(L,P),L=r.sub(B,P),P=r.add(B,P),P=r.mul(L,P),L=r.mul(A,L),R=r.mul(O,R),C=r.mul(S,C),A=r.sub(I,C),A=r.mul(S,A),A=r.add(A,R),R=r.add(I,I),I=r.add(R,I),I=r.add(I,C),I=r.mul(I,A),P=r.add(P,I),C=r.mul(M,N),C=r.add(C,C),I=r.mul(C,A),L=r.sub(L,I),R=r.mul(C,B),R=r.add(R,R),R=r.add(R,R),new w(L,P,R)}add(S){p(S);let{px:_,py:O,pz:D}=this,{px:M,py:N,pz:L}=S,P=r.ZERO,R=r.ZERO,I=r.ZERO,B=t.a,C=r.mul(t.b,FR),A=r.mul(_,M),U=r.mul(O,N),H=r.mul(D,L),k=r.add(_,O),F=r.add(M,N);k=r.mul(k,F),F=r.add(A,U),k=r.sub(k,F),F=r.add(_,D);let j=r.add(M,L);return F=r.mul(F,j),j=r.add(A,H),F=r.sub(F,j),j=r.add(O,D),P=r.add(N,L),j=r.mul(j,P),P=r.add(U,H),j=r.sub(j,P),I=r.mul(B,F),P=r.mul(C,H),I=r.add(P,I),P=r.sub(U,I),I=r.add(U,I),R=r.mul(P,I),U=r.add(A,A),U=r.add(U,A),H=r.mul(B,H),F=r.mul(C,F),U=r.add(U,H),H=r.sub(A,H),H=r.mul(B,H),F=r.add(F,H),A=r.mul(U,F),R=r.add(R,A),A=r.mul(j,F),P=r.mul(k,P),P=r.sub(P,A),A=r.mul(k,U),I=r.mul(j,I),I=r.add(I,A),new w(P,R,I)}subtract(S){return this.add(S.negate())}is0(){return this.equals(w.ZERO)}wNAF(S){return T.wNAFCached(this,S,w.normalizeZ)}multiplyUnsafe(S){let{endo:_,n:O}=t;w1("scalar",S,Xd,O);let D=w.ZERO;if(S===Xd)return D;if(this.is0()||S===po)return this;if(!_||T.hasPrecomputes(this))return T.wNAFCachedUnsafe(this,S,w.normalizeZ);let{k1neg:M,k1:N,k2neg:L,k2:P}=_.splitScalar(S),R=D,I=D,B=this;for(;N>Xd||P>Xd;)N&po&&(R=R.add(B)),P&po&&(I=I.add(B)),B=B.double(),N>>=po,P>>=po;return M&&(R=R.negate()),L&&(I=I.negate()),I=new w(r.mul(I.px,_.beta),I.py,I.pz),R.add(I)}multiply(S){let{endo:_,n:O}=t;w1("scalar",S,po,O);let D,M;if(_){let{k1neg:N,k1:L,k2neg:P,k2:R}=_.splitScalar(S),{p:I,f:B}=this.wNAF(L),{p:C,f:A}=this.wNAF(R);I=T.constTimeNegate(N,I),C=T.constTimeNegate(P,C),C=new w(r.mul(C.px,_.beta),C.py,C.pz),D=I.add(C),M=B.add(A)}else{let{p:N,f:L}=this.wNAF(S);D=N,M=L}return w.normalizeZ([D,M])[0]}multiplyAndAddUnsafe(S,_,O){let D=w.BASE,M=(L,P)=>P===Xd||P===po||!L.equals(D)?L.multiplyUnsafe(P):L.multiply(P),N=M(this,_).add(M(S,O));return N.is0()?void 0:N}toAffine(S){return h(this,S)}isTorsionFree(){let{h:S,isTorsionFree:_}=t;if(S===po)return!0;if(_)return _(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:S,clearCofactor:_}=t;return S===po?this:_?_(w,this):this.multiplyUnsafe(t.h)}toRawBytes(S=!0){return _2("isCompressed",S),this.assertValidity(),o(w,this,S)}toHex(S=!0){return _2("isCompressed",S),P2(this.toRawBytes(S))}}w.BASE=new w(t.Gx,t.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);let{endo:x,nBitLength:v}=t,T=GK(w,x?Math.ceil(v/2):v);return{CURVE:t,ProjectivePoint:w,normPrivateKeyToScalar:f,weierstrassEquation:i,isWithinCurveOrder:d}}function bIe(e){let t=HR(e);return x1(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function QK(e){let t=bIe(e),{Fp:r,n,nByteLength:o,nBitLength:s}=t,i=r.BYTES+1,a=2*r.BYTES+1;function c(C){return es(C,n)}function u(C){return UA(C,n)}let{ProjectivePoint:d,normPrivateKeyToScalar:f,weierstrassEquation:p,isWithinCurveOrder:h}=wIe({...t,toBytes(C,A,U){let H=A.toAffine(),k=r.toBytes(H.x),F=a8;return _2("isCompressed",U),U?F(Uint8Array.from([A.hasEvenY()?2:3]),k):F(Uint8Array.from([4]),k,r.toBytes(H.y))},fromBytes(C){let A=C.length,U=C[0],H=C.subarray(1);if(A===i&&(U===2||U===3)){let k=Yd(H);if(!xA(k,po,r.ORDER))throw new Error("Point is not on curve");let F=p(k),j;try{j=r.sqrt(F)}catch(te){let X=te instanceof Error?": "+te.message:"";throw new Error("Point is not on curve"+X)}let W=(j&po)===po;return(U&1)===1!==W&&(j=r.neg(j)),{x:k,y:j}}else if(A===a&&U===4){let k=r.fromBytes(H.subarray(0,r.BYTES)),F=r.fromBytes(H.subarray(r.BYTES,2*r.BYTES));return{x:k,y:F}}else{let k=i,F=a;throw new Error("invalid Point, expected length of "+k+", or uncompressed "+F+", got "+A)}}});function y(C){let A=n>>po;return C>A}function w(C){return y(C)?c(-C):C}let x=(C,A,U)=>Yd(C.slice(A,U));class v{constructor(A,U,H){w1("r",A,po,n),w1("s",U,po,n),this.r=A,this.s=U,H!=null&&(this.recovery=H),Object.freeze(this)}static fromCompact(A){let U=o;return A=gi("compactSignature",A,U*2),new v(x(A,0,U),x(A,U,2*U))}static fromDER(A){let{r:U,s:H}=Qd.toSig(gi("DER",A));return new v(U,H)}assertValidity(){}addRecoveryBit(A){return new v(this.r,this.s,A)}recoverPublicKey(A){let{r:U,s:H,recovery:k}=this,F=D(gi("msgHash",A));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let j=k===2||k===3?U+t.n:U;if(j>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=(k&1)===0?"02":"03",ae=d.fromHex(W+$R(j,r.BYTES)),te=u(j),X=c(-F*te),pe=c(H*te),me=d.BASE.multiplyAndAddUnsafe(ae,X,pe);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return i8(this.toDERHex())}toDERHex(){return Qd.hexFromSig(this)}toCompactRawBytes(){return i8(this.toCompactHex())}toCompactHex(){let A=o;return $R(this.r,A)+$R(this.s,A)}}let T={isValidPrivateKey(C){try{return f(C),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let C=BR(t.n);return jK(t.randomBytes(C),t.n)},precompute(C=8,A=d.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}};function E(C,A=!0){return d.fromPrivateKey(C).toRawBytes(A)}function S(C){if(typeof C=="bigint")return!1;if(C instanceof d)return!0;let U=gi("key",C).length,H=r.BYTES,k=H+1,F=2*H+1;if(!(t.allowedPrivateKeyLengths||o===k))return U===k||U===F}function _(C,A,U=!0){if(S(C)===!0)throw new Error("first arg must be private key");if(S(A)===!1)throw new Error("second arg must be public key");return d.fromHex(A).multiply(f(C)).toRawBytes(U)}let O=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=Yd(C),U=C.length*8-s;return U>0?A>>BigInt(U):A},D=t.bits2int_modN||function(C){return c(O(C))},M=b1(s);function N(C){return w1("num < 2^"+s,C,Xd,M),y1(C,o)}function L(C,A,U=P){if(["recovered","canonical"].some(ye=>ye in U))throw new Error("sign() legacy options not supported");let{hash:H,randomBytes:k}=t,{lowS:F,prehash:j,extraEntropy:W}=U;F==null&&(F=!0),C=gi("msgHash",C),JK(U),j&&(C=gi("prehashed msgHash",H(C)));let ae=D(C),te=f(A),X=[N(te),N(ae)];if(W!=null&&W!==!1){let ye=W===!0?k(r.BYTES):W;X.push(gi("extraEntropy",ye))}let pe=a8(...X),me=ae;function Ne(ye){let Re=O(ye);if(!h(Re))return;let Et=u(Re),kt=d.BASE.multiply(Re).toAffine(),At=c(kt.x);if(At===Xd)return;let ur=c(Et*c(me+At*te));if(ur===Xd)return;let _r=(kt.x===At?0:2)|Number(kt.y&po),Pl=ur;return F&&y(ur)&&(Pl=w(ur),_r^=1),new v(At,Pl,_r)}return{seed:pe,k2sig:Ne}}let P={lowS:t.lowS,prehash:!1},R={lowS:t.lowS,prehash:!1};function I(C,A,U=P){let{seed:H,k2sig:k}=L(C,A,U),F=t;return bK(F.hash.outputLen,F.nByteLength,F.hmac)(H,k)}d.BASE._setWindowSize(8);function B(C,A,U,H=R){let k=C;A=gi("msgHash",A),U=gi("publicKey",U);let{lowS:F,prehash:j,format:W}=H;if(JK(H),"strict"in H)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");let ae=typeof k=="string"||T2(k),te=!ae&&!W&&typeof k=="object"&&k!==null&&typeof k.r=="bigint"&&typeof k.s=="bigint";if(!ae&&!te)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,pe;try{if(te&&(X=new v(k.r,k.s)),ae){try{W!=="compact"&&(X=v.fromDER(k))}catch(_r){if(!(_r instanceof Qd.Err))throw _r}!X&&W!=="der"&&(X=v.fromCompact(k))}pe=d.fromHex(U)}catch{return!1}if(!X||F&&X.hasHighS())return!1;j&&(A=t.hash(A));let{r:me,s:Ne}=X,ye=D(A),Re=u(Ne),Et=c(ye*Re),kt=c(me*Re),At=d.BASE.multiplyAndAddUnsafe(pe,Et,kt)?.toAffine();return At?c(At.x)===me:!1}return{CURVE:t,getPublicKey:E,getSharedSecret:_,sign:I,verify:B,ProjectivePoint:d,Signature:v,utils:T}}function xIe(e){return{hash:e,hmac:(t,...r)=>Xp(e,t,ko(...r)),randomBytes:Us}}function XK(e,t){let r=n=>QK({...e,...xIe(n)});return{...r(t),create:r}}var rZ=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),eZ=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),vIe=BigInt(0),EIe=BigInt(1),VR=BigInt(2),tZ=(e,t)=>(e+t/VR)/t;function AIe(e){let t=rZ,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,d=u*u*e%t,f=sa(d,r,t)*d%t,p=sa(f,r,t)*d%t,h=sa(p,VR,t)*u%t,y=sa(h,o,t)*h%t,w=sa(y,s,t)*y%t,x=sa(w,a,t)*w%t,v=sa(x,c,t)*x%t,T=sa(v,a,t)*w%t,E=sa(T,r,t)*d%t,S=sa(E,i,t)*y%t,_=sa(S,n,t)*u%t,O=sa(_,VR,t);if(!jR.eql(jR.sqr(O),e))throw new Error("Cannot find square root");return O}var jR=f8(rZ,void 0,void 0,{sqrt:AIe}),ia=XK({a:vIe,b:BigInt(7),Fp:jR,n:eZ,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=eZ,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-EIe*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=tZ(s*e,t),c=tZ(-n*e,t),u=es(e-a*r-c*o,t),d=es(-a*n-c*s,t),f=u>i,p=d>i;if(f&&(u=t-u),p&&(d=t-d),u>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}}},Zd);function $A(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new O2({signature:e});if(typeof e.s>"u")throw new O2({signature:e});if(r&&typeof e.yParity>"u")throw new O2({signature:e});if(e.r<0n||e.r>PR)throw new LA({value:e.r});if(e.s<0n||e.s>PR)throw new MA({value:e.s});if(typeof e.yParity=="number"&&e.yParity!==0&&e.yParity!==1)throw new C1({value:e.yParity})}function nZ(e){return qR(na(e))}function qR(e){if(e.length!==130&&e.length!==132)throw new DA({signature:e});let t=BigInt(Oc(e,0,32)),r=BigInt(Oc(e,32,64)),n=(()=>{let o=+`0x${e.slice(130)}`;if(!Number.isNaN(o))try{return FA(o)}catch{throw new C1({value:o})}})();return typeof n>"u"?{r:t,s:r}:{r:t,s:r,yParity:n}}function CIe(e){if(!(typeof e.r>"u")&&!(typeof e.s>"u"))return WR(e)}function WR(e){let t=typeof e=="string"?qR(e):e instanceof Uint8Array?nZ(e):typeof e.r=="string"?iZ(e):e.v?sZ(e):{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}};return $A(t),t}function SIe(e){return oZ(na(e))}function oZ(e){let{r:t,s:r}=ia.Signature.fromDER(Ul(e).slice(2));return{r:t,s:r}}function sZ(e){return{r:e.r,s:e.s,yParity:FA(e.v)}}function iZ(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r=="number"&&typeof n!="number"&&(n=FA(r)),typeof n!="number")throw new C1({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function IIe(e){let[t,r,n]=e;return WR({r:r==="0x"?0n:BigInt(r),s:n==="0x"?0n:BigInt(n),yParity:t==="0x"?0:Number(t)})}function TIe(e){return u8(aZ(e))}function aZ(e){$A(e);let t=e.r,r=e.s;return _A(oa(t,{size:32}),oa(r,{size:32}),typeof e.yParity=="number"?oa(KR(e.yParity),{size:1}):"0x")}function _Ie(e){return new ia.Signature(e.r,e.s).toDERRawBytes()}function PIe(e){return`0x${new ia.Signature(e.r,e.s).toDERHex()}`}function NIe(e){return{r:e.r,s:e.s,v:KR(e.yParity)}}function RIe(e){let{r:t,s:r,yParity:n}=e;return{r:oa(t,{size:32}),s:oa(r,{size:32}),yParity:n===0?"0x0":"0x1"}}function OIe(e){let{r:t,s:r,yParity:n}=e;return[n?"0x01":"0x",t===0n?"0x":wR(oa(t)),r===0n?"0x":wR(oa(r))]}function BIe(e,t={}){try{return $A(e,t),!0}catch{return!1}}function FA(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new HA({value:e})}function KR(e){if(e===0)return 27;if(e===1)return 28;throw new C1({value:e})}var DA=class extends nr{constructor({signature:t}){super(`Value \`${t}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Va(Ul(t))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}},O2=class extends nr{constructor({signature:t}){super(`Signature \`${Qp(t)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}},LA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid r value. r must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}},MA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid s value. s must be a positive integer less than 2^256.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}},C1=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}},HA=class extends nr{constructor({value:t}){super(`Value \`${t}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}};l();l();var cZ=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]);var Xn=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Be=new Uint32Array(32);function eh(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=Be[2*e],u=Be[2*e+1],d=Be[2*t],f=Be[2*t+1],p=Be[2*r],h=Be[2*r+1],y=Be[2*n],w=Be[2*n+1],x=Xx(c,d,i);u=e8(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:MW(w,y),Dl:HW(w,y)},{h,l:p}=ra(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:Nl(f,d,24),Bl:Rl(f,d,24)},Be[2*e]=c,Be[2*e+1]=u,Be[2*t]=d,Be[2*t+1]=f,Be[2*r]=p,Be[2*r+1]=h,Be[2*n]=y,Be[2*n+1]=w}function th(e,t,r,n,o,s){let i=o[s],a=o[s+1],c=Be[2*e],u=Be[2*e+1],d=Be[2*t],f=Be[2*t+1],p=Be[2*r],h=Be[2*r+1],y=Be[2*n],w=Be[2*n+1],x=Xx(c,d,i);u=e8(x,u,f,a),c=x|0,{Dh:w,Dl:y}={Dh:w^u,Dl:y^c},{Dh:w,Dl:y}={Dh:Nl(w,y,16),Dl:Rl(w,y,16)},{h,l:p}=ra(h,p,w,y),{Bh:f,Bl:d}={Bh:f^h,Bl:d^p},{Bh:f,Bl:d}={Bh:u1(f,d,63),Bl:d1(f,d,63)},Be[2*e]=c,Be[2*e+1]=u,Be[2*t]=d,Be[2*t+1]=f,Be[2*r]=p,Be[2*r+1]=h,Be[2*n]=y,Be[2*n+1]=w}function kIe(e,t={},r,n,o){if(Jo(r),e<0||e>r)throw new Error("outputLen bigger than keyLen");let{key:s,salt:i,personalization:a}=t;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(i!==void 0&&i.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==o)throw new Error("personalization must be undefined or "+o)}var ZR=class extends Ol{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Jo(t),Jo(r),this.blockLen=t,this.outputLen=r,this.buffer=new Uint8Array(t),this.buffer32=h1(this.buffer)}update(t){Fa(this),t=Qo(t),Cn(t);let{blockLen:r,buffer:n,buffer32:o}=this,s=t.length,i=t.byteOffset,a=t.buffer;for(let c=0;co[i]=Bl(s))}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){let{buffer:r,length:n,finished:o,destroyed:s,outputLen:i,pos:a}=this;return t||(t=new this.constructor({dkLen:i})),t.set(...this.get()),t.buffer.set(r),t.destroyed=s,t.finished=o,t.length=n,t.pos=a,t.outputLen=i,t}clone(){return this._cloneInto()}},GR=class extends ZR{constructor(t={}){let r=t.dkLen===void 0?64:t.dkLen;super(128,r),this.v0l=Xn[0]|0,this.v0h=Xn[1]|0,this.v1l=Xn[2]|0,this.v1h=Xn[3]|0,this.v2l=Xn[4]|0,this.v2h=Xn[5]|0,this.v3l=Xn[6]|0,this.v3h=Xn[7]|0,this.v4l=Xn[8]|0,this.v4h=Xn[9]|0,this.v5l=Xn[10]|0,this.v5h=Xn[11]|0,this.v6l=Xn[12]|0,this.v6h=Xn[13]|0,this.v7l=Xn[14]|0,this.v7h=Xn[15]|0,kIe(r,t,64,16,16);let{key:n,personalization:o,salt:s}=t,i=0;if(n!==void 0&&(n=Qo(n),i=n.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){s=Qo(s);let a=h1(s);this.v4l^=Bl(a[0]),this.v4h^=Bl(a[1]),this.v5l^=Bl(a[2]),this.v5h^=Bl(a[3])}if(o!==void 0){o=Qo(o);let a=h1(o);this.v6l^=Bl(a[0]),this.v6h^=Bl(a[1]),this.v7l^=Bl(a[2]),this.v7h^=Bl(a[3])}if(n!==void 0){let a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:t,v0h:r,v1l:n,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:u,v4h:d,v5l:f,v5h:p,v6l:h,v6h:y,v7l:w,v7h:x}=this;return[t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x]}set(t,r,n,o,s,i,a,c,u,d,f,p,h,y,w,x){this.v0l=t|0,this.v0h=r|0,this.v1l=n|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=d|0,this.v5l=f|0,this.v5h=p|0,this.v6l=h|0,this.v6h=y|0,this.v7l=w|0,this.v7h=x|0}compress(t,r,n){this.get().forEach((c,u)=>Be[u]=c),Be.set(Xn,16);let{h:o,l:s}=QN(BigInt(this.length));Be[24]=Xn[8]^s,Be[25]=Xn[9]^o,n&&(Be[28]=~Be[28],Be[29]=~Be[29]);let i=0,a=cZ;for(let c=0;c<12;c++)eh(0,4,8,12,t,r+2*a[i++]),th(0,4,8,12,t,r+2*a[i++]),eh(1,5,9,13,t,r+2*a[i++]),th(1,5,9,13,t,r+2*a[i++]),eh(2,6,10,14,t,r+2*a[i++]),th(2,6,10,14,t,r+2*a[i++]),eh(3,7,11,15,t,r+2*a[i++]),th(3,7,11,15,t,r+2*a[i++]),eh(0,5,10,15,t,r+2*a[i++]),th(0,5,10,15,t,r+2*a[i++]),eh(1,6,11,12,t,r+2*a[i++]),th(1,6,11,12,t,r+2*a[i++]),eh(2,7,8,13,t,r+2*a[i++]),th(2,7,8,13,t,r+2*a[i++]),eh(3,4,9,14,t,r+2*a[i++]),th(3,4,9,14,t,r+2*a[i++]);this.v0l^=Be[0]^Be[16],this.v0h^=Be[1]^Be[17],this.v1l^=Be[2]^Be[18],this.v1h^=Be[3]^Be[19],this.v2l^=Be[4]^Be[20],this.v2h^=Be[5]^Be[21],this.v3l^=Be[6]^Be[22],this.v3h^=Be[7]^Be[23],this.v4l^=Be[8]^Be[24],this.v4h^=Be[9]^Be[25],this.v5l^=Be[10]^Be[26],this.v5h^=Be[11]^Be[27],this.v6l^=Be[12]^Be[28],this.v6h^=Be[13]^Be[29],this.v7l^=Be[14]^Be[30],this.v7h^=Be[15]^Be[31],fo(Be)}destroy(){this.destroyed=!0,fo(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},lZ=XW(e=>new GR(e));var ZA={};Te(ZA,{createKeyPair:()=>KIe,getPublicKey:()=>CZ,getSharedSecret:()=>ZIe,noble:()=>WIe,randomPrivateKey:()=>SZ,recoverAddress:()=>IZ,recoverPublicKey:()=>TZ,sign:()=>GIe,verify:()=>YIe});l();l();var AZ=!1;var WIe=ia;function KIe(e={}){let{as:t="Hex"}=e,r=SZ({as:t}),n=CZ({privateKey:r});return{privateKey:r,publicKey:n}}function CZ(e){let{privateKey:t}=e,r=ia.ProjectivePoint.fromPrivateKey(Ul(t).slice(2));return SR(r)}function ZIe(e){let{as:t="Hex",privateKey:r,publicKey:n}=e,i=ia.ProjectivePoint.fromHex(d8(n).slice(2)).multiply(ia.utils.normPrivateKeyToScalar(Ul(r).slice(2))).toRawBytes(!0);return t==="Hex"?na(i):i}function SZ(e={}){let{as:t="Hex"}=e,r=ia.utils.randomPrivateKey();return t==="Hex"?na(r):r}function IZ(e){return kK(TZ(e))}function TZ(e){let{payload:t,signature:r}=e,{r:n,s:o,yParity:s}=r,a=new ia.Signature(BigInt(n),BigInt(o)).addRecoveryBit(s).recoverPublicKey(Ul(t).substring(2));return SR(a)}function GIe(e){let{extraEntropy:t=AZ,hash:r,payload:n,privateKey:o}=e,{r:s,s:i,recovery:a}=ia.sign(R2(n),R2(o),{extraEntropy:typeof t=="boolean"?t:Ul(t).slice(2),lowS:!0,...r?{prehash:!0}:{}});return{r:s,s:i,yParity:a}}function YIe(e){let{address:t,hash:r,payload:n,publicKey:o,signature:s}=e;return t?UK(t,IZ({payload:n,signature:s})):ia.verify(s,R2(n),OK(o),...r?[{prehash:!0,lowS:!0}]:[])}l();l();l();l();function HZ(e){let t=e.length,r=0,n=0;for(;n=55296&&o<=56319&&n>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[o++]=i>>6&63|128):(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128)}t[o++]=i&63|128}}var o9e=new TextEncoder,s9e=50;function i9e(e,t,r){o9e.encodeInto(e,t.subarray(r))}function $Z(e,t,r){e.length>s9e?i9e(e,t,r):n9e(e,t,r)}var a9e=4096;function rO(e,t,r){let n=t,o=n+r,s=[],i="";for(;n65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=a9e&&(i+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(i+=String.fromCharCode(...s)),i}var c9e=new TextDecoder,l9e=200;function u9e(e,t,r){let n=e.subarray(t,t+r);return c9e.decode(n)}function FZ(e,t,r){return r>l9e?u9e(e,t,r):rO(e,t,r)}l();l();var S1=class{type;data;constructor(t,r){this.type=t,this.data=r}};l();l();var yi=class e extends Error{constructor(t){super(t);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};l();function zZ(e,t,r){let n=r/4294967296,o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function tC(e,t,r){let n=Math.floor(r/4294967296),o=r;e.setUint32(t,n),e.setUint32(t+4,o)}function rC(e,t){let r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function VZ(e,t){let r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}var d9e=-1,f9e=4294967296-1,p9e=17179869184-1;function h9e({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=p9e)if(t===0&&e<=f9e){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,t<<2|r&3),s.setUint32(4,n),o}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),tC(n,4,e),r}}function m9e(e){let t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,o=Math.floor(n/1e9);return{sec:r+o,nsec:n-o*1e9}}function g9e(e){if(e instanceof Date){let t=m9e(e);return h9e(t)}else return null}function y9e(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let r=t.getUint32(0),n=t.getUint32(4),o=(r&3)*4294967296+n,s=r>>>2;return{sec:o,nsec:s}}case 12:{let r=rC(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new yi(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function w9e(e){let t=y9e(e);return new Date(t.sec*1e3+t.nsec/1e6)}var jZ={type:d9e,encode:g9e,decode:w9e};var k2=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(jZ)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{let o=-1-t;this.builtInEncoders[o]=r,this.builtInDecoders[o]=n}}tryToEncode(t,r){for(let n=0;nthis.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){let r=this.pos+t;this.view.byteLength=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){let n=HZ(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),$Z(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){let n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){let r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);let n=m8(t);this.writeU8a(n)}encodeArray(t,r){let n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(let o of t)this.doEncode(o,r+1)}countWithoutUndefined(t,r){let n=0;for(let o of r)t[o]!==void 0&&n++;return n}encodeMap(t,r){let n=Object.keys(t);this.sortKeys&&n.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let s of n){let i=t[s];this.ignoreUndefined&&i===void 0||(this.encodeString(s),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){let n=t.data(this.pos+6),o=n.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(t.type),this.writeU8a(n);return}let r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){let r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),zZ(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),tC(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}};function nO(e,t){return new nC(t).encodeSharedRef(e)}l();l();l();function oC(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}l();var E9e=16,A9e=16,sC=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(t=E9e,r=A9e){this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n0&&t<=this.maxKeyLength}find(t,r,n){let o=this.caches[n-1];e:for(let s of o){let i=s.bytes;for(let a=0;a=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)}decode(t,r,n){let o=this.find(t,r,n);if(o!=null)return this.hit++,o;this.miss++;let s=rO(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,s),s}};var oO="array",w8="map_key",WZ="map_value",C9e=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new yi("The type of key must be string or number but "+typeof e)},sO=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){let r=this.getUninitializedStateFromPool();r.type=oO,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){let r=this.getUninitializedStateFromPool();r.type=w8,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===oO){let n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===w8||t.type===WZ){let n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},y8=-1,iO=new DataView(new ArrayBuffer(0)),S9e=new Uint8Array(iO.buffer);try{iO.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var qZ=new RangeError("Insufficient data"),I9e=new sC,iC=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=iO;bytes=S9e;headByte=y8;stack=new sO;entered=!1;constructor(t){this.extensionCodec=t?.extensionCodec??k2.defaultCodec,this.context=t?.context,this.useBigInt64=t?.useBigInt64??!1,this.rawStrings=t?.rawStrings??!1,this.maxStrLength=t?.maxStrLength??4294967295,this.maxBinLength=t?.maxBinLength??4294967295,this.maxArrayLength=t?.maxArrayLength??4294967295,this.maxMapLength=t?.maxMapLength??4294967295,this.maxExtLength=t?.maxExtLength??4294967295,this.keyDecoder=t?.keyDecoder!==void 0?t.keyDecoder:I9e,this.mapKeyConverter=t?.mapKeyConverter??C9e}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=y8,this.stack.reset()}setBuffer(t){let r=m8(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===y8&&!this.hasRemaining(1))this.setBuffer(t);else{let r=this.bytes.subarray(this.pos),n=m8(t),o=new Uint8Array(r.length+n.length);o.set(r),o.set(n,r.length),this.setBuffer(o)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){let{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(let a of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:o,pos:s,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${oC(o)} at ${i} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,o=-1;for await(let s of t){if(r&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let t=this.readHeadByte(),r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){let o=t-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t<160){let o=t-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else{let o=t-160;r=this.decodeString(o,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){let o=this.lookU8();r=this.decodeString(o,1)}else if(t===218){let o=this.lookU16();r=this.decodeString(o,2)}else if(t===219){let o=this.lookU32();r=this.decodeString(o,4)}else if(t===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else r=[]}else if(t===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else r={}}else if(t===196){let o=this.lookU8();r=this.decodeBinary(o,1)}else if(t===197){let o=this.lookU16();r=this.decodeBinary(o,2)}else if(t===198){let o=this.lookU32();r=this.decodeBinary(o,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){let o=this.lookU8();r=this.decodeExtension(o,1)}else if(t===200){let o=this.lookU16();r=this.decodeExtension(o,2)}else if(t===201){let o=this.lookU32();r=this.decodeExtension(o,4)}else throw new yi(`Unrecognized type byte: ${oC(t)}`);this.complete();let n=this.stack;for(;n.length>0;){let o=n.top();if(o.type===oO)if(o.array[o.position]=r,o.position++,o.position===o.size)r=o.array,n.release(o);else continue e;else if(o.type===w8){if(r==="__proto__")throw new yi("The key __proto__ is not allowed");o.key=this.mapKeyConverter(r),o.type=WZ;continue e}else if(o.map[o.key]=r,o.readCount++,o.readCount===o.size)r=o.map,n.release(o);else{o.key=null,o.type=w8;continue e}}return r}}readHeadByte(){return this.headByte===y8&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=y8}readArraySize(){let t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new yi(`Unrecognized array type byte: ${oC(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new yi(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new yi(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){if(t>this.maxStrLength)throw new yi(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===w8:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new yi(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw qZ;let n=this.pos+r,o=this.bytes.subarray(n,n+t);return this.pos+=r+t,o}decodeExtension(t,r){if(t>this.maxExtLength)throw new yi(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+r),o=this.decodeBinary(t,r+1);return this.extensionCodec.decode(o,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){let t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){let t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){let t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){let t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){let t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){let t=VZ(this.view,this.pos);return this.pos+=8,t}readI64(){let t=rC(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){let t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){let t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){let t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){let t=this.view.getFloat64(this.pos);return this.pos+=8,t}};function aO(e,t){return new iC(t).decode(e)}JR();I8();l();l();XA();var DG=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),LTe=DG("expand 16-byte k"),MTe=DG("expand 32-byte k"),HTe=ef(LTe),$Te=ef(MTe);function je(e,t){return e<>>32-t}function kO(e){return e.byteOffset%4===0}var hC=64,FTe=16,LG=2**32-1,UG=new Uint32Array;function zTe(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(hC),d=ef(u),f=kO(o)&&kO(s),p=f?ef(o):UG,h=f?ef(s):UG;for(let y=0;y=LG)throw new Error("arx: counter overflow");let w=Math.min(hC,c-y);if(f&&w===hC){let x=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let v=0,T;v{rs(a),rs(c),rs(u);let p=u.length;if(d===void 0&&(d=new Uint8Array(p)),rs(d),YA(f),f<0||f>=LG)throw new Error("arx: counter overflow");if(d.lengthe[t++]&255|(e[t++]&255)<<8,DO=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=JA(t),rs(t,32);let r=Lo(t,0),n=Lo(t,2),o=Lo(t,4),s=Lo(t,6),i=Lo(t,8),a=Lo(t,10),c=Lo(t,12),u=Lo(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Lo(t,16+2*d)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],d=i[3],f=i[4],p=i[5],h=i[6],y=i[7],w=i[8],x=i[9],v=Lo(t,r+0),T=Lo(t,r+2),E=Lo(t,r+4),S=Lo(t,r+6),_=Lo(t,r+8),O=Lo(t,r+10),D=Lo(t,r+12),M=Lo(t,r+14),N=s[0]+(v&8191),L=s[1]+((v>>>13|T<<3)&8191),P=s[2]+((T>>>10|E<<6)&8191),R=s[3]+((E>>>7|S<<9)&8191),I=s[4]+((S>>>4|_<<12)&8191),B=s[5]+(_>>>1&8191),C=s[6]+((_>>>14|O<<2)&8191),A=s[7]+((O>>>11|D<<5)&8191),U=s[8]+((D>>>8|M<<8)&8191),H=s[9]+(M>>>5|o),k=0,F=k+N*a+L*(5*x)+P*(5*w)+R*(5*y)+I*(5*h);k=F>>>13,F&=8191,F+=B*(5*p)+C*(5*f)+A*(5*d)+U*(5*u)+H*(5*c),k+=F>>>13,F&=8191;let j=k+N*c+L*a+P*(5*x)+R*(5*w)+I*(5*y);k=j>>>13,j&=8191,j+=B*(5*h)+C*(5*p)+A*(5*f)+U*(5*d)+H*(5*u),k+=j>>>13,j&=8191;let W=k+N*u+L*c+P*a+R*(5*x)+I*(5*w);k=W>>>13,W&=8191,W+=B*(5*y)+C*(5*h)+A*(5*p)+U*(5*f)+H*(5*d),k+=W>>>13,W&=8191;let ae=k+N*d+L*u+P*c+R*a+I*(5*x);k=ae>>>13,ae&=8191,ae+=B*(5*w)+C*(5*y)+A*(5*h)+U*(5*p)+H*(5*f),k+=ae>>>13,ae&=8191;let te=k+N*f+L*d+P*u+R*c+I*a;k=te>>>13,te&=8191,te+=B*(5*x)+C*(5*w)+A*(5*y)+U*(5*h)+H*(5*p),k+=te>>>13,te&=8191;let X=k+N*p+L*f+P*d+R*u+I*c;k=X>>>13,X&=8191,X+=B*a+C*(5*x)+A*(5*w)+U*(5*y)+H*(5*h),k+=X>>>13,X&=8191;let pe=k+N*h+L*p+P*f+R*d+I*u;k=pe>>>13,pe&=8191,pe+=B*c+C*a+A*(5*x)+U*(5*w)+H*(5*y),k+=pe>>>13,pe&=8191;let me=k+N*y+L*h+P*p+R*f+I*d;k=me>>>13,me&=8191,me+=B*u+C*c+A*a+U*(5*x)+H*(5*w),k+=me>>>13,me&=8191;let Ne=k+N*w+L*y+P*h+R*p+I*f;k=Ne>>>13,Ne&=8191,Ne+=B*d+C*u+A*c+U*a+H*(5*x),k+=Ne>>>13,Ne&=8191;let ye=k+N*x+L*w+P*y+R*h+I*p;k=ye>>>13,ye&=8191,ye+=B*f+C*d+A*u+U*c+H*a,k+=ye>>>13,ye&=8191,k=(k<<2)+k|0,k=k+F|0,F=k&8191,k=k>>>13,j+=k,s[0]=F,s[1]=j,s[2]=W,s[3]=ae,s[4]=te,s[5]=X,s[6]=pe,s[7]=me,s[8]=Ne,s[9]=ye}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;tf(n)}update(t){QR(this),t=JA(t),rs(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let s=0;s>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function VTe(e){let t=(n,o)=>e(o).update(JA(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var MG=VTe(e=>new DO(e));XA();function FG(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],d=t[0],f=t[1],p=t[2],h=t[3],y=t[4],w=t[5],x=t[6],v=t[7],T=o,E=r[0],S=r[1],_=r[2],O=i,D=a,M=c,N=u,L=d,P=f,R=p,I=h,B=y,C=w,A=x,U=v,H=T,k=E,F=S,j=_;for(let ae=0;ae{e.update(t);let r=t.length%16;r&&e.update(KTe.subarray(r))},ZTe=new Uint8Array(32);function $G(e,t,r,n,o){let s=e(t,r,ZTe),i=MG.create(s);o&&HG(i,o),HG(i,n);let a=BZ(n.length,o?o.length:0,!0);i.update(a);let c=i.digest();return tf(s,a),c}var zG=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=eO(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let u=$G(e,t,r,c,n);return i.set(u,a),tf(u),i},decrypt(s,i){i=eO(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=$G(e,t,r,a,n);if(!OZ(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),tf(u),i}}),LO=XR({blockSize:64,nonceLength:12,tagLength:16},zG(qTe)),hdt=XR({blockSize:64,nonceLength:24,tagLength:16},zG(WTe));l();function GTe(e,t,r){return p1(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Xp(e,Qo(r),Qo(t))}var MO=Uint8Array.from([0]),VG=Uint8Array.of();function YTe(e,t,r,n=32){p1(e),Jo(n);let o=e.outputLen;if(n>255*o)throw new Error("Length should be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0&&(r=VG);let i=new Uint8Array(s*o),a=Xp.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;dYTe(e,GTe(e,t,r),n,o);l();l();l();var FO=BigInt(0),$O=BigInt(1);function nf(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function aa(e,t,r=""){let n=Wd(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function T8(e){let t=e.toString(16);return t.length&1?"0"+t:t}function qG(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?FO:BigInt("0x"+e)}function $2(e){return qG(za(e))}function ja(e){return Cn(e),qG(za(Uint8Array.from(e).reverse()))}function mC(e,t){return m1(e.toString(16).padStart(t*2,"0"))}function _8(e,t){return mC(e,t).reverse()}function or(e,t,r){let n;if(typeof t=="string")try{n=m1(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(Wd(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function WG(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;ntypeof e=="bigint"&&FO<=e;function KG(e,t,r){return HO(e)&&HO(t)&&HO(r)&&t<=e&&eFO;e>>=$O,t+=1);return t}var sh=e=>($O<new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(e),i=n(e),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...h)=>r(i,s,...h),d=(h=n(0))=>{i=u(o(0),h),s=u(),h.length!==0&&(i=u(o(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,y=[];for(;h{c(),d(h);let w;for(;!(w=y(f()));)d();return c(),w}}function Ll(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,s,i){let a=e[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var VO=()=>{throw new Error("not implemented")};function F2(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}l();var Hs=BigInt(0),ho=BigInt(1),_1=BigInt(2),JG=BigInt(3),QG=BigInt(4),XG=BigInt(5),JTe=BigInt(7),eY=BigInt(8),QTe=BigInt(9),tY=BigInt(16);function Yr(e,t){let r=e%t;return r>=Hs?r:t+r}function qa(e,t,r){let n=e;for(;t-- >Hs;)n*=n,n%=r;return n}function GG(e,t){if(e===Hs)throw new Error("invert: expected non-zero number");if(t<=Hs)throw new Error("invert: expected positive modulus, got "+t);let r=Yr(e,t),n=t,o=Hs,s=ho,i=ho,a=Hs;for(;r!==Hs;){let u=n/r,d=n%r,f=o-i*u,p=s-a*u;n=r,r=d,o=i,s=a,i=f,a=p}if(n!==ho)throw new Error("invert: does not exist");return Yr(o,t)}function jO(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function rY(e,t){let r=(e.ORDER+ho)/QG,n=e.pow(t,r);return jO(e,n,t),n}function XTe(e,t){let r=(e.ORDER-XG)/eY,n=e.mul(t,_1),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,_1),o),a=e.mul(s,e.sub(i,e.ONE));return jO(e,a,t),a}function e_e(e){let t=$s(e),r=nY(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+JTe)/tY;return(a,c)=>{let u=a.pow(c,i),d=a.mul(u,n),f=a.mul(u,o),p=a.mul(u,s),h=a.eql(a.sqr(d),c),y=a.eql(a.sqr(f),c);u=a.cmov(u,d,h),d=a.cmov(p,f,y);let w=a.eql(a.sqr(d),c),x=a.cmov(u,d,w);return jO(a,x,c),x}}function nY(e){if(e1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return rY;let s=o.pow(n,t),i=(t+ho)/_1;return function(c,u){if(c.is0(u))return u;if(YG(c,u)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,s),p=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(p,c.ONE);){if(c.is0(p))return c.ZERO;let y=1,w=c.sqr(p);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===d)throw new Error("Cannot find square root");let x=ho<(Yr(e,t)&ho)===ho,r_e=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qO(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=r_e.reduce((n,o)=>(n[o]="function",n),t);return Ll(e,r),e}function n_e(e,t,r){if(rHs;)r&ho&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ho;return n}function P8(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function YG(e,t){let r=(e.ORDER-ho)/_1,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function yC(e,t){t!==void 0&&Jo(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function $s(e,t,r=!1,n={}){if(e<=Hs)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let p=t;p.BITS&&(o=p.BITS),p.sqrt&&(s=p.sqrt),typeof p.isLE=="boolean"&&(r=p.isLE),typeof p.modFromBytes=="boolean"&&(i=p.modFromBytes),a=p.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:u}=yC(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:sh(c),ZERO:Hs,ONE:ho,allowedLengths:a,create:p=>Yr(p,e),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return Hs<=p&&pp===Hs,isValidNot0:p=>!f.is0(p)&&f.isValid(p),isOdd:p=>(p&ho)===ho,neg:p=>Yr(-p,e),eql:(p,h)=>p===h,sqr:p=>Yr(p*p,e),add:(p,h)=>Yr(p+h,e),sub:(p,h)=>Yr(p-h,e),mul:(p,h)=>Yr(p*h,e),pow:(p,h)=>n_e(f,p,h),div:(p,h)=>Yr(p*GG(h,e),e),sqrN:p=>p*p,addN:(p,h)=>p+h,subN:(p,h)=>p-h,mulN:(p,h)=>p*h,inv:p=>GG(p,e),sqrt:s||(p=>(d||(d=t_e(e)),d(f,p))),toBytes:p=>r?_8(p,u):mC(p,u),fromBytes:(p,h=!0)=>{if(a){if(!a.includes(p.length)||p.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+p.length);let w=new Uint8Array(u);w.set(p,r?0:w.length-p.length),p=w}if(p.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+p.length);let y=r?ja(p):$2(p);if(i&&(y=Yr(y,e)),!h&&!f.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:p=>P8(f,p),cmov:(p,h,y)=>y?h:p});return Object.freeze(f)}function oY(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function WO(e){let t=oY(e);return t+Math.ceil(t/2)}function sY(e,t,r=!1){let n=e.length,o=oY(t),s=WO(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?ja(e):$2(e),a=Yr(i,t-ho)+ho;return r?_8(a,o):mC(a,o)}var z2=BigInt(0),P1=BigInt(1);function N8(e,t){let r=t.negate();return e?r:t}function sf(e,t){let r=P8(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function lY(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function KO(e,t){lY(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=sh(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function iY(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=P1);let u=t*n,d=u+Math.abs(a)-1,f=a===0,p=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:p,isNegF:h,offsetF:u}}function o_e(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function s_e(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var ZO=new WeakMap,uY=new WeakMap;function GO(e){return uY.get(e)||1}function aY(e){if(e!==z2)throw new Error("invalid wNAF")}var V2=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>z2;)r&P1&&(n=n.add(o)),o=o.double(),r>>=P1;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=KO(r,this.bits),s=[],i=t,a=i;for(let c=0;cz2||n>z2;)r&P1&&(s=s.add(o)),n&P1&&(i=i.add(o)),o=o.double(),r>>=P1,n>>=P1;return{p1:s,p2:i}}function j2(e,t,r,n){o_e(r,e),s_e(n,t);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=gC(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=sh(c),d=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,p=i;for(let h=f;h>=0;h-=c){d.fill(i);for(let w=0;w>BigInt(h)&u);d[v]=d[v].add(r[w])}let y=i;for(let w=d.length-1,x=i;w>0;w--)x=x.add(d[w]),y=y.add(x);if(p=p.add(y),h!==0)for(let w=0;wz2))throw new Error(`CURVE.${c} must be positive bigint`)}let o=cY(t.p,r.Fp,n),s=cY(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}l();var ih=BigInt(0),mo=BigInt(1),YO=BigInt(2),i_e=BigInt(8);function a_e(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function c_e(e,t={}){let r=wC("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Ll(t,{},{uvRatio:"function"});let a=YO<n.create(x),u=t.uvRatio||((x,v)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,v))}}catch{return{isValid:!1,value:ih}}});if(!a_e(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(x,v,T=!1){let E=T?mo:ih;return oh("coordinate "+x,v,E,a),v}function f(x){if(!(x instanceof y))throw new Error("ExtendedPoint expected")}let p=F2((x,v)=>{let{X:T,Y:E,Z:S}=x,_=x.is0();v==null&&(v=_?i_e:n.inv(S));let O=c(T*v),D=c(E*v),M=n.mul(S,v);if(_)return{x:ih,y:mo};if(M!==mo)throw new Error("invZ was invalid");return{x:O,y:D}}),h=F2(x=>{let{a:v,d:T}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:E,Y:S,Z:_,T:O}=x,D=c(E*E),M=c(S*S),N=c(_*_),L=c(N*N),P=c(D*v),R=c(N*c(P+M)),I=c(L+c(T*c(D*M)));if(R!==I)throw new Error("bad point: equation left != right (1)");let B=c(E*S),C=c(_*O);if(B!==C)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(v,T,E,S){this.X=d("x",v),this.Y=d("y",T),this.Z=d("z",E,!0),this.T=d("t",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){if(v instanceof y)throw new Error("extended point not allowed");let{x:T,y:E}=v||{};return d("x",T),d("y",E),new y(T,E,mo,c(T*E))}static fromBytes(v,T=!1){let E=n.BYTES,{a:S,d:_}=s;v=zO(aa(v,E,"point")),nf(T,"zip215");let O=zO(v),D=v[E-1];O[E-1]=D&-129;let M=ja(O),N=T?a:n.ORDER;oh("point.y",M,ih,N);let L=c(M*M),P=c(L-mo),R=c(_*L-S),{isValid:I,value:B}=u(P,R);if(!I)throw new Error("bad point: invalid y coordinate");let C=(B&mo)===mo,A=(D&128)!==0;if(!T&&B===ih&&A)throw new Error("bad point: x=0 and x_0=1");return A!==C&&(B=c(-B)),y.fromAffine({x:B,y:M})}static fromHex(v,T=!1){return y.fromBytes(or("point",v),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,T=!0){return w.createCache(this,v),T||this.multiply(YO),this}assertValidity(){h(this)}equals(v){f(v);let{X:T,Y:E,Z:S}=this,{X:_,Y:O,Z:D}=v,M=c(T*D),N=c(_*S),L=c(E*D),P=c(O*S);return M===N&&L===P}is0(){return this.equals(y.ZERO)}negate(){return new y(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:v}=s,{X:T,Y:E,Z:S}=this,_=c(T*T),O=c(E*E),D=c(YO*c(S*S)),M=c(v*_),N=T+E,L=c(c(N*N)-_-O),P=M+O,R=P-D,I=M-O,B=c(L*R),C=c(P*I),A=c(L*I),U=c(R*P);return new y(B,C,U,A)}add(v){f(v);let{a:T,d:E}=s,{X:S,Y:_,Z:O,T:D}=this,{X:M,Y:N,Z:L,T:P}=v,R=c(S*M),I=c(_*N),B=c(D*E*P),C=c(O*L),A=c((S+_)*(M+N)-R-I),U=C-B,H=C+B,k=c(I-T*R),F=c(A*U),j=c(H*k),W=c(A*k),ae=c(U*H);return new y(F,j,ae,W)}subtract(v){return this.add(v.negate())}multiply(v){if(!o.isValidNot0(v))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:T,f:E}=w.cached(this,v,S=>sf(y,S));return sf(y,[T,E])[0]}multiplyUnsafe(v,T=y.ZERO){if(!o.isValid(v))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return v===ih?y.ZERO:this.is0()||v===mo?this:w.unsafe(this,v,E=>sf(y,E),T)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return w.unsafe(this,s.n).is0()}toAffine(v){return p(this,v)}clearCofactor(){return i===mo?this:this.multiplyUnsafe(i)}toBytes(){let{x:v,y:T}=this.toAffine(),E=n.toBytes(T);return E[E.length-1]|=v&mo?128:0,E}toHex(){return za(this.toBytes())}toString(){return``}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(v){return sf(y,v)}static msm(v,T){return j2(y,o,v,T)}_setWindowSize(v){this.precompute(v)}toRawBytes(){return this.toBytes()}}y.BASE=new y(s.Gx,s.Gy,mo,c(s.Gx*s.Gy)),y.ZERO=new y(ih,mo,mo,ih),y.Fp=n,y.Fn=o;let w=new V2(y,o.BITS);return y.BASE.precompute(8),y}var bC=class{constructor(t){this.ep=t}static fromBytes(t){VO()}static fromHex(t){VO()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return za(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function l_e(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ll(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||Us,c=r.adjustScalarBytes||(N=>N),u=r.domain||((N,L,P)=>{if(nf(P,"phflag"),L.length||P)throw new Error("Contexts/pre-hash are not supported");return N});function d(N){return i.create(ja(N))}function f(N){let L=E.secretKey;N=or("private key",N,L);let P=or("hashed private key",t(N),2*L),R=c(P.slice(0,L)),I=P.slice(L,2*L),B=d(R);return{head:R,prefix:I,scalar:B}}function p(N){let{head:L,prefix:P,scalar:R}=f(N),I=o.multiply(R),B=I.toBytes();return{head:L,prefix:P,scalar:R,point:I,pointBytes:B}}function h(N){return p(N).pointBytes}function y(N=Uint8Array.of(),...L){let P=ko(...L);return d(t(u(P,or("context",N),!!n)))}function w(N,L,P={}){N=or("message",N),n&&(N=n(N));let{prefix:R,scalar:I,pointBytes:B}=p(L),C=y(P.context,R,N),A=o.multiply(C).toBytes(),U=y(P.context,A,B,N),H=i.create(C+U*I);if(!i.isValid(H))throw new Error("sign failed: invalid s");let k=ko(A,i.toBytes(H));return aa(k,E.signature,"result")}let x={zip215:!0};function v(N,L,P,R=x){let{context:I,zip215:B}=R,C=E.signature;N=or("signature",N,C),L=or("message",L),P=or("publicKey",P,E.publicKey),B!==void 0&&nf(B,"zip215"),n&&(L=n(L));let A=C/2,U=N.subarray(0,A),H=ja(N.subarray(A,C)),k,F,j;try{k=e.fromBytes(P,B),F=e.fromBytes(U,B),j=o.multiplyUnsafe(H)}catch{return!1}if(!B&&k.isSmallOrder())return!1;let W=y(I,F.toBytes(),k.toBytes(),L);return F.add(k.multiplyUnsafe(W)).subtract(j).clearCofactor().is0()}let T=s.BYTES,E={secretKey:T,publicKey:T,signature:2*T,seed:T};function S(N=a(E.seed)){return aa(N,E.seed,"seed")}function _(N){let L=M.randomSecretKey(N);return{secretKey:L,publicKey:h(L)}}function O(N){return Wd(N)&&N.length===i.BYTES}function D(N,L){try{return!!e.fromBytes(N,L)}catch{return!1}}let M={getExtendedPublicKey:p,randomSecretKey:S,isValidSecretKey:O,isValidPublicKey:D,toMontgomery(N){let{y:L}=e.fromBytes(N),P=E.publicKey,R=P===32;if(!R&&P!==57)throw new Error("only defined for 25519 and 448");let I=R?s.div(mo+L,mo-L):s.div(L-mo,L+mo);return s.toBytes(I)},toMontgomerySecret(N){let L=E.secretKey;aa(N,L);let P=t(N.subarray(0,L));return c(P).subarray(0,L)},randomPrivateKey:S,precompute(N=8,L=e.BASE){return L.precompute(N,!1)}};return Object.freeze({keygen:_,getPublicKey:h,sign:w,verify:v,utils:M,Point:e,lengths:E})}function u_e(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=$s(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:s}}function d_e(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function fY(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=u_e(e),s=c_e(t,r),i=l_e(s,n,o);return d_e(e,i)}l();var R8=BigInt(0),q2=BigInt(1),xC=BigInt(2);function f_e(e){return Ll(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function pY(e){let t=f_e(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Us,u=a?255:448,d=a?32:56,f=BigInt(a?9:5),p=BigInt(a?121665:39081),h=a?xC**BigInt(254):xC**BigInt(447),y=a?BigInt(8)*xC**BigInt(251)-q2:BigInt(4)*xC**BigInt(445)-q2,w=h+y+q2,x=I=>Yr(I,r),v=T(f);function T(I){return _8(x(I),d)}function E(I){let B=or("u coordinate",I,d);return a&&(B[31]&=127),x(ja(B))}function S(I){return ja(o(or("scalar",I,d)))}function _(I,B){let C=M(E(B),S(I));if(C===R8)throw new Error("invalid private or public key received");return T(C)}function O(I){return _(I,v)}function D(I,B,C){let A=x(I*(B-C));return B=x(B-A),C=x(C+A),{x_2:B,x_3:C}}function M(I,B){oh("u",I,R8,r),oh("scalar",B,h,w);let C=B,A=I,U=q2,H=R8,k=I,F=q2,j=R8;for(let ae=BigInt(u-1);ae>=R8;ae--){let te=C>>ae&q2;j^=te,{x_2:U,x_3:k}=D(j,U,k),{x_2:H,x_3:F}=D(j,H,F),j=te;let X=U+H,pe=x(X*X),me=U-H,Ne=x(me*me),ye=pe-Ne,Re=k+F,Et=k-F,kt=x(Et*X),At=x(Re*me),ur=kt+At,_r=kt-At;k=x(ur*ur),F=x(A*x(_r*_r)),U=x(pe*Ne),H=x(ye*(pe+x(p*ye)))}({x_2:U,x_3:k}=D(j,U,k)),{x_2:H,x_3:F}=D(j,H,F);let W=s(H);return x(U*W)}let N={secretKey:d,publicKey:d,seed:d},L=(I=c(d))=>(Cn(I,N.seed),I);function P(I){let B=L(I);return{secretKey:B,publicKey:O(B)}}return{keygen:P,getSharedSecret:(I,B)=>_(I,B),getPublicKey:I=>O(I),scalarMult:_,scalarMultBase:O,utils:{randomSecretKey:L,randomPrivateKey:L},GuBytes:v.slice(),lengths:N}}var p_e=BigInt(0),cf=BigInt(1),hY=BigInt(2),h_e=BigInt(3),m_e=BigInt(5),g_e=BigInt(8),W2=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),O8={p:W2,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:g_e,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yY(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=W2,a=e*e%s*e%s,c=qa(a,hY,s)*a%s,u=qa(c,cf,s)*e%s,d=qa(u,m_e,s)*u%s,f=qa(d,t,s)*d%s,p=qa(f,r,s)*f%s,h=qa(p,n,s)*p%s,y=qa(h,o,s)*h%s,w=qa(y,o,s)*h%s,x=qa(w,t,s)*d%s;return{pow_p_5_8:qa(x,hY,s)*e%s,b2:a}}function wY(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var JO=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function eB(e,t){let r=W2,n=Yr(t*t*t,r),o=Yr(n*n*t,r),s=yY(e*o).pow_p_5_8,i=Yr(e*n*s,r),a=Yr(t*i*i,r),c=i,u=Yr(i*JO,r),d=a===e,f=a===Yr(-e,r),p=a===Yr(-e*JO,r);return d&&(i=c),(f||p)&&(i=u),of(i,r)&&(i=Yr(-i,r)),{isValid:d||f,value:i}}var af=$s(O8.p,{isLE:!0}),y_e=$s(O8.n,{isLE:!0}),w_e={...O8,Fp:af,hash:bA,adjustScalarBytes:wY,uvRatio:eB},N1=fY(w_e);var vC=(()=>{let e=af.ORDER;return pY({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=yY(t);return Yr(qa(r,h_e,e)*n,e)},adjustScalarBytes:wY})})();var QO=JO,b_e=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x_e=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),v_e=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),E_e=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),mY=e=>eB(cf,e),A_e=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),XO=e=>N1.Point.Fp.create(ja(e)&A_e);function gY(e){let{d:t}=O8,r=W2,n=v=>af.create(v),o=n(QO*e*e),s=n((o+cf)*v_e),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:u}=eB(s,a),d=n(u*e);of(d,r)||(d=n(-d)),c||(u=d),c||(i=o);let f=n(i*(o-cf)*E_e-a),p=u*u,h=n((u+u)*a),y=n(f*b_e),w=n(cf-p),x=n(cf+p);return new N1.Point(n(h*x),n(w*y),n(y*x),n(h*w))}function C_e(e){Cn(e,64);let t=XO(e.subarray(0,32)),r=gY(t),n=XO(e.subarray(32,64)),o=gY(n);return new lf(r.add(o))}var lf=class e extends bC{constructor(t){super(t)}static fromAffine(t){return new e(N1.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return C_e(or("ristrettoHash",t,64))}static fromBytes(t){Cn(t,32);let{a:r,d:n}=O8,o=W2,s=S=>af.create(S),i=XO(t);if(!WG(af.toBytes(i),t)||of(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(cf+r*a),u=s(cf-r*a),d=s(c*c),f=s(u*u),p=s(r*n*d-f),{isValid:h,value:y}=mY(s(p*f)),w=s(y*u),x=s(y*w*p),v=s((i+i)*w);of(v,o)&&(v=s(-v));let T=s(c*x),E=s(v*T);if(!h||of(E,o)||T===p_e)throw new Error("invalid ristretto255 encoding 2");return new e(new N1.Point(v,T,cf,E))}static fromHex(t){return e.fromBytes(or("ristrettoHex",t,32))}static msm(t,r){return j2(e,N1.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,s=W2,i=x=>af.create(x),a=i(i(n+r)*i(n-r)),c=i(t*r),u=i(c*c),{value:d}=mY(i(a*u)),f=i(d*a),p=i(d*c),h=i(f*p*o),y;if(of(o*h,s)){let x=i(r*QO),v=i(t*QO);t=x,r=v,y=i(f*x_e)}else y=p;of(t*h,s)&&(r=i(-r));let w=i((n-r)*y);return of(w,s)&&(w=i(-w)),af.toBytes(w)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=u=>af.create(u),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(e.ZERO)}};lf.BASE=new lf(N1.Point.BASE);lf.ZERO=new lf(N1.Point.ZERO);lf.Fp=af;lf.Fn=y_e;l();l();l();l();var bY=(e,t)=>(e+(e>=0?t:-t)/xY)/t;function S_e(e,t,r){let[[n,o],[s,i]]=t,a=bY(i*e,r),c=bY(-o*e,r),u=e-a*n-c*s,d=-a*o-c*i,f=u=h||d=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:u,k2neg:p,k2:d}}function rB(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function tB(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return nf(r.lowS,"lowS"),nf(r.prehash,"prehash"),r.format!==void 0&&rB(r.format),r}var nB=class extends Error{constructor(t=""){super(t)}},uf={Err:nB,_tlv:{encode:(e,t)=>{let{Err:r}=uf;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=T8(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?T8(o.length/2|128):"";return T8(e)+s+o+t},decode(e,t){let{Err:r}=uf,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=uf;if(e{let{X:B,Y:C,Z:A}=R;if(n.eql(A,n.ONE))return{x:B,y:C};let U=R.is0();I==null&&(I=U?n.ONE:n.inv(A));let H=n.mul(B,I),k=n.mul(C,I),F=n.mul(A,I);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:k}}),D=F2(R=>{if(R.is0()){if(t.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:B}=R.toAffine();if(!n.isValid(I)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!x(I,B))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(R,I,B,C,A){return B=new N(n.mul(B.X,R),B.Y,B.Z),I=N8(C,I),B=N8(A,B),I.add(B)}class N{constructor(I,B,C){this.X=E("x",I),this.Y=E("y",B,!0),this.Z=E("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){let{x:B,y:C}=I||{};if(!I||!n.isValid(B)||!n.isValid(C))throw new Error("invalid affine point");if(I instanceof N)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(C)?N.ZERO:new N(B,C,n.ONE)}static fromBytes(I){let B=N.fromAffine(y(aa(I,void 0,"point")));return B.assertValidity(),B}static fromHex(I){return N.fromBytes(or("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,B=!0){return P.createCache(this,I),B||this.multiply(EC),this}assertValidity(){D(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.eql(n.mul(B,k),n.mul(U,A)),j=n.eql(n.mul(C,k),n.mul(H,A));return F&&j}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:B}=s,C=n.mul(B,EC),{X:A,Y:U,Z:H}=this,k=n.ZERO,F=n.ZERO,j=n.ZERO,W=n.mul(A,A),ae=n.mul(U,U),te=n.mul(H,H),X=n.mul(A,U);return X=n.add(X,X),j=n.mul(A,H),j=n.add(j,j),k=n.mul(I,j),F=n.mul(C,te),F=n.add(k,F),k=n.sub(ae,F),F=n.add(ae,F),F=n.mul(k,F),k=n.mul(X,k),j=n.mul(C,j),te=n.mul(I,te),X=n.sub(W,te),X=n.mul(I,X),X=n.add(X,j),j=n.add(W,W),W=n.add(j,W),W=n.add(W,te),W=n.mul(W,X),F=n.add(F,W),te=n.mul(U,H),te=n.add(te,te),W=n.mul(te,X),k=n.sub(k,W),j=n.mul(te,ae),j=n.add(j,j),j=n.add(j,j),new N(k,F,j)}add(I){S(I);let{X:B,Y:C,Z:A}=this,{X:U,Y:H,Z:k}=I,F=n.ZERO,j=n.ZERO,W=n.ZERO,ae=s.a,te=n.mul(s.b,EC),X=n.mul(B,U),pe=n.mul(C,H),me=n.mul(A,k),Ne=n.add(B,C),ye=n.add(U,H);Ne=n.mul(Ne,ye),ye=n.add(X,pe),Ne=n.sub(Ne,ye),ye=n.add(B,A);let Re=n.add(U,k);return ye=n.mul(ye,Re),Re=n.add(X,me),ye=n.sub(ye,Re),Re=n.add(C,A),F=n.add(H,k),Re=n.mul(Re,F),F=n.add(pe,me),Re=n.sub(Re,F),W=n.mul(ae,ye),F=n.mul(te,me),W=n.add(F,W),F=n.sub(pe,W),W=n.add(pe,W),j=n.mul(F,W),pe=n.add(X,X),pe=n.add(pe,X),me=n.mul(ae,me),ye=n.mul(te,ye),pe=n.add(pe,me),me=n.sub(X,me),me=n.mul(ae,me),ye=n.add(ye,me),X=n.mul(pe,ye),j=n.add(j,X),X=n.mul(Re,ye),F=n.mul(Ne,F),F=n.sub(F,X),X=n.mul(Ne,pe),W=n.mul(Re,W),W=n.add(W,X),new N(F,j,W)}subtract(I){return this.add(I.negate())}is0(){return this.equals(N.ZERO)}multiply(I){let{endo:B}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let C,A,U=H=>P.cached(this,H,k=>sf(N,k));if(B){let{k1neg:H,k1:k,k2neg:F,k2:j}=_(I),{p:W,f:ae}=U(k),{p:te,f:X}=U(j);A=ae.add(X),C=M(B.beta,W,te,H,F)}else{let{p:H,f:k}=U(I);C=H,A=k}return sf(N,[C,A])[0]}multiplyUnsafe(I){let{endo:B}=t,C=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===df||C.is0())return N.ZERO;if(I===Z2)return C;if(P.hasCache(this))return this.multiply(I);if(B){let{k1neg:A,k1:U,k2neg:H,k2:k}=_(I),{p1:F,p2:j}=dY(N,C,U,k);return M(B.beta,F,j,A,H)}else return P.unsafe(C,I)}multiplyAndAddUnsafe(I,B,C){let A=this.multiplyUnsafe(B).add(I.multiplyUnsafe(C));return A.is0()?void 0:A}toAffine(I){return O(this,I)}isTorsionFree(){let{isTorsionFree:I}=t;return i===Z2?!0:I?I(N,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=t;return i===Z2?this:I?I(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return nf(I,"isCompressed"),this.assertValidity(),h(N,this,I)}toHex(I=!0){return za(this.toBytes(I))}toString(){return``}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return sf(N,I)}static msm(I,B){return j2(N,o,I,B)}static fromPrivateKey(I){return N.BASE.multiply(K2(o,I))}}N.BASE=new N(s.Gx,s.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=o;let L=o.BITS,P=new V2(N,t.endo?Math.ceil(L/2):L);return N.BASE.precompute(8),N}function vY(e){return Uint8Array.of(e?2:3)}function EY(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function __e(e,t={}){let{Fn:r}=e,n=t.randomBytes||Us,o=Object.assign(EY(e.Fp,r),{seed:WO(r.ORDER)});function s(h){try{return!!K2(r,h)}catch{return!1}}function i(h,y){let{publicKey:w,publicKeyUncompressed:x}=o;try{let v=h.length;return y===!0&&v!==w||y===!1&&v!==x?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return sY(aa(h,o.seed,"seed"),r.ORDER)}function c(h,y=!0){return e.BASE.multiply(K2(r,h)).toBytes(y)}function u(h){let y=a(h);return{secretKey:y,publicKey:c(y)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;let{secretKey:y,publicKey:w,publicKeyUncompressed:x}=o;if(r.allowedLengths||y===w)return;let v=or("key",h).length;return v===w||v===x}function f(h,y,w=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let x=K2(r,h);return e.fromHex(y).multiply(x).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:e,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>K2(r,h),precompute(h=8,y=e.BASE){return y.precompute(h,!1)}},lengths:o})}function P_e(e,t,r={}){p1(t),Ll(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Us,o=r.hmac||((B,...C)=>Xp(t,B,ko(...C))),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h}=__e(e,r),y={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function x(B){let C=a>>Z2;return B>C}function v(B,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${B}: out of range 1..Point.Fn.ORDER`);return C}function T(B,C){rB(C);let A=h.signature,U=C==="compact"?A:C==="recovered"?A+1:void 0;return aa(B,U,`${C} signature`)}class E{constructor(C,A,U){this.r=v("r",C),this.s=v("s",A),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(C,A=w){T(C,A);let U;if(A==="der"){let{r:j,s:W}=uf.toSig(aa(C));return new E(j,W)}A==="recovered"&&(U=C[0],A="compact",C=C.subarray(1));let H=i.BYTES,k=C.subarray(0,H),F=C.subarray(H,H*2);return new E(i.fromBytes(k),i.fromBytes(F),U)}static fromHex(C,A){return this.fromBytes(m1(C),A)}addRecoveryBit(C){return new E(this.r,this.s,C)}recoverPublicKey(C){let A=s.ORDER,{r:U,s:H,recovery:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*xY1)throw new Error("recovery id is ambiguous for h>1 curve");let j=k===2||k===3?U+a:U;if(!s.isValid(j))throw new Error("recovery id 2 or 3 invalid");let W=s.toBytes(j),ae=e.fromBytes(ko(vY((k&1)===0),W)),te=i.inv(j),X=_(or("msgHash",C)),pe=i.create(-X*te),me=i.create(H*te),Ne=e.BASE.multiplyUnsafe(pe).add(ae.multiplyUnsafe(me));if(Ne.is0())throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return x(this.s)}toBytes(C=w){if(rB(C),C==="der")return m1(uf.hexFromSig(this));let A=i.toBytes(this.r),U=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ko(Uint8Array.of(this.recovery),A,U)}return ko(A,U)}toHex(C){return za(this.toBytes(C))}assertValidity(){}static fromCompact(C){return E.fromBytes(or("sig",C),"compact")}static fromDER(C){return E.fromBytes(or("sig",C),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return za(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return za(this.toBytes("compact"))}}let S=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let A=$2(C),U=C.length*8-c;return U>0?A>>BigInt(U):A},_=r.bits2int_modN||function(C){return i.create(S(C))},O=sh(c);function D(B){return oh("num < 2^"+c,B,df,O),i.toBytes(B)}function M(B,C){return aa(B,void 0,"message"),C?aa(t(B),void 0,"prehashed message"):B}function N(B,C,A){if(["recovered","canonical"].some(pe=>pe in A))throw new Error("sign() legacy options not supported");let{lowS:U,prehash:H,extraEntropy:k}=tB(A,y);B=M(B,H);let F=_(B),j=K2(i,C),W=[D(j),D(F)];if(k!=null&&k!==!1){let pe=k===!0?n(h.secretKey):k;W.push(or("extraEntropy",pe))}let ae=ko(...W),te=F;function X(pe){let me=S(pe);if(!i.isValidNot0(me))return;let Ne=i.inv(me),ye=e.BASE.multiply(me).toAffine(),Re=i.create(ye.x);if(Re===df)return;let Et=i.create(Ne*i.create(te+Re*j));if(Et===df)return;let kt=(ye.x===Re?0:2)|Number(ye.y&Z2),At=Et;return U&&x(Et)&&(At=i.neg(Et),kt^=1),new E(Re,At,kt)}return{seed:ae,k2sig:X}}function L(B,C,A={}){B=or("message",B);let{seed:U,k2sig:H}=N(B,C,A);return ZG(t.outputLen,i.BYTES,o)(U,H)}function P(B){let C,A=typeof B=="string"||Wd(B),U=!A&&B!==null&&typeof B=="object"&&typeof B.r=="bigint"&&typeof B.s=="bigint";if(!A&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)C=new E(B.r,B.s);else if(A){try{C=E.fromBytes(or("sig",B),"der")}catch(H){if(!(H instanceof uf.Err))throw H}if(!C)try{C=E.fromBytes(or("sig",B),"compact")}catch{return!1}}return C||!1}function R(B,C,A,U={}){let{lowS:H,prehash:k,format:F}=tB(U,y);if(A=or("publicKey",A),C=M(or("message",C),k),"strict"in U)throw new Error("options.strict was renamed to lowS");let j=F===void 0?P(B):E.fromBytes(or("sig",B),F);if(j===!1)return!1;try{let W=e.fromBytes(A);if(H&&j.hasHighS())return!1;let{r:ae,s:te}=j,X=_(C),pe=i.inv(te),me=i.create(X*pe),Ne=i.create(ae*pe),ye=e.BASE.multiplyUnsafe(me).add(W.multiplyUnsafe(Ne));return ye.is0()?!1:i.create(ye.x)===ae}catch{return!1}}function I(B,C,A={}){let{prehash:U}=tB(A,y);return C=M(C,U),E.fromBytes(B,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:p,lengths:h,Point:e,sign:L,verify:R,recoverPublicKey:I,Signature:E,hash:t})}function N_e(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$s(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function R_e(e){let{CURVE:t,curveOpts:r}=N_e(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function O_e(e,t){let r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,yC(r.Fn.ORDER,r.Fn.BITS))})}function AY(e){let{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:o}=R_e(e),s=T_e(t,r),i=P_e(s,n,o);return O_e(e,i)}function AC(e,t){let r=n=>AY({...e,hash:n});return{...r(t),create:r}}var CY={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},SY={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},IY={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},B_e=$s(CY.p),k_e=$s(SY.p),U_e=$s(IY.p);var TY=AC({...CY,Fp:B_e,lowS:!1},Zd);var fft=AC({...SY,Fp:k_e,lowS:!1},fK);var pft=AC({...IY,Fp:U_e,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},bA);var _Y=TY;B1();BB();var tQ=Ht(LB(),1);gh();var pRe=":";function Lc(e){let[t,r]=e.split(pRe);return{namespace:t,reference:r}}function GB(e,t=[]){let r=[];return Object.keys(e).forEach(n=>{if(t.length&&!t.includes(n))return;let o=e[n];r.push(...o.accounts)}),r}function rQ(e,t){return e.includes(":")?[e]:t.chains||[]}var hRe={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},mRe={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Se(e,t){let{message:r,code:n}=mRe[e];return{message:t?`${r} ${t}`:r,code:n}}function Sr(e,t){let{message:r,code:n}=hRe[e];return{message:t?`${r} ${t}`:r,code:n}}var gRe="ReactNative",xi={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"};var yRe="js";function z8(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function gf(){return!(0,Dc.getDocument)()&&!!(0,Dc.getNavigator)()&&navigator.product===gRe}function nQ(){return gf()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="android"}function oQ(){return gf()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="ios"}function L1(){return!z8()&&!!(0,Dc.getNavigator)()&&!!(0,Dc.getDocument)()}function V8(){return gf()?xi.reactNative:z8()?xi.node:L1()?xi.browser:xi.unknown}function YB(){try{return gf()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function wRe(e,t){let r=new URLSearchParams(e);return Object.entries(t).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!=null&&r.set(n,String(o))}),r.toString()}function sQ(e){let t=JB();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter(r=>r!=="")),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(r){return console.warn("Error populating app metadata",r),e||t}}function JB(){return(0,eQ.getWindowMetadata)()||{name:"",description:"",url:"",icons:[""]}}function bRe(){if(V8()===xi.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){let{OS:r,Version:n}=global.Platform;return[r,n].join("-")}let e=iA();if(e===null)return"unknown";let t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return e.type==="browser"?[t,e.name,e.version].join("-"):[t,e.version].join("-")}function xRe(){let e=V8();return e===xi.browser?[e,(0,Dc.getLocation)()?.host||"unknown"].join(":"):e}function QB(e,t,r){let n=bRe(),o=xRe();return[[e,t].join("-"),[yRe,r].join("-"),n,o].join("/")}function iQ({protocol:e,version:t,relayUrl:r,sdkVersion:n,auth:o,projectId:s,useOnCloseEvent:i,bundleId:a,packageName:c}){let u=r.split("?"),d=QB(e,t,n),f={auth:o,ua:d,projectId:s,useOnCloseEvent:i||void 0,packageName:c||void 0,bundleId:a||void 0},p=wRe(u[1]||"",f);return u[0]+"?"+p}function U1(e,t){return e.filter(r=>t.includes(r)).length===e.length}function ZC(e){return Object.fromEntries(e.entries())}function GC(e){return new Map(Object.entries(e))}function yf(e=mf.FIVE_MINUTES,t){let r=(0,mf.toMiliseconds)(e||mf.FIVE_MINUTES),n,o,s,i;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),i=Promise.resolve(a))},reject:a=>{s&&o&&(clearTimeout(s),o(a))},done:()=>new Promise((a,c)=>{if(i)return a(i);s=setTimeout(()=>{let u=Se("EXPIRED"),d=new Error(t||u.message);d.code=u.code,c(d)},r),n=a,o=c})}}function Wa(e,t,r){return new Promise(async(n,o)=>{let s=setTimeout(()=>o(new Error(r)),t);try{let i=await e;n(i)}catch(i){o(i)}clearTimeout(s)})}function aQ(e,t){if(typeof t=="string"&&t.startsWith(`${e}:`))return t;if(e.toLowerCase()==="topic"){if(typeof t!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}else if(e.toLowerCase()==="id"){if(typeof t!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function cQ(e){return aQ("topic",e)}function lQ(e){return aQ("id",e)}function YC(e){let[t,r]=e.split(":"),n={id:void 0,topic:void 0};if(t==="topic"&&typeof r=="string")n.topic=r;else if(t==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${r}`);return n}function ln(e,t){return(0,mf.fromMiliseconds)((t||Date.now())+(0,mf.toMiliseconds)(e))}function ca(e){return Date.now()>=(0,mf.toMiliseconds)(e)}function ir(e,t){return`${e}${t?`:${t}`:""}`}function Uc(e=[],t=[]){return[...new Set([...e,...t])]}async function uQ({id:e,topic:t,wcDeepLink:r}){try{if(!r)return;let n=(typeof r=="string"?JSON.parse(r):r)?.href;if(typeof n!="string")return;let o=vRe(n,e,t),s=V8();if(s===xi.browser){if(!(0,Dc.getDocument)()?.hasFocus()){console.warn("Document does not have focus, skipping deeplink.");return}ERe(o)}else s===xi.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(o)}catch(n){console.error(n)}}function vRe(e,t,r){let n=`requestId=${t}&sessionTopic=${r}`;e.endsWith("/")&&(e=e.slice(0,-1));let o=`${e}`;if(e.startsWith("https://t.me")){let s=e.includes("?")?"&startapp=":"?startapp=";o=`${o}${s}${SRe(n,!0)}`}else o=`${o}/wc?${n}`;return o}function ERe(e){let t="_self";CRe()?t="_top":(ARe()||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"),window.open(e,t,"noreferrer noopener")}async function dQ(e,t){let r="";try{if(L1()&&(r=localStorage.getItem(t),r))return r;r=await e.getItem(t)}catch(n){console.error(n)}return r}function XB(e,t){if(!e.includes(t))return null;let r=e.split(/([&,?,=])/),n=r.indexOf(t);return r[n+2]}function ek(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function j8(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function ARe(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function CRe(){try{return window.self!==window.top}catch{return!1}}function SRe(e,t=!1){let r=new TextEncoder().encode(e),n=new Array(r.length);for(let s=0;ssetTimeout(t,e))}var jC=class{constructor({limit:t}){this.limit=t,this.set=new Set}add(t){if(!this.set.has(t)){if(this.set.size>=this.limit){let r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(t)}}has(t){return this.set.has(t)}},IRe="https://rpc.walletconnect.org/v1";function ew(e){let t=e+"=".repeat((4-e.length%4)%4),r=atob(t),n=new Uint8Array(r.length);for(let o=0;o=0x80n;)t.push(Number(r&0x7fn|0x80n)),r>>=7n;return t.push(Number(r)),new Uint8Array(t)}function yQ(e){let t=ew(e.signed.bodyBytes),r=ew(e.signed.authInfoBytes),n=ew(e.signature.signature),o=[];o.push(new Uint8Array([10])),o.push(KB(t.length)),o.push(t),o.push(new Uint8Array([18])),o.push(KB(r.length)),o.push(r),o.push(new Uint8Array([26])),o.push(KB(n.length)),o.push(n);let s=Ms(o),i=Zd(s);return Ut(i,"base16").toUpperCase()}function wQ(e){let t=[];try{if(typeof e=="string")return t.push(e),t;if(typeof e!="object")return t;e?.id&&t.push(e.id);let r=e?.capabilities?.caip345?.transactionHashes;r&&t.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return t}var bQ="did:pkh:",ORe={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},BRe=e=>e?ORe[e]||e:"",JC=e=>e?.split(":"),kRe=e=>{let t=e&&JC(e);if(t)return e.includes(bQ)?t[3]:t[1]},URe=e=>{let t=e&&JC(e);if(t)return e.includes(bQ)?t[2]:t[0]},QC=e=>{let t=e&&JC(e);if(t)return t[2]+":"+t[3]},q8=e=>{let t=e&&JC(e);if(t)return t.pop()};async function nk(e){let{cacao:t,projectId:r}=e,{s:n,p:o}=t,s=ok(o,o.iss),i=q8(o.iss);return await TRe(i,s,n,QC(o.iss),r)}var ok=(e,t)=>{let r=URe(t);if(!r)throw new Error("Invalid issuer: "+t);let n=`${e.domain} wants you to sign in with your ${BRe(r)} account:`,o=q8(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=e.statement||void 0,i=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${kRe(t)}`,u=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,f=e.exp?`Expiration Time: ${e.exp}`:void 0,p=e.nbf?`Not Before: ${e.nbf}`:void 0,h=e.requestId?`Request ID: ${e.requestId}`:void 0,y=e.resources?`Resources:${e.resources.map(x=>` - ${x}`).join("")}`:void 0,w=W8(e.resources);if(w){let x=F8(w);s=zRe(s,x)}return[n,o,"",s,"",i,a,c,u,d,f,p,h,y].filter(x=>x!=null).join(` -`)};function DRe(e){let t=JSON.stringify(e),r=new TextEncoder().encode(t),n=new Array(r.length);for(let o=0;o{let n=e.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(o=>{let s=n[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!="object")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function MRe(e,t,r,n={}){return r?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:HRe(t,r,n)}}}function HRe(e,t,r={}){t=t?.sort((o,s)=>o.localeCompare(s));let n=t.map(o=>({[`${e}/${o}`]:[r]}));return Object.assign({},...n)}function xQ(e){return D1(e),`urn:recap:${DRe(e).replace(/=/g,"")}`}function F8(e){let t=LRe(e.replace("urn:recap:",""));return D1(t),t}function vQ(e,t,r){let n=MRe(e,t,r);return xQ(n)}function $Re(e){return e&&e.includes("urn:recap:")}function EQ(e,t){let r=F8(e),n=F8(t),o=FRe(r,n);return xQ(o)}function FRe(e,t){D1(e),D1(t);let r=Object.keys(e.att).concat(Object.keys(t.att)).sort((o,s)=>o.localeCompare(s)),n={att:{}};return r.forEach(o=>{Object.keys(e.att?.[o]||{}).concat(Object.keys(t.att?.[o]||{})).sort((s,i)=>s.localeCompare(i)).forEach(s=>{n.att[o]={...n.att[o],[s]:e.att[o]?.[s]||t.att[o]?.[s]}})}),n}function zRe(e="",t){D1(t);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(r))return e;let n=[],o=0;Object.keys(t.att).forEach(a=>{let c=Object.keys(t.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,p)=>f.action.localeCompare(p.action));let u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});let d=Object.keys(u).map(f=>(o++,`(${o}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});let s=n.join(" "),i=`${r}${s}`;return`${e?e+" ":""}${i}`}function sk(e){let t=F8(e);D1(t);let r=t.att?.eip155;return r?Object.keys(r).map(n=>n.split("/")[1]):[]}function ik(e){let t=F8(e);D1(t);let r=[];return Object.values(t.att).forEach(n=>{Object.values(n).forEach(o=>{o?.[0]?.chains&&r.push(o[0].chains)})}),[...new Set(r.flat())]}function W8(e){if(!e)return;let t=e?.[e.length-1];return $Re(t)?t:void 0}var AQ="base10",is="base16",to="base64pad",wf="base64url",K8="utf8",CQ=0,Mc=1,tw=2,VRe=0,YJ=1,$8=12,ak=32;function SQ(){let e=vC.utils.randomPrivateKey(),t=vC.getPublicKey(e);return{privateKey:Ut(e,is),publicKey:Ut(t,is)}}function XC(){let e=Us(ak);return Ut(e,is)}function IQ(e,t){let r=vC.getSharedSecret(Qt(e,is),Qt(t,is)),n=jG(o8,r,void 0,void 0,ak);return Ut(n,is)}function rw(e){let t=o8(Qt(e,is));return Ut(t,is)}function xi(e){let t=o8(Qt(e,K8));return Ut(t,is)}function TQ(e){return Qt(`${e}`,AQ)}function yh(e){return Number(Ut(e,AQ))}function _Q(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qC(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}function PQ(e){let t=TQ(typeof e.type<"u"?e.type:CQ);if(yh(t)===Mc&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof e.senderPublicKey<"u"?Qt(e.senderPublicKey,is):void 0,n=typeof e.iv<"u"?Qt(e.iv,is):Us($8),o=Qt(e.symKey,is),s=LO(o,n).encrypt(Qt(e.message,K8)),i=BQ({type:t,sealed:s,iv:n,senderPublicKey:r});return e.encoding===wf?_Q(i):i}function NQ(e){let t=Qt(e.symKey,is),{sealed:r,iv:n}=nw({encoded:e.encoded,encoding:e.encoding}),o=LO(t,n).decrypt(r);if(o===null)throw new Error("Failed to decrypt");return Ut(o,K8)}function RQ(e,t){let r=TQ(tw),n=Us($8),o=Qt(e,K8),s=BQ({type:r,sealed:o,iv:n});return t===wf?_Q(s):s}function OQ(e,t){let{sealed:r}=nw({encoded:e,encoding:t});return Ut(r,K8)}function BQ(e){if(yh(e.type)===tw)return Ut(Ms([e.type,e.sealed]),to);if(yh(e.type)===Mc){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ut(Ms([e.type,e.senderPublicKey,e.iv,e.sealed]),to)}return Ut(Ms([e.type,e.iv,e.sealed]),to)}function nw(e){let t=(e.encoding||to)===wf?qC(e.encoded):e.encoded,r=Qt(t,to),n=r.slice(VRe,YJ),o=YJ;if(yh(n)===Mc){let c=o+ak,u=c+$8,d=r.slice(o,c),f=r.slice(c,u),p=r.slice(u);return{type:n,sealed:p,iv:f,senderPublicKey:d}}if(yh(n)===tw){let c=r.slice(o),u=Us($8);return{type:n,sealed:c,iv:u}}let s=o+$8,i=r.slice(o,s),a=r.slice(s);return{type:n,sealed:a,iv:i}}function kQ(e,t){let r=nw({encoded:e,encoding:t?.encoding});return ck({type:yh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ut(r.senderPublicKey,is):void 0,receiverPublicKey:t?.receiverPublicKey})}function ck(e){let t=e?.type||CQ;if(t===Mc){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function lk(e){return e.type===Mc&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function uk(e){return e.type===tw}function jRe(e){let t=Qt(qC(e.x),to),r=Qt(qC(e.y),to);return Ms([new Uint8Array([4]),t,r])}function UQ(e,t){let[r,n,o]=e.split("."),s=Qt(qC(o),to);if(s.length!==64)throw new Error("Invalid signature length");let i=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=o8(c),d=jRe(t);if(!_Y.verify(Ms([i,a]),u,d))throw new Error("Invalid signature");return Hl(e).payload}var qRe="irn";function Z8(e){return e?.relay||{protocol:qRe}}function M1(e){let t=kC[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function WRe(e,t="-"){let r={},n="relay"+t;return Object.keys(e).forEach(o=>{if(o.startsWith(n)){let s=o.replace(n,""),i=e[o];r[s]=i}}),r}function dk(e){if(!e.includes("wc:")){let u=fQ(e);u?.includes("wc:")&&(e=u)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;let t=e.indexOf(":"),r=e.indexOf("?")!==-1?e.indexOf("?"):void 0,n=e.substring(0,t),o=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",i=new URLSearchParams(s),a=Object.fromEntries(i.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:KRe(o[0]),version:parseInt(o[1],10),symKey:a.symKey,relay:WRe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function KRe(e){return e.startsWith("//")?e.substring(2):e}function ZRe(e,t="-"){let r="relay",n={};return Object.keys(e).forEach(o=>{let s=o,i=r+t+s;e[s]&&(n[i]=e[s])}),n}function fk(e){let t=new URLSearchParams,r={...ZRe(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(r).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!==void 0&&t.append(n,String(o))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function G8(e,t,r){return`${e}?wc_ev=${r}&topic=${t}`}function ow(e){let t=[];return e.forEach(r=>{let[n,o]=r.split(":");t.push(`${n}:${o}`)}),t}function pk(e){let t=[];return Object.values(e).forEach(r=>{t.push(...ow(r.accounts))}),[...new Set(t)]}function DQ(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.methods)}),[...new Set(t)]}function LQ(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.events)}),[...new Set(t)]}function GRe(e,t){let r=[];return Object.values(e).forEach(n=>{ow(n.accounts).includes(t)&&r.push(...n.methods)}),r}function YRe(e,t){let r=[];return Object.values(e).forEach(n=>{ow(n.accounts).includes(t)&&r.push(...n.events)}),r}function Y8(e){return e.includes(":")}function H1(e){return Y8(e)?e.split(":")[0]:e}function JJ(e){let t={};if(!Ka(e))return t;for(let[r,n]of Object.entries(e)){let o=Y8(r)?[r]:n.chains,s=n.methods||[],i=n.events||[],a=H1(r);t[a]={...t[a],chains:Uc(o,t[a]?.chains),methods:Uc(s,t[a]?.methods),events:Uc(i,t[a]?.events)}}return t}function JRe(e){let t={};return e?.forEach(r=>{let[n,o]=r.split(":");t[n]||(t[n]={accounts:[],chains:[],events:[],methods:[]}),t[n].accounts.push(r),t[n].chains?.push(`${n}:${o}`)}),t}function hk(e,t){t=t.map(n=>n.replace("did:pkh:",""));let r=JRe(t);for(let[n,o]of Object.entries(r))o.methods?o.methods=Uc(o.methods,e):o.methods=e,o.events=["chainChanged","accountsChanged"];return r}function MQ(e,t){let r=JJ(e),n=JJ(t),o={},s=Object.keys(r).concat(Object.keys(n));for(let i of s)o[i]={chains:Uc(r[i]?.chains,n[i]?.chains),methods:Uc(r[i]?.methods,n[i]?.methods),events:Uc(r[i]?.events,n[i]?.events)};return o}function zs(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function Ka(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function In(e){return typeof e>"u"}function gn(e,t){return t&&In(e)?!0:typeof e=="string"&&!!e.trim().length}function mk(e,t){return t&&In(e)?!0:typeof e=="number"&&!isNaN(e)}function HQ(e,t){let{requiredNamespaces:r}=t,n=Object.keys(e.namespaces),o=Object.keys(r),s=!0;return U1(o,n)?(n.forEach(i=>{let{accounts:a,methods:c,events:u}=e.namespaces[i],d=ow(a),f=r[i];(!U1(rQ(i,f),d)||!U1(f.methods,c)||!U1(f.events,u))&&(s=!1)}),s):!1}function WC(e){return gn(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function QRe(e){if(gn(e,!1)&&e.includes(":")){let t=e.split(":");if(t.length===3){let r=t[0]+":"+t[1];return!!t[2]&&WC(r)}}return!1}function $Q(e){function t(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(gn(e,!1)){if(t(e))return!0;let r=fQ(e);return t(r)}}catch{}return!1}function FQ(e){return e?.proposer?.publicKey}function zQ(e){return e?.topic}function VQ(e,t){let r=null;return gn(e?.publicKey,!1)||(r=Se("MISSING_OR_INVALID",`${t} controller public key should be a string`)),r}function QJ(e){let t=!0;return zs(e)?e.length&&(t=e.every(r=>gn(r,!1))):t=!1,t}function XRe(e,t,r){let n=null;return zs(t)&&t.length?t.forEach(o=>{n||WC(o)||(n=Sr("UNSUPPORTED_CHAINS",`${r}, chain ${o} should be a string and conform to "namespace:chainId" format`))}):WC(e)||(n=Sr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function eOe(e,t,r){let n=null;return Object.entries(e).forEach(([o,s])=>{if(n)return;let i=XRe(o,rQ(o,s),`${t} ${r}`);i&&(n=i)}),n}function tOe(e,t){let r=null;return zs(e)?e.forEach(n=>{r||QRe(n)||(r=Sr("UNSUPPORTED_ACCOUNTS",`${t}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=Sr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function rOe(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=tOe(n?.accounts,`${t} namespace`);o&&(r=o)}),r}function nOe(e,t){let r=null;return QJ(e?.methods)?QJ(e?.events)||(r=Sr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Sr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}function jQ(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=nOe(n,`${t}, namespace`);o&&(r=o)}),r}function qQ(e,t,r){let n=null;if(e&&Ka(e)){let o=jQ(e,t);o&&(n=o);let s=eOe(e,t,r);s&&(n=s)}else n=Se("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return n}function eS(e,t){let r=null;if(e&&Ka(e)){let n=jQ(e,t);n&&(r=n);let o=rOe(e,t);o&&(r=o)}else r=Se("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function gk(e){return gn(e.protocol,!0)}function WQ(e,t){let r=!1;return t&&!e?r=!0:e&&zs(e)&&e.length&&e.forEach(n=>{r=gk(n)}),r}function KQ(e){return typeof e=="number"}function as(e){return typeof e<"u"&&typeof e!==null}function ZQ(e){return!(!e||typeof e!="object"||!e.code||!mk(e.code,!1)||!e.message||!gn(e.message,!1))}function GQ(e){return!(In(e)||!gn(e.method,!1))}function YQ(e){return!(In(e)||In(e.result)&&In(e.error)||!mk(e.id,!1)||!gn(e.jsonrpc,!1))}function JQ(e){return!(In(e)||!gn(e.name,!1))}function yk(e,t){return!(!WC(t)||!pk(e).includes(t))}function QQ(e,t,r){return gn(r,!1)?GRe(e,t).includes(r):!1}function XQ(e,t,r){return gn(r,!1)?YRe(e,t).includes(r):!1}function wk(e,t,r){let n=null,o=oOe(e),s=sOe(t),i=Object.keys(o),a=Object.keys(s),c=XJ(Object.keys(e)),u=XJ(Object.keys(t)),d=c.filter(f=>!u.includes(f));return d.length&&(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. +`)};function DRe(e){let t=JSON.stringify(e),r=new TextEncoder().encode(t),n=new Array(r.length);for(let o=0;o{let n=e.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(o=>{let s=n[o];if(!Array.isArray(s))throw new Error(`Ability limits ${o} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${o} is empty array, must be an array with objects`);s.forEach(i=>{if(typeof i!="object")throw new Error(`Ability limits (${o}) must be an array of objects, found: ${i}`)})})})}function MRe(e,t,r,n={}){return r?.sort((o,s)=>o.localeCompare(s)),{att:{[e]:HRe(t,r,n)}}}function HRe(e,t,r={}){t=t?.sort((o,s)=>o.localeCompare(s));let n=t.map(o=>({[`${e}/${o}`]:[r]}));return Object.assign({},...n)}function xQ(e){return D1(e),`urn:recap:${DRe(e).replace(/=/g,"")}`}function F8(e){let t=LRe(e.replace("urn:recap:",""));return D1(t),t}function vQ(e,t,r){let n=MRe(e,t,r);return xQ(n)}function $Re(e){return e&&e.includes("urn:recap:")}function EQ(e,t){let r=F8(e),n=F8(t),o=FRe(r,n);return xQ(o)}function FRe(e,t){D1(e),D1(t);let r=Object.keys(e.att).concat(Object.keys(t.att)).sort((o,s)=>o.localeCompare(s)),n={att:{}};return r.forEach(o=>{Object.keys(e.att?.[o]||{}).concat(Object.keys(t.att?.[o]||{})).sort((s,i)=>s.localeCompare(i)).forEach(s=>{n.att[o]={...n.att[o],[s]:e.att[o]?.[s]||t.att[o]?.[s]}})}),n}function zRe(e="",t){D1(t);let r="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(r))return e;let n=[],o=0;Object.keys(t.att).forEach(a=>{let c=Object.keys(t.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,p)=>f.action.localeCompare(p.action));let u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});let d=Object.keys(u).map(f=>(o++,`(${o}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});let s=n.join(" "),i=`${r}${s}`;return`${e?e+" ":""}${i}`}function sk(e){let t=F8(e);D1(t);let r=t.att?.eip155;return r?Object.keys(r).map(n=>n.split("/")[1]):[]}function ik(e){let t=F8(e);D1(t);let r=[];return Object.values(t.att).forEach(n=>{Object.values(n).forEach(o=>{o?.[0]?.chains&&r.push(o[0].chains)})}),[...new Set(r.flat())]}function W8(e){if(!e)return;let t=e?.[e.length-1];return $Re(t)?t:void 0}var AQ="base10",is="base16",to="base64pad",wf="base64url",K8="utf8",CQ=0,Mc=1,tw=2,VRe=0,YJ=1,$8=12,ak=32;function SQ(){let e=vC.utils.randomPrivateKey(),t=vC.getPublicKey(e);return{privateKey:Ut(e,is),publicKey:Ut(t,is)}}function XC(){let e=Us(ak);return Ut(e,is)}function IQ(e,t){let r=vC.getSharedSecret(Qt(e,is),Qt(t,is)),n=jG(o8,r,void 0,void 0,ak);return Ut(n,is)}function rw(e){let t=o8(Qt(e,is));return Ut(t,is)}function vi(e){let t=o8(Qt(e,K8));return Ut(t,is)}function TQ(e){return Qt(`${e}`,AQ)}function yh(e){return Number(Ut(e,AQ))}function _Q(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qC(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4;return t+"=".repeat(r)}function PQ(e){let t=TQ(typeof e.type<"u"?e.type:CQ);if(yh(t)===Mc&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");let r=typeof e.senderPublicKey<"u"?Qt(e.senderPublicKey,is):void 0,n=typeof e.iv<"u"?Qt(e.iv,is):Us($8),o=Qt(e.symKey,is),s=LO(o,n).encrypt(Qt(e.message,K8)),i=BQ({type:t,sealed:s,iv:n,senderPublicKey:r});return e.encoding===wf?_Q(i):i}function NQ(e){let t=Qt(e.symKey,is),{sealed:r,iv:n}=nw({encoded:e.encoded,encoding:e.encoding}),o=LO(t,n).decrypt(r);if(o===null)throw new Error("Failed to decrypt");return Ut(o,K8)}function RQ(e,t){let r=TQ(tw),n=Us($8),o=Qt(e,K8),s=BQ({type:r,sealed:o,iv:n});return t===wf?_Q(s):s}function OQ(e,t){let{sealed:r}=nw({encoded:e,encoding:t});return Ut(r,K8)}function BQ(e){if(yh(e.type)===tw)return Ut(Ms([e.type,e.sealed]),to);if(yh(e.type)===Mc){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ut(Ms([e.type,e.senderPublicKey,e.iv,e.sealed]),to)}return Ut(Ms([e.type,e.iv,e.sealed]),to)}function nw(e){let t=(e.encoding||to)===wf?qC(e.encoded):e.encoded,r=Qt(t,to),n=r.slice(VRe,YJ),o=YJ;if(yh(n)===Mc){let c=o+ak,u=c+$8,d=r.slice(o,c),f=r.slice(c,u),p=r.slice(u);return{type:n,sealed:p,iv:f,senderPublicKey:d}}if(yh(n)===tw){let c=r.slice(o),u=Us($8);return{type:n,sealed:c,iv:u}}let s=o+$8,i=r.slice(o,s),a=r.slice(s);return{type:n,sealed:a,iv:i}}function kQ(e,t){let r=nw({encoded:e,encoding:t?.encoding});return ck({type:yh(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ut(r.senderPublicKey,is):void 0,receiverPublicKey:t?.receiverPublicKey})}function ck(e){let t=e?.type||CQ;if(t===Mc){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function lk(e){return e.type===Mc&&typeof e.senderPublicKey=="string"&&typeof e.receiverPublicKey=="string"}function uk(e){return e.type===tw}function jRe(e){let t=Qt(qC(e.x),to),r=Qt(qC(e.y),to);return Ms([new Uint8Array([4]),t,r])}function UQ(e,t){let[r,n,o]=e.split("."),s=Qt(qC(o),to);if(s.length!==64)throw new Error("Invalid signature length");let i=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=o8(c),d=jRe(t);if(!_Y.verify(Ms([i,a]),u,d))throw new Error("Invalid signature");return Hl(e).payload}var qRe="irn";function Z8(e){return e?.relay||{protocol:qRe}}function M1(e){let t=kC[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function WRe(e,t="-"){let r={},n="relay"+t;return Object.keys(e).forEach(o=>{if(o.startsWith(n)){let s=o.replace(n,""),i=e[o];r[s]=i}}),r}function dk(e){if(!e.includes("wc:")){let u=fQ(e);u?.includes("wc:")&&(e=u)}e=e.includes("wc://")?e.replace("wc://",""):e,e=e.includes("wc:")?e.replace("wc:",""):e;let t=e.indexOf(":"),r=e.indexOf("?")!==-1?e.indexOf("?"):void 0,n=e.substring(0,t),o=e.substring(t+1,r).split("@"),s=typeof r<"u"?e.substring(r):"",i=new URLSearchParams(s),a=Object.fromEntries(i.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:KRe(o[0]),version:parseInt(o[1],10),symKey:a.symKey,relay:WRe(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function KRe(e){return e.startsWith("//")?e.substring(2):e}function ZRe(e,t="-"){let r="relay",n={};return Object.keys(e).forEach(o=>{let s=o,i=r+t+s;e[s]&&(n[i]=e[s])}),n}function fk(e){let t=new URLSearchParams,r={...ZRe(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(r).sort(([n],[o])=>n.localeCompare(o)).forEach(([n,o])=>{o!==void 0&&t.append(n,String(o))}),`${e.protocol}:${e.topic}@${e.version}?${t}`}function G8(e,t,r){return`${e}?wc_ev=${r}&topic=${t}`}function ow(e){let t=[];return e.forEach(r=>{let[n,o]=r.split(":");t.push(`${n}:${o}`)}),t}function pk(e){let t=[];return Object.values(e).forEach(r=>{t.push(...ow(r.accounts))}),[...new Set(t)]}function DQ(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.methods)}),[...new Set(t)]}function LQ(e){let t=[];return Object.values(e).forEach(r=>{t.push(...r.events)}),[...new Set(t)]}function GRe(e,t){let r=[];return Object.values(e).forEach(n=>{ow(n.accounts).includes(t)&&r.push(...n.methods)}),r}function YRe(e,t){let r=[];return Object.values(e).forEach(n=>{ow(n.accounts).includes(t)&&r.push(...n.events)}),r}function Y8(e){return e.includes(":")}function H1(e){return Y8(e)?e.split(":")[0]:e}function JJ(e){let t={};if(!Ka(e))return t;for(let[r,n]of Object.entries(e)){let o=Y8(r)?[r]:n.chains,s=n.methods||[],i=n.events||[],a=H1(r);t[a]={...t[a],chains:Uc(o,t[a]?.chains),methods:Uc(s,t[a]?.methods),events:Uc(i,t[a]?.events)}}return t}function JRe(e){let t={};return e?.forEach(r=>{let[n,o]=r.split(":");t[n]||(t[n]={accounts:[],chains:[],events:[],methods:[]}),t[n].accounts.push(r),t[n].chains?.push(`${n}:${o}`)}),t}function hk(e,t){t=t.map(n=>n.replace("did:pkh:",""));let r=JRe(t);for(let[n,o]of Object.entries(r))o.methods?o.methods=Uc(o.methods,e):o.methods=e,o.events=["chainChanged","accountsChanged"];return r}function MQ(e,t){let r=JJ(e),n=JJ(t),o={},s=Object.keys(r).concat(Object.keys(n));for(let i of s)o[i]={chains:Uc(r[i]?.chains,n[i]?.chains),methods:Uc(r[i]?.methods,n[i]?.methods),events:Uc(r[i]?.events,n[i]?.events)};return o}function zs(e,t){return Array.isArray(e)?typeof t<"u"&&e.length?e.every(t):!0:!1}function Ka(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function In(e){return typeof e>"u"}function gn(e,t){return t&&In(e)?!0:typeof e=="string"&&!!e.trim().length}function mk(e,t){return t&&In(e)?!0:typeof e=="number"&&!isNaN(e)}function HQ(e,t){let{requiredNamespaces:r}=t,n=Object.keys(e.namespaces),o=Object.keys(r),s=!0;return U1(o,n)?(n.forEach(i=>{let{accounts:a,methods:c,events:u}=e.namespaces[i],d=ow(a),f=r[i];(!U1(rQ(i,f),d)||!U1(f.methods,c)||!U1(f.events,u))&&(s=!1)}),s):!1}function WC(e){return gn(e,!1)&&e.includes(":")?e.split(":").length===2:!1}function QRe(e){if(gn(e,!1)&&e.includes(":")){let t=e.split(":");if(t.length===3){let r=t[0]+":"+t[1];return!!t[2]&&WC(r)}}return!1}function $Q(e){function t(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(gn(e,!1)){if(t(e))return!0;let r=fQ(e);return t(r)}}catch{}return!1}function FQ(e){return e?.proposer?.publicKey}function zQ(e){return e?.topic}function VQ(e,t){let r=null;return gn(e?.publicKey,!1)||(r=Se("MISSING_OR_INVALID",`${t} controller public key should be a string`)),r}function QJ(e){let t=!0;return zs(e)?e.length&&(t=e.every(r=>gn(r,!1))):t=!1,t}function XRe(e,t,r){let n=null;return zs(t)&&t.length?t.forEach(o=>{n||WC(o)||(n=Sr("UNSUPPORTED_CHAINS",`${r}, chain ${o} should be a string and conform to "namespace:chainId" format`))}):WC(e)||(n=Sr("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function eOe(e,t,r){let n=null;return Object.entries(e).forEach(([o,s])=>{if(n)return;let i=XRe(o,rQ(o,s),`${t} ${r}`);i&&(n=i)}),n}function tOe(e,t){let r=null;return zs(e)?e.forEach(n=>{r||QRe(n)||(r=Sr("UNSUPPORTED_ACCOUNTS",`${t}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=Sr("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function rOe(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=tOe(n?.accounts,`${t} namespace`);o&&(r=o)}),r}function nOe(e,t){let r=null;return QJ(e?.methods)?QJ(e?.events)||(r=Sr("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):r=Sr("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),r}function jQ(e,t){let r=null;return Object.values(e).forEach(n=>{if(r)return;let o=nOe(n,`${t}, namespace`);o&&(r=o)}),r}function qQ(e,t,r){let n=null;if(e&&Ka(e)){let o=jQ(e,t);o&&(n=o);let s=eOe(e,t,r);s&&(n=s)}else n=Se("MISSING_OR_INVALID",`${t}, ${r} should be an object with data`);return n}function eS(e,t){let r=null;if(e&&Ka(e)){let n=jQ(e,t);n&&(r=n);let o=rOe(e,t);o&&(r=o)}else r=Se("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return r}function gk(e){return gn(e.protocol,!0)}function WQ(e,t){let r=!1;return t&&!e?r=!0:e&&zs(e)&&e.length&&e.forEach(n=>{r=gk(n)}),r}function KQ(e){return typeof e=="number"}function as(e){return typeof e<"u"&&typeof e!==null}function ZQ(e){return!(!e||typeof e!="object"||!e.code||!mk(e.code,!1)||!e.message||!gn(e.message,!1))}function GQ(e){return!(In(e)||!gn(e.method,!1))}function YQ(e){return!(In(e)||In(e.result)&&In(e.error)||!mk(e.id,!1)||!gn(e.jsonrpc,!1))}function JQ(e){return!(In(e)||!gn(e.name,!1))}function yk(e,t){return!(!WC(t)||!pk(e).includes(t))}function QQ(e,t,r){return gn(r,!1)?GRe(e,t).includes(r):!1}function XQ(e,t,r){return gn(r,!1)?YRe(e,t).includes(r):!1}function wk(e,t,r){let n=null,o=oOe(e),s=sOe(t),i=Object.keys(o),a=Object.keys(s),c=XJ(Object.keys(e)),u=XJ(Object.keys(t)),d=c.filter(f=>!u.includes(f));return d.length&&(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces. Required: ${d.toString()} Received: ${Object.keys(t).toString()}`)),U1(i,a)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces. Required: ${i.toString()} Approved: ${a.toString()}`)),Object.keys(t).forEach(f=>{if(!f.includes(":")||n)return;let p=ow(t[f].accounts);p.includes(f)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${f} Required: ${f} - Approved: ${p.toString()}`))}),i.forEach(f=>{n||(U1(o[f].methods,s[f].methods)?U1(o[f].events,s[f].events)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function oOe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:e[r].chains?.forEach(n=>{t[n]={methods:e[r].methods,events:e[r].events}})}),t}function XJ(e){return[...new Set(e.map(t=>t.includes(":")?t.split(":")[0]:t))]}function sOe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:ow(e[r].accounts)?.forEach(n=>{t[n]={accounts:e[r].accounts.filter(o=>o.includes(`${n}:`)),methods:e[r].methods,events:e[r].events}})}),t}function eX(e,t){return mk(e,!1)&&e<=t.max&&e>=t.min}function bk(){let e=V8();return new Promise(t=>{switch(e){case bi.browser:t(iOe());break;case bi.reactNative:t(aOe());break;case bi.node:t(cOe());break;default:t(!0)}})}function iOe(){return L1()&&navigator?.onLine}async function aOe(){return gf()&&typeof global<"u"&&global?.NetInfo?(await global?.NetInfo.fetch())?.isConnected:!0}function cOe(){return!0}function tX(e){switch(V8()){case bi.browser:lOe(e);break;case bi.reactNative:uOe(e);break;case bi.node:break}}function lOe(e){!gf()&&L1()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}function uOe(e){gf()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener(t=>e(t?.isConnected))}function rX(){return L1()&&(0,Dc.getDocument)()?(0,Dc.getDocument)()?.visibilityState==="visible":!0}var ZB={},wh=class{static get(t){return ZB[t]}static set(t,r){ZB[t]=r}static delete(t){delete ZB[t]}};function dOe(e){let t=B2.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}function fOe({publicKey:e,signature:t,payload:r}){let n=KC(r.method),o=128|parseInt(r.version?.toString()||"4"),s=mOe(r.address),i=r.era==="00"?new Uint8Array([0]):KC(r.era);if(i.length!==1&&i.length!==2)throw new Error("Invalid era length");let a=parseInt(r.nonce,16),c=new Uint8Array([a&255,a>>8&255]),u=BigInt(`0x${hOe(r.tip)}`),d=yOe(u),f=new Uint8Array([0,...e,s,...t,...i,...c,...d,...n]),p=gOe(f.length+1);return new Uint8Array([...p,o,...f])}function pOe(e){let t=KC(e),r=(0,tQ.blake2b)(t,void 0,32);return"0x"+Ut(r,"base16")}function KC(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(t=>parseInt(t,16)))}function hOe(e){return e.startsWith("0x")?e.slice(2):e}function mOe(e){let t=B2.decode(e)[0];return t===42?0:t===60?2:1}function gOe(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([t&255,t>>8&255])}else if(e<1<<30){let t=e<<2|2;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function yOe(e){if(e<1n<<6n)return new Uint8Array([Number(e<<2n)]);if(e<1n<<14n){let t=e<<2n|0x01n;return new Uint8Array([Number(t&0xffn),Number(t>>8n&0xffn)])}else if(e<1n<<30n){let t=e<<2n|0x02n;return new Uint8Array([Number(t&0xffn),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}else throw new Error("BigInt compact encoding not supported > 2^30")}function nX(e){let t=KC(e.signature),r=dOe(e.transaction.address),n=fOe({publicKey:r,signature:t,payload:e.transaction}),o=Ut(n,"base16");return pOe(o)}function sw({logger:e,name:t}){let r=typeof e=="string"?Fl({opts:{level:e,name:t}}).logger:e;return r.level=typeof e=="string"?e:e.level,r}l();l();var QS=Ht(ks(),1);l();var xf=Ht(ks(),1);vk();Rk();gh();l();tS();var CX=Ht(ks()),oS=class extends yo{constructor(t){super(),this.opts=t,this.protocol="wc",this.version=2}};var sS=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r,this.records=new Map}},iS=class{constructor(t,r){this.logger=t,this.core=r}},aS=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},cS=class extends yo{constructor(t){super()}},lS=class{constructor(t,r,n,o){this.core=t,this.logger=r,this.name=n}};var uS=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}};var dS=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r}};var fS=class{constructor(t,r,n){this.core=t,this.logger=r,this.store=n}},pS=class{constructor(t,r){this.projectId=t,this.logger=r}},hS=class{constructor(t,r,n){this.core=t,this.logger=r,this.telemetryEnabled=n}};var mS=class{constructor(t){this.opts=t,this.protocol="wc",this.version=2}};var gS=class{constructor(t){this.client=t}};var Ge=Ht(jd(),1);R1();B1();B1();BO();I8();cw();$c();Hk();l();l();l();function XX(e){return Number.isSafeInteger(e)&&e>=0}function eee(e){return e!=null&&typeof e!="function"&&XX(e.length)}l();function tee(e){return e==="__proto__"}l();function uw(e){return e==null||typeof e!="object"&&typeof e!="function"}l();function ree(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}l();l();function F1(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}l();function bf(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}l();var PS="[object RegExp]",dw="[object String]",fw="[object Number]",pw="[object Boolean]",z1="[object Arguments]",NS="[object Symbol]",RS="[object Date]",OS="[object Map]",BS="[object Set]",kS="[object Array]",nee="[object Function]",US="[object ArrayBuffer]",Ah="[object Object]",oee="[object Error]",DS="[object DataView]",LS="[object Uint8Array]",MS="[object Uint8ClampedArray]",HS="[object Uint16Array]",$S="[object Uint32Array]",see="[object BigUint64Array]",FS="[object Int8Array]",zS="[object Int16Array]",VS="[object Int32Array]",iee="[object BigInt64Array]",jS="[object Float32Array]",qS="[object Float64Array]";l();function hw(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function aee(e,t){return mw(e,void 0,e,new Map,t)}function mw(e,t,r,n=new Map,o=void 0){let s=o?.(e,t,r,n);if(s!==void 0)return s;if(uw(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){let i=new Array(e.length);n.set(e,i);for(let a=0;a{let i=t?.(r,n,o,s);if(i!==void 0)return i;if(typeof e=="object"){if(bf(e)===Ah&&typeof e.constructor!="function"){let a={};return s.set(e,a),Za(a,e,o,s),a}switch(Object.prototype.toString.call(e)){case fw:case dw:case pw:{let a=new e.constructor(e?.valueOf());return Za(a,e),a}case z1:{let a={};return Za(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}}})}function $k(e){return cee(e)}l();function Fk(e){return e!==null&&typeof e=="object"&&bf(e)==="[object Arguments]"}l();l();function s4(e){return typeof e=="object"&&e!==null}function lee(e){return s4(e)&&eee(e)}l();l();l();function zk(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function uee(e,t,r){return i4(e,t,void 0,void 0,void 0,void 0,r)}function i4(e,t,r,n,o,s,i){let a=i(e,t,r,n,o,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return a4(e,t,s,i)}return a4(e,t,s,i)}function a4(e,t,r,n){if(Object.is(e,t))return!0;let o=bf(e),s=bf(t);if(o===z1&&(o=Ah),s===z1&&(s=Ah),o!==s)return!1;switch(o){case dw:return e.toString()===t.toString();case fw:{let c=e.valueOf(),u=t.valueOf();return ree(c,u)}case pw:case RS:case NS:return Object.is(e.valueOf(),t.valueOf());case PS:return e.source===t.source&&e.flags===t.flags;case nee:return e===t}r=r??new Map;let i=r.get(e),a=r.get(t);if(i!=null&&a!=null)return i===t;r.set(e,t),r.set(t,e);try{switch(o){case OS:{if(e.size!==t.size)return!1;for(let[c,u]of e.entries())if(!t.has(c)||!i4(u,t.get(c),c,e,t,r,n))return!1;return!0}case BS:{if(e.size!==t.size)return!1;let c=Array.from(e.values()),u=Array.from(t.values());for(let d=0;di4(f,h,void 0,e,t,r,n));if(p===-1)return!1;u.splice(p,1)}return!0}case kS:case LS:case MS:case HS:case $S:case see:case FS:case zS:case VS:case iee:case jS:case qS:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,o)=>{this.isInitialized(),this.keychain.set(n,o),await this.persist()},this.get=n=>{this.isInitialized();let o=this.keychain.get(n);if(typeof o>"u"){let{message:s}=Se("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return o},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=t,this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,ZC(t))}async getKeyChain(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?GC(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Kk=class{constructor(t,r,n){this.core=t,this.logger=r,this.name=rBe,this.randomSessionIdentifier=XC(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=o=>(this.isInitialized(),this.keychain.has(o)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;let o=await this.getClientSeed(),s=J2(o),i=U8(s.publicKey);return this.clientId=i,i},this.generateKeyPair=()=>{this.isInitialized();let o=SQ();return this.setPrivateKey(o.publicKey,o.privateKey)},this.signJWT=async o=>{this.isInitialized();let s=await this.getClientSeed(),i=J2(s),a=this.randomSessionIdentifier;return await BC(a,o,nBe,i)},this.generateSharedKey=(o,s,i)=>{this.isInitialized();let a=this.getPrivateKey(o),c=IQ(a,s);return this.setSymKey(c,i)},this.setSymKey=async(o,s)=>{this.isInitialized();let i=s||rw(o);return await this.keychain.set(i,o),i},this.deleteKeyPair=async o=>{this.isInitialized(),await this.keychain.del(o)},this.deleteSymKey=async o=>{this.isInitialized(),await this.keychain.del(o)},this.encode=async(o,s,i)=>{this.isInitialized();let a=ck(i),c=yi(s);if(uk(a))return RQ(c,i?.encoding);if(lk(a)){let p=a.senderPublicKey,h=a.receiverPublicKey;o=await this.generateSharedKey(p,h)}let u=this.getSymKey(o),{type:d,senderPublicKey:f}=a;return PQ({type:d,symKey:u,message:c,senderPublicKey:f,encoding:i?.encoding})},this.decode=async(o,s,i)=>{this.isInitialized();let a=kQ(s,i);if(uk(a)){let c=OQ(s,i?.encoding);return Fs(c)}if(lk(a)){let c=a.receiverPublicKey,u=a.senderPublicKey;o=await this.generateSharedKey(c,u)}try{let c=this.getSymKey(o),u=NQ({symKey:c,encoded:s,encoding:i?.encoding});return Fs(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(o,s=to)=>{let i=nw({encoded:o,encoding:s});return yh(i.type)},this.getPayloadSenderPublicKey=(o,s=to)=>{let i=nw({encoded:o,encoding:s});return i.senderPublicKey?Ut(i.senderPublicKey,is):void 0},this.core=t,this.logger=Cr(r,this.name),this.keychain=n||new Wk(this.core,this.logger)}get context(){return sr(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(pee)}catch{t=XC(),await this.keychain.set(pee,t)}return Qt(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Zk=class extends iS{constructor(t,r){super(t,r),this.logger=t,this.core=r,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name=iBe,this.version=aBe,this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);let o=await this.getRelayerMessagesWithoutClientAck();typeof o<"u"&&(this.messagesWithoutClientAck=o),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,o,s)=>{this.isInitialized();let i=xi(o),a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[i]<"u")return i;if(a[i]=o,this.messages.set(n,a),s===YS.inbound){let c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,{...c,[i]:o})}return await this.persist(),i},this.get=n=>{this.isInitialized();let o=this.messages.get(n);return typeof o>"u"&&(o={}),o},this.getWithoutAck=n=>{this.isInitialized();let o={};for(let s of n){let i=this.messagesWithoutClientAck.get(s)||{};o[s]=Object.values(i)}return o},this.has=(n,o)=>{this.isInitialized();let s=this.get(n),i=xi(o);return typeof s[i]<"u"},this.ack=async(n,o)=>{this.isInitialized();let s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;let i=xi(o);delete s[i],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()},this.del=async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()},this.logger=Cr(t,this.name),this.core=r}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,ZC(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,ZC(t))}async getRelayerMessages(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?GC(t):void 0}async getRelayerMessagesWithoutClientAck(){let t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?GC(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Gk=class extends aS{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.events=new xf.EventEmitter,this.name=lBe,this.queue=new Map,this.publishTimeout=(0,Ge.toMiliseconds)(Ge.ONE_MINUTE),this.initialPublishTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(n,o,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:o,opts:s}});let i=s?.ttl||cBe,a=s?.prompt||!1,c=s?.tag||0,u=s?.id||_n().toString(),d=M1(Z8().protocol),f={id:u,method:s?.publishMethod||d.publish,params:{topic:n,message:o,ttl:i,prompt:a,tag:c,attestation:s?.attestation,...s?.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${c}`;try{In(f.params?.prompt)&&delete f.params?.prompt,In(f.params?.tag)&&delete f.params?.tag;let h=new Promise(async y=>{let w=({id:v})=>{f.id?.toString()===v.toString()&&(this.removeRequestFromQueue(v),this.relayer.events.removeListener(yn.publish,w),y())};this.relayer.events.on(yn.publish,w);let x=Wa(new Promise((v,T)=>{this.rpcPublish(f,s).then(v).catch(E=>{this.logger.warn(E,E?.message),T(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${c}`);try{await x,this.events.removeListener(yn.publish,w)}catch(v){this.queue.set(u,{request:f,opts:s,attempt:1}),this.logger.warn(v,v?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:n,message:o,opts:s}}),await Wa(h,this.publishTimeout,p)}catch(h){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(h),s?.internal?.throwOnFailedPublish)throw h}finally{this.queue.delete(u)}},this.publishCustom=async n=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});let{payload:o,opts:s={}}=n,{attestation:i,tvf:a,publishMethod:c,prompt:u,tag:d,ttl:f=Ge.FIVE_MINUTES}=s,p=s.id||_n().toString(),h=M1(Z8().protocol),y=c||h.publish,w={id:p,method:y,params:{...o,ttl:f,prompt:u,tag:d,attestation:i,...a}},x=`Failed to publish custom payload, please try again. id:${p} tag:${d}`;try{In(w.params?.prompt)&&delete w.params?.prompt,In(w.params?.tag)&&delete w.params?.tag;let v=new Promise(async T=>{let E=({id:_})=>{w.id?.toString()===_.toString()&&(this.removeRequestFromQueue(_),this.relayer.events.removeListener(yn.publish,E),T())};this.relayer.events.on(yn.publish,E);let S=Wa(new Promise((_,O)=>{this.rpcPublish(w,s).then(_).catch(D=>{this.logger.warn(D,D?.message),O(D)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${p} tag:${d}`);try{await S,this.events.removeListener(yn.publish,E)}catch(_){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(_,_?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,payload:o,opts:s}}),await Wa(v,this.publishTimeout,x)}catch(v){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(v),s?.internal?.throwOnFailedPublish)throw v}finally{this.queue.delete(p)}},this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.relayer=t,this.logger=Cr(r,this.name),this.registerEventListeners()}get context(){return sr(this.logger)}async rpcPublish(t,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});let n=await this.relayer.request(t);return this.relayer.events.emit(yn.publish,{...t,...r}),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,r)=>{let n=t.attempt+1;this.queue.set(r,{...t,attempt:n}),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${t.request.params?.tag}, attempt: ${n}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(yn.connection_stalled);return}this.checkQueue()}),this.relayer.on(yn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}},Yk=class{constructor(){this.map=new Map,this.set=(t,r)=>{let n=this.get(t);this.exists(t,r)||this.map.set(t,[...n,r])},this.get=t=>this.map.get(t)||[],this.exists=(t,r)=>this.get(t).includes(r),this.delete=(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;let n=this.get(t);if(!this.exists(t,r))return;let o=n.filter(s=>s!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Jk=class extends uS{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.subscriptions=new Map,this.topicMap=new Yk,this.events=new xf.EventEmitter,this.name=gBe,this.version=yBe,this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.subscribeTimeout=(0,Ge.toMiliseconds)(Ge.ONE_MINUTE),this.initialSubscribeTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(n,o)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}});try{let s=Z8(o),i={topic:n,relay:s,transportType:o?.transportType};o?.internal?.skipSubscribe||this.pending.set(n,i);let a=await this.rpcSubscribe(n,s,o);return typeof a=="string"&&(this.onSubscribe(a,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,o)=>{this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(n,o.id,o):await this.unsubscribeByTopic(n,o)},this.isSubscribed=n=>new Promise(o=>{o(this.topicMap.topics.includes(n))}),this.isKnownTopic=n=>new Promise(o=>{o(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))}),this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;let n=[];this.pending.forEach(o=>{n.push(o)}),await this.batchSubscribe(n)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(Vs.pulse,async()=>{await this.checkPending()}),this.events.on(fa.created,async n=>{let o=fa.created;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()}),this.events.on(fa.deleted,async n=>{let o=fa.deleted;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()})},this.relayer=t,this.logger=Cr(r,this.name),this.clientId=""}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,r){let n=!1;try{n=this.getSubscription(t).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){let n=this.topicMap.get(t);await Promise.all(n.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}});try{let o=Sr("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,o);let s=Z8(n);await this.restartToComplete({topic:t,id:r,relay:s}),await this.rpcUnsubscribe(t,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r,n){let o=await this.getSubscriptionId(t);if(n?.internal?.skipSubscribe)return o;(!n||n?.transportType===Dr.relay)&&await this.restartToComplete({topic:t,id:t,relay:r});let s={method:M1(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let i=n?.internal?.throwOnFailedPublish;try{if(n?.transportType===Dr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},(0,Ge.toMiliseconds)(Ge.ONE_SECOND)),o;let a=new Promise(async u=>{let d=f=>{f.topic===t&&(this.events.removeListener(fa.created,d),u(f.id))};this.events.on(fa.created,d);try{let f=await Wa(new Promise((p,h)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),h(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(fa.created,d),u(f)}catch{}}),c=await Wa(a,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!c&&i)throw new Error(`Subscribing to ${t} failed, please try again`);return c?o:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(yn.connection_stalled),i)throw a}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;let r=t[0].relay,n={method:M1(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await Wa(new Promise((o,s)=>{this.relayer.request(n).then(o).catch(i=>{this.logger.warn(i),s(i)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(yn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;let r=t[0].relay,n={method:M1(r.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let o;try{o=await await Wa(new Promise((s,i)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),i(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(yn.connection_stalled)}return o}rpcUnsubscribe(t,r,n){let o={method:M1(n.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,{...r,id:t}),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,{...r}),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,n),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r)}addSubscription(t,r){this.subscriptions.set(t,{...r}),this.topicMap.set(r.topic,t),this.events.emit(fa.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});let r=this.subscriptions.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});let n=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(n.topic,t),this.events.emit(fa.deleted,{...n,reason:r})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(fa.sync)}async onRestart(){if(this.cached.length){let t=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n"u"||!t.length)return;if(this.subscriptions.size&&!t.every(r=>r.topic===this.subscriptions.get(r.id)?.topic)){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(r=>{this.pending.set(r.topic,r)});return}this.onBatchSubscribe(await Promise.all(t.map(async r=>({...r,id:await this.getSubscriptionId(r.topic)}))))}}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);let r=await this.rpcBatchFetchMessages(t);r&&r.messages&&(await pQ((0,Ge.toMiliseconds)(Ge.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return xi(t+await this.getClientId())}},Qk=class extends cS{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new xf.EventEmitter,this.name=dBe,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=(0,Ge.toMiliseconds)(Ge.THIRTY_SECONDS+Ge.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*2),this.stalledRestartMaxInterval=(0,Ge.toMiliseconds)(Ge.THIRTY_SECONDS),this.request=async r=>{this.logger.debug("Publishing Request Payload");let n=r.id||_n().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:r.method,topic:r.params?.topic},"relayer.request - publishing...");let o=`${n}:${r.params?.tag||""}`;this.requestsInFlight.push(o);let s=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(i=>i!==o),s}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}},this.resetPingTimeout=()=>{z8()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(r){this.logger.warn(r,r?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(yn.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(yn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(n=>this.logger.warn(n))},this.registerProviderListeners=()=>{this.provider.on(Ga.payload,this.onPayloadHandler),this.provider.on(Ga.connect,this.onConnectHandler),this.provider.on(Ga.disconnect,this.onDisconnectHandler),this.provider.on(Ga.error,this.onProviderErrorHandler)},this.core=t.core,this.logger=sw({logger:t.logger??uBe,name:this.name}),this.messages=new Zk(this.logger,t.core),this.subscriber=new Jk(this,this.logger),this.publisher=new Gk(this,this.logger),this.projectId=t.projectId,this.relayUrl=t.relayUrl||wee,nQ()?this.packageName=YB():oQ()&&(this.bundleId=YB()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return sr(this.logger)}get connected(){return this.provider?.connection?.socket?.readyState===1}get connecting(){return this.provider?.connection?.socket?.readyState===0||this.connectPromise!==void 0}async publish(t,r,n){this.isInitialized(),await this.publisher.publish(t,r,n),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now(),transportType:Dr.relay},YS.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,r){this.isInitialized(),(!r?.transportType||r?.transportType==="relay")&&await this.toEstablishConnection();let n=r?.internal?.throwOnFailedPublish??!0,o=this.subscriber.topicMap.get(t)?.[0]||"",s,i=a=>{a.topic===t&&(this.subscriber.off(fa.created,i),s())};return await Promise.all([new Promise(a=>{s=a,this.subscriber.on(fa.created,i)}),new Promise((a,c)=>{this.subscriber.subscribe(t,{internal:{throwOnFailedPublish:n},...r}).then(u=>{o=u||o,a()}).catch(u=>{n?c(u):a()})})]),o}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Wa(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=this.connect(t).finally(()=>{this.connectPromise=void 0}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await bk())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}let r=t.sort((n,o)=>n.publishedAt-o.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(let n of r)try{await this.onMessageEvent(n)}catch(o){this.logger.warn(o,"Error while processing batch message event: "+o?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(t,r){let{topic:n}=t;if(!r.sessionExists){let o=ln(Ge.FIVE_MINUTES),s={topic:n,expiry:o,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(yn.message,t),await this.recordMessageEvent(t,YS.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let r=1;try{for(;r<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise((n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ga.disconnect,s),Wa(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>n()).catch(o).finally(()=>{this.provider.off(Ga.disconnect,s),clearTimeout(this.reconnectTimeout)})}),await new Promise((n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ga.disconnect,s),this.subscriber.start().then(n).catch(o).finally(()=>{this.provider.off(Ga.disconnect,s)})}),this.hasExperiencedNetworkDisruption=!1}catch(n){await this.subscriber.stop();let o=n;this.logger.warn({},o.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,(0,Ge.toMiliseconds)(r*1))),r++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(z8())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(t){this.logger.warn(t,t?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await Wa(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}let t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new da(new lw(iQ({sdkVersion:qk,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,r){let{topic:n,message:o}=t;await this.messages.set(n,o,r)}async shouldIgnoreMessageEvent(t){let{topic:r,message:n}=t;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;let o=this.messages.has(r,n);return o&&this.logger.warn(`Ignoring duplicate message: ${n}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Hc(t)){if(!t.method.endsWith(fBe))return;let r=t.params,{topic:n,message:o,publishedAt:s,attestation:i}=r.data,a={topic:n,message:o,publishedAt:s,transportType:Dr.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:r.id,...a}),this.events.emit(r.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else ua(t)&&this.events.emit(yn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,YS.inbound),this.events.emit(yn.message,t))}async acknowledgePayload(t){let r=bo(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Ga.payload,this.onPayloadHandler),this.provider.off(Ga.connect,this.onConnectHandler),this.provider.off(Ga.disconnect,this.onDisconnectHandler),this.provider.off(Ga.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await bk();tX(async r=>{t!==r&&(t=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vs.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&rX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}}),this.events.on(yn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;let r=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${r?` in ${r}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(n){this.logger.error(n,n?.message)}finally{this.stalledRestartInProgress=!1}},r)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(yn.disconnect),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(t){this.logger.warn(t,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed){this.reconnectInProgress=!1;return}this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,Ge.toMiliseconds)(pBe))}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}},jl=class extends lS{constructor(t,r,n,o=Vl,s=void 0){super(t,r,n,o),this.core=t,this.logger=r,this.name=n,this.map=new Map,this.version=hBe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>{this.getKey&&i!==null&&!In(i)?this.map.set(this.getKey(i),i):FQ(i)?this.map.set(i.id,i):zQ(i)&&this.map.set(i.topic,i)}),this.cached=[],this.initialized=!0)},this.set=async(i,a)=>{this.isInitialized(),this.map.has(i)?await this.update(i,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:i,value:a}),this.map.set(i,a),await this.persist())},this.get=i=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:i}),this.getData(i)),this.getAll=i=>(this.isInitialized(),i?this.values.filter(a=>Object.keys(i).every(c=>Vk(a[c],i[c]))):this.values),this.update=async(i,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:i,update:a});let c={...this.getData(i),...a};this.map.set(i,c),await this.persist()},this.delete=async(i,a)=>{this.isInitialized(),this.map.has(i)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:i,reason:a}),this.map.delete(i),this.addToRecentlyDeleted(i),await this.persist())},this.logger=Cr(r,this.name),this.storagePrefix=o,this.getKey=s}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){let r=this.map.get(t);if(!r){if(this.recentlyDeleted.includes(t)){let{message:o}=Se("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(o),new Error(o)}let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Xk=class{constructor(t,r){this.core=t,this.logger=r,this.name=wBe,this.version=bBe,this.events=new xf.default,this.initialized=!1,this.storagePrefix=Vl,this.ignoredPayloadTypes=[Mc],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let o=XC(),s=await this.core.crypto.setSymKey(o),i=ln(Ge.FIVE_MINUTES),a={protocol:sU},c={topic:s,expiry:i,relay:a,active:!1,methods:n?.methods},u=fk({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:o,relay:a,expiryTimestamp:i,methods:n?.methods});return this.events.emit(Ch.create,c),this.core.expirer.set(s,i),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}},this.pair=async n=>{this.isInitialized();let o=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[zc.pairing_started]}});this.isValidPair(n,o);let{topic:s,symKey:i,relay:a,expiryTimestamp:c,methods:u}=dk(n.uri);o.props.properties.topic=s,o.addTrace(zc.pairing_uri_validation_success),o.addTrace(zc.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(s)){if(d=this.pairings.get(s),o.addTrace(zc.existing_pairing),d.active)throw o.setError(zl.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);o.addTrace(zc.pairing_not_expired)}let f=c||ln(Ge.FIVE_MINUTES),p={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,p),o.addTrace(zc.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Ch.create,p),o.addTrace(zc.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),o.addTrace(zc.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{o.setError(zl.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw o.setError(zl.subscribe_pairing_topic_failure),h}return o.addTrace(zc.subscribe_pairing_topic_success),p},this.activate=async({topic:n})=>{this.isInitialized();let o=ln(Ge.FIVE_MINUTES);this.core.expirer.set(n,o),await this.pairings.update(n,{active:!0,expiry:o})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:o}=n;if(this.pairings.keys.includes(o)){let s=await this.sendRequest(o,"wc_pairingPing",{}),{done:i,resolve:a,reject:c}=yf();this.events.once(ir("pairing_ping",s),({error:u})=>{u?c(u):a()}),await i()}},this.updateExpiry=async({topic:n,expiry:o})=>{this.isInitialized(),await this.pairings.update(n,{expiry:o})},this.updateMetadata=async({topic:n,metadata:o})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:o})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:o}=n;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",Sr("USER_DISCONNECTED")),await this.deletePairing(o))},this.formatUriFromPairing=n=>{this.isInitialized();let{topic:o,relay:s,expiry:i,methods:a}=n,c=this.core.crypto.keychain.get(o);return fk({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:c,relay:s,expiryTimestamp:i,methods:a})},this.sendRequest=async(n,o,s)=>{let i=dr(o,s),a=await this.core.crypto.encode(n,i),c=c4[o].req;return this.core.history.set(n,i),this.core.relayer.publish(n,a,c),i.id},this.sendResult=async(n,o,s)=>{let i=bo(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=c4[c].res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)},this.sendError=async(n,o,s)=>{let i=la(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=c4[c]?c4[c].res:c4.unregistered_method.res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)},this.deletePairing=async(n,o)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Sr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),o?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(o=>ca(o.expiry));await Promise.all(n.map(o=>this.deletePairing(o.topic)))},this.onRelayEventRequest=async n=>{let{topic:o,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(o,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(o,s);default:return await this.onUnknownRpcMethodRequest(o,s)}},this.onRelayEventResponse=async n=>{let{topic:o,payload:s}=n,i=(await this.core.history.get(o,s.id)).request.method;return i==="wc_pairingPing"?this.onPairingPingResponse(o,s):this.onUnknownRpcMethodResponse(i)},this.onPairingPingRequest=async(n,o)=>{let{id:s}=o;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Ch.ping,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}},this.onPairingPingResponse=(n,o)=>{let{id:s}=o;setTimeout(()=>{Jr(o)?this.events.emit(ir("pairing_ping",s),{}):Ir(o)&&this.events.emit(ir("pairing_ping",s),{error:o.error})},500)},this.onPairingDeleteRequest=async(n,o)=>{let{id:s}=o;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Ch.delete,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}},this.onUnknownRpcMethodRequest=async(n,o)=>{let{id:s,method:i}=o;try{if(this.registeredMethods.includes(i))return;let a=Sr("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Sr("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=(n,o)=>{if(!as(n)){let{message:i}=Se("MISSING_OR_INVALID",`pair() params: ${n}`);throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(!$Q(n.uri)){let{message:i}=Se("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw o.setError(zl.malformed_pairing_uri),new Error(i)}let s=dk(n?.uri);if(!s?.relay?.protocol){let{message:i}=Se("MISSING_OR_INVALID","pair() uri#relay-protocol");throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(!s?.symKey){let{message:i}=Se("MISSING_OR_INVALID","pair() uri#symKey");throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(s?.expiryTimestamp&&(0,Ge.toMiliseconds)(s?.expiryTimestamp){if(!as(n)){let{message:s}=Se("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)},this.isValidDisconnect=async n=>{if(!as(n)){let{message:s}=Se("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)},this.isValidPairingTopic=async n=>{if(!gn(n,!1)){let{message:o}=Se("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(o)}if(!this.pairings.keys.includes(n)){let{message:o}=Se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(o)}if(ca(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:o}=Se("EXPIRED",`pairing topic: ${n}`);throw new Error(o)}},this.core=t,this.logger=Cr(r,this.name),this.pairings=new jl(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sr(this.logger)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(yn.message,async t=>{let{topic:r,message:n,transportType:o}=t;if(this.pairings.keys.includes(r)&&o!==Dr.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{let s=await this.core.crypto.decode(r,n);Hc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ua(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(pa.expired,async t=>{let{topic:r}=YC(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ch.expire,{topic:r}))})}},eU=class extends sS{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.records=new Map,this.events=new xf.EventEmitter,this.name=xBe,this.version=vBe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,o,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:o,chainId:s}),this.records.has(o.id))return;let i={id:o.id,topic:n,request:{method:o.method,params:o.params||null},chainId:s,expiry:ln(Ge.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Fc.created,i)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let o=await this.getRecord(n.id);typeof o.response<"u"||(o.response=Ir(n)?{error:n.error}:{result:n.result},this.records.set(o.id,o),this.persist(),this.events.emit(Fc.updated,o))},this.get=async(n,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:o}),await this.getRecord(o)),this.delete=(n,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(s=>{if(s.topic===n){if(typeof o<"u"&&s.id!==o)return;this.records.delete(s.id),this.events.emit(Fc.deleted,s)}}),this.persist()},this.exists=async(n,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===n:!1),this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(n)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();let r=this.records.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fc.sync)}async restore(){try{let t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(Fc.created,t=>{let r=Fc.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Fc.updated,t=>{let r=Fc.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Fc.deleted,t=>{let r=Fc.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.core.heartbeat.on(Vs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(r=>{(0,Ge.toMiliseconds)(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Fc.deleted,r,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},tU=class extends dS{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.expirations=new Map,this.events=new xf.EventEmitter,this.name=EBe,this.version=ABe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let o=this.formatTarget(n);return typeof this.getExpiration(o)<"u"}catch{return!1}},this.set=(n,o)=>{this.isInitialized();let s=this.formatTarget(n),i={target:s,expiry:o};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(pa.created,{target:s,expiration:i})},this.get=n=>{this.isInitialized();let o=this.formatTarget(n);return this.getExpiration(o)},this.del=n=>{if(this.isInitialized(),this.has(n)){let o=this.formatTarget(n),s=this.getExpiration(o);this.expirations.delete(o),this.events.emit(pa.deleted,{target:o,expiration:s})}},this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(t){if(typeof t=="string")return cQ(t);if(typeof t=="number")return lQ(t);let{message:r}=Se("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(pa.sync)}async restore(){try{let t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){let r=this.expirations.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(t,r){let{expiry:n}=r;(0,Ge.toMiliseconds)(n)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(pa.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Vs.pulse,()=>this.checkExpirations()),this.events.on(pa.created,t=>{let r=pa.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(pa.expired,t=>{let r=pa.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(pa.deleted,t=>{let r=pa.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},rU=class extends fS{constructor(t,r,n){super(t,r,n),this.core=t,this.logger=r,this.store=n,this.name=CBe,this.verifyUrlV3=IBe,this.storagePrefix=Vl,this.version=yee,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,Ge.toMiliseconds)(this.publicKey?.expiresAt){if(!L1()||this.isDevEnv)return;let s=window.location.origin,{id:i,decryptedId:a}=o,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${i}&decryptedId=${a}`;try{let u=(0,mee.getDocument)(),d=this.startAbortTimer(Ge.ONE_SECOND*5),f=await new Promise((p,h)=>{let y=()=>{window.removeEventListener("message",x),u.body.removeChild(w),h("attestation aborted")};this.abortController.signal.addEventListener("abort",y);let w=u.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});let x=v=>{if(v.data&&typeof v.data=="string")try{let T=JSON.parse(v.data);if(T.type==="verify_attestation"){if(Hl(T.attestation).payload.id!==i)return;clearInterval(d),u.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",x),p(T.attestation===null?"":T.attestation)}}catch(T){this.logger.warn(T)}};u.body.appendChild(w),window.addEventListener("message",x,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""},this.resolve=async o=>{if(this.isDevEnv)return"";let{attestationId:s,hash:i,encryptedId:a}=o;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Hl(s).payload.id!==a)return;let u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!i)return;let c=this.getVerifyUrl(o?.verifyUrl);return this.fetchAttestation(i,c)},this.fetchAttestation=async(o,s)=>{this.logger.debug(`resolving attestation: ${o} from url: ${s}`);let i=this.startAbortTimer(Ge.ONE_SECOND*5),a=await fetch(`${s}/attestation/${o}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),a.status===200?await a.json():void 0},this.getVerifyUrl=o=>{let s=o||gw;return TBe.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gw}`),s=gw),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let o=this.startAbortTimer(Ge.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(o),await s.json()}catch(o){this.logger.warn(o)}},this.persistPublicKey=async o=>{this.logger.debug(o,"persisting public key to local storage"),await this.store.setItem(this.storeKey,o),this.publicKey=o},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async o=>{let s=await this.getPublicKey();try{if(s)return this.validateAttestation(o,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(o,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{let i=await this.fetchPublicKey();i&&(await this.persistPublicKey(i),s(i))});let o=await this.fetchPromise;return this.fetchPromise=void 0,o},this.validateAttestation=(o,s)=>{let i=UQ(o,s.publicKey),a={hasExpired:(0,Ge.toMiliseconds)(i.exp)this.abortController.abort(),(0,Ge.toMiliseconds)(t))}},nU=class extends pS{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,this.context=_Be,this.registerDeviceToken=async n=>{let{clientId:o,token:s,notificationType:i,enableEncrypted:a=!1}=n,c=`${PBe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:i,token:s,always_raw:a})})},this.logger=Cr(r,this.context)}},oU=class extends hS{constructor(t,r,n=!0){super(t,r,n),this.core=t,this.logger=r,this.context=RBe,this.storagePrefix=Vl,this.storageVersion=NBe,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!j8())try{let o={eventId:ek(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:QB(this.core.relayer.protocol,this.core.relayer.version,qk)}}};await this.sendEvent([o])}catch(o){this.logger.warn(o)}},this.createEvent=o=>{let{event:s="ERROR",type:i="",properties:{topic:a,trace:c}}=o,u=ek(),d=this.core.projectId||"",f=Date.now(),p={eventId:u,timestamp:f,props:{event:s,type:i,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain(),...this.setMethods(u)};return this.telemetryEnabled&&(this.events.set(u,p),this.shouldPersist=!0),p},this.getEvent=o=>{let{eventId:s,topic:i}=o;if(s)return this.events.get(s);let a=Array.from(this.events.values()).find(c=>c.props.properties.topic===i);if(a)return{...a,...this.setMethods(a.eventId)}},this.deleteEvent=o=>{let{eventId:s}=o;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Vs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(o=>{(0,Ge.fromMiliseconds)(Date.now())-(0,Ge.fromMiliseconds)(o.timestamp)>OBe&&(this.events.delete(o.eventId),this.shouldPersist=!0)})})},this.setMethods=o=>({addTrace:s=>this.addTrace(o,s),setError:s=>this.setError(o,s)}),this.addTrace=(o,s)=>{let i=this.events.get(o);i&&(i.props.properties.trace.push(s),this.events.set(o,i),this.shouldPersist=!0)},this.setError=(o,s)=>{let i=this.events.get(o);i&&(i.props.type=s,i.timestamp=Date.now(),this.events.set(o,i),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{let o=await this.core.storage.getItem(this.storageKey)||[];if(!o.length)return;o.forEach(s=>{this.events.set(s.eventId,{...s,...this.setMethods(s.eventId)})})}catch(o){this.logger.warn(o)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;let o=[];for(let[s,i]of this.events)i.props.type&&o.push(i);if(o.length!==0)try{if((await this.sendEvent(o)).ok)for(let s of o)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async o=>{let s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${BBe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${qk}${s}`,{method:"POST",body:JSON.stringify(o)})},this.getAppDomain=()=>JB().url,this.logger=Cr(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},kBe=class xee extends oS{constructor(t){super(t),this.protocol=gee,this.version=yee,this.name=JS,this.events=new xf.EventEmitter,this.initialized=!1,this.on=(i,a)=>this.events.on(i,a),this.once=(i,a)=>this.events.once(i,a),this.off=(i,a)=>this.events.off(i,a),this.removeListener=(i,a)=>this.events.removeListener(i,a),this.dispatchEnvelope=({topic:i,message:a,sessionExists:c})=>{if(!i||!a)return;let u={topic:i,message:a,publishedAt:Date.now(),transportType:Dr.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:c})};let r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(i){console.warn("Failed to copy global core",i)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||wee,this.customStoragePrefix=t?.customStoragePrefix?`:${t.customStoragePrefix}`:"";let n=X2({level:typeof t?.logger=="string"&&t.logger?t.logger:eBe.logger,name:JS}),{logger:o,chunkLoggerController:s}=Fl({opts:n,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=s,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Cr(o,this.name),this.heartbeat=new iw,this.crypto=new Kk(this,this.logger,t?.keychain),this.history=new eU(this,this.logger),this.expirer=new tU(this,this.logger),this.storage=t?.storage?t.storage:new aw({...tBe,...t?.storageOptions}),this.relayer=new Qk({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Xk(this,this.logger),this.verify=new rU(this,this.logger,this.storage),this.echoClient=new nU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new oU(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){let r=new xee(t);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(mBe,n),r}get context(){return sr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(hee,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(hee)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(t){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t.opts?.customStoragePrefix||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},vee=kBe;gh();var It=Ht(jd(),1);$c();var Cee="wc",See=2,Iee="client",gU=`${Cee}@${See}:${Iee}:`,iU={name:Iee,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"};var Eee="WALLETCONNECT_DEEPLINK_CHOICE";var UBe="proposal";var Aee="Proposal expired",DBe="session",ww=It.SEVEN_DAYS,LBe="engine",$o={wc_sessionPropose:{req:{ttl:It.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1104},res:{ttl:It.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1106},res:{ttl:It.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:It.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:It.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:It.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1112},res:{ttl:It.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1114},res:{ttl:It.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:It.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:It.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1119}}},aU={min:It.FIVE_MINUTES,max:It.SEVEN_DAYS},ql={idle:"IDLE",active:"ACTIVE"},MBe={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},HBe="request",$Be=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],FBe="wc";var zBe="auth",VBe="authKeys",jBe="pairingTopics",qBe="requests",XS=`${FBe}@${1.5}:${zBe}:`,Th=`${XS}:PUB_KEY`,cU=class extends gS{constructor(t){super(t),this.name=LBe,this.events=new QS.default,this.initialized=!1,this.requestQueue={state:ql.idle,queue:[]},this.sessionRequestQueue={state:ql.idle,queue:[]},this.emittedSessionRequests=new jC({limit:500}),this.requestQueueDelay=It.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys($o)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,It.toMiliseconds)(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();let n={...r,requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}};await this.isValidConnect(n),n.optionalNamespaces=MQ(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};let{pairingTopic:o,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:a,scopedProperties:c,relays:u,authentication:d,walletPay:f}=n,p=d?.[0]?.ttl||$o.wc_sessionPropose.req.ttl||It.FIVE_MINUTES;this.validateRequestExpiry(p);let h=o,y,w=!1;try{if(h){let M=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=M.active}}catch(M){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),M}if(!h||!w){let{topic:M,uri:N}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});h=M,y=N}if(!h){let{message:M}=Se("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(M)}let x=await this.client.core.crypto.generateKeyPair(),v=ln(p),T={requiredNamespaces:s,optionalNamespaces:i,relays:u??[{protocol:sU}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:v,pairingTopic:h,...a&&{sessionProperties:a},...c&&{scopedProperties:c},id:Tn(),...(d||f)&&{requests:{authentication:d?.map(M=>{let{domain:N,chains:L,nonce:P,uri:R,exp:I,nbf:B,type:C,statement:A,requestId:U,resources:H,signatureTypes:k}=M;return{domain:N,chains:L,nonce:P,type:C??"caip122",aud:R,version:"1",iat:new Date().toISOString(),exp:I,nbf:B,statement:A,requestId:U,resources:H,signatureTypes:k}}),walletPay:f}}},E=ir("session_connect",T.id),{reject:S,resolve:_,done:O}=yf(p,Aee),D=({id:M})=>{if(M===T.id){this.client.events.off("proposal_expire",D);let N=this.pendingSessions.get(T.id);if(N){let{sessionTopic:L,publicKey:P}=N;Promise.all([this.client.core.relayer.unsubscribe(L),this.client.core.crypto.keychain.has(L)?this.client.core.crypto.deleteSymKey(L):Promise.resolve(),this.client.core.crypto.keychain.has(P)?this.client.core.crypto.deleteKeyPair(P):Promise.resolve()]).catch(R=>this.client.logger.warn(R))}this.pendingSessions.delete(T.id),this.events.emit(E,{error:{message:Aee,code:0}})}};return this.client.events.on("proposal_expire",D),this.events.once(E,({error:M,session:N})=>{this.client.events.off("proposal_expire",D),M?S(M):N&&_(N)}),await this.setProposal(T.id,T),await this.sendProposeSession({proposal:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:T.id}}}).catch(M=>{throw this.deleteProposal(T.id),M}),{uri:y,approval:O}},this.pair=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{let n=this.client.core.eventClient.createEvent({properties:{topic:r?.id?.toString(),trace:[Ya.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(D){throw n.setError(Sh.no_internet_connection),D}try{await this.isValidProposalId(r?.id)}catch(D){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),n.setError(Sh.proposal_not_found),D}try{await this.isValidApprove(r)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),n.setError(Sh.session_approve_namespace_validation_failure),D}let{id:o,relayProtocol:s,namespaces:i,sessionProperties:a,scopedProperties:c,sessionConfig:u,proposalRequestsResponses:d}=r,f=this.client.proposal.get(o);this.client.core.eventClient.deleteEvent({eventId:n.eventId});let{pairingTopic:p,proposer:h,requiredNamespaces:y,optionalNamespaces:w}=f,x=this.client.core.eventClient?.getEvent({topic:p});x||(x=this.client.core.eventClient?.createEvent({type:Ya.session_approve_started,properties:{topic:p,trace:[Ya.session_approve_started,Ya.session_namespaces_validation_success]}}));let v=await this.client.core.crypto.generateKeyPair(),T=h.publicKey,E=await this.client.core.crypto.generateSharedKey(v,T),S={relay:{protocol:s??"irn"},namespaces:i,controller:{publicKey:v,metadata:this.client.metadata},expiry:ln(ww),...a&&{sessionProperties:a},...c&&{scopedProperties:c},...u&&{sessionConfig:u},proposalRequestsResponses:d},_=Dr.relay;x.addTrace(Ya.subscribing_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:_,internal:{skipSubscribe:!0}})}catch(D){throw x.setError(Sh.subscribe_session_topic_failure),D}x.addTrace(Ya.subscribe_session_topic_success);let O={...S,topic:E,requiredNamespaces:y,optionalNamespaces:w,pairingTopic:p,acknowledged:!1,self:S.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:v,transportType:Dr.relay,authentication:d?.authentication,walletPayResult:d?.walletPay};await this.client.session.set(E,O),x.addTrace(Ya.store_session);try{await this.sendApproveSession({sessionTopic:E,proposal:f,pairingProposalResponse:{relay:{protocol:s??"irn"},responderPublicKey:v},sessionSettleRequest:S,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:o,...this.getTVFApproveParams(O)}}}),x.addTrace(Ya.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(E,Sr("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(E),D}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:h.metadata}),await this.deleteProposal(o),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(E,ln(ww)),{topic:E,acknowledged:()=>Promise.resolve(this.client.session.get(E))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(i){throw this.client.logger.error("reject() -> isValidReject() failed"),i}let{id:n,reason:o}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(i){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),i}s&&await this.sendError({id:n,topic:s,error:o,rpcOpts:$o.wc_sessionPropose.reject}),await this.deleteProposal(n)},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}let{topic:n,namespaces:o}=r,{done:s,resolve:i,reject:a}=yf(It.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tn(),u=_n().toString(),d=this.client.session.get(n).namespaces;return this.events.once(ir("session_update",c),({error:f})=>{f?a(f):i()}),await this.client.session.update(n,{namespaces:o}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:o},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:d}),a(f)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}let{topic:n}=r,o=Tn(),{done:s,resolve:i,reject:a}=yf(It.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ir("session_extend",o),({error:c})=>{c?a(c):i()}),await this.setExpiry(n,ln(ww)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:o,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}let{chainId:n,request:o,topic:s,expiry:i=$o.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=Tn(),u=_n().toString(),{done:d,resolve:f,reject:p}=yf(i,"Request expired. Please try again.");this.events.once(ir("session_request",c),({error:x,result:v})=>{x?p(x):f(v)});let h="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:{...o,expiryTimestamp:ln(i)},chainId:n},expiry:i,throwOnFailedPublish:!0,appLink:y}).catch(x=>p(x)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),await d();let w={request:{...o,expiryTimestamp:ln(i)},chainId:n};return await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:w,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),x()}),new Promise(async x=>{if(!a.sessionConfig?.disableDeepLink){let v=await dQ(this.client.core.storage,Eee);await uQ({id:c,topic:s,wcDeepLink:v})}x()}),d()]).then(x=>x[2])},this.respond=async r=>{this.isInitialized();let n=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||r?.response?.id?.toString(),trace:[Ya.session_request_response_started]}});try{await this.isValidRespond(r)}catch(u){throw n.addTrace(u?.message),n.setError(Sh.session_request_response_validation_failure),u}n.addTrace(Ya.session_request_response_validation_success);let{topic:o,response:s}=r,{id:i}=s,a=this.client.session.get(o);a.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{n.addTrace(Ya.session_request_response_publish_started),Jr(s)?await this.sendResult({id:i,topic:o,result:s.result,throwOnFailedPublish:!0,appLink:c}):Ir(s)&&await this.sendError({id:i,topic:o,error:s.error,appLink:c}),this.cleanupAfterResponse(r)}catch(u){throw n.addTrace(u?.message),n.setError(Sh.session_request_response_publish_failure),u}},this.ping=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(o){throw this.client.logger.error("ping() -> isValidPing() failed"),o}let{topic:n}=r;if(this.client.session.keys.includes(n)){let o=Tn(),s=_n().toString(),{done:i,resolve:a,reject:c}=yf(It.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ir("session_ping",o),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);let{topic:n,event:o,chainId:s}=r,i=_n().toString(),a=Tn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:o,chainId:s},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:a})},this.disconnect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Sr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:o}=Se("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(o)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>HQ(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(r,n)=>{this.isInitialized(),this.isValidAuthenticate(r);let o=n&&this.client.core.linkModeSupportedApps.includes(n)&&this.client.metadata.redirect?.linkMode,s=o?Dr.link_mode:Dr.relay;s===Dr.relay&&await this.confirmOnlineStateOrThrow();let{chains:i,statement:a="",uri:c,domain:u,nonce:d,type:f,exp:p,nbf:h,methods:y=[],expiry:w}=r,x=[...r.resources||[]],{topic:v,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:s});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:T}}),this.client.auth.authKeys.keys.includes(Th)){let{responseTopic:H,publicKey:k}=this.client.auth.authKeys.get(Th);H&&(await this.client.core.relayer.unsubscribe(H).catch(F=>this.client.logger.warn(F)),await this.client.auth.pairingTopics.delete(H,{message:"replaced",code:0}).catch(F=>this.client.logger.warn(F))),k&&this.client.core.crypto.keychain.has(k)&&await this.client.core.crypto.deleteKeyPair(k)}let E=await this.client.core.crypto.generateKeyPair(),S=rw(E);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:S,publicKey:E}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:v})]),await this.client.core.relayer.subscribe(S,{transportType:s}),this.client.logger.info(`sending request to new pairing topic: ${v}`),y.length>0){let{namespace:H}=Lc(i[0]),k=vQ(H,"request",y);W8(x)&&(k=EQ(k,x.pop())),x.push(k)}let _=w&&w>$o.wc_sessionAuthenticate.req.ttl?w:$o.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:f??"caip122",chains:i,statement:a,aud:c,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:p,nbf:h,resources:x},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:ln(_)},D={eip155:{chains:i,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},M={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:ln($o.wc_sessionPropose.req.ttl),id:Tn()},{done:N,resolve:L,reject:P}=yf(_,"Request expired"),R=Tn(),I=ir("session_connect",M.id),B=ir("session_request",R),C=async({error:H,session:k})=>{this.events.off(B,A),H?P(H):k&&L({session:k})},A=async H=>{if(await this.deletePendingAuthRequest(R,{message:"fulfilled",code:0}),H.error){let X=Sr("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return H.error.code===X.code?void 0:(this.events.off(I,C),P(H.error.message))}await this.deleteProposal(M.id),this.events.off(I,C);let{cacaos:k,responder:F}=H.result,j=[],W=[];for(let X of k){await nk({cacao:X,projectId:this.client.core.projectId})||(this.client.logger.error(X,"Signature verification failed"),P(Sr("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:pe}=X,me=W8(pe.resources),Ne=[QC(pe.iss)],ye=q8(pe.iss);if(me){let Re=sk(me),Et=ik(me);j.push(...Re),Ne.push(...Et)}for(let Re of Ne)W.push(`${Re}:${ye}`)}let ae=await this.client.core.crypto.generateSharedKey(E,F.publicKey),te;j.length>0&&(te={topic:ae,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:F,controller:F.publicKey,expiry:ln(ww),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:hk([...new Set(j)],[...new Set(W)]),transportType:s},await this.client.core.relayer.subscribe(ae,{transportType:s}),await this.client.session.set(ae,te),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:F.metadata}),te=this.client.session.get(ae)),this.client.metadata.redirect?.linkMode&&F.metadata.redirect?.linkMode&&F.metadata.redirect?.universal&&n&&(this.client.core.addLinkModeSupportedApp(F.metadata.redirect.universal),this.client.session.update(ae,{transportType:Dr.link_mode})),L({auths:k,session:te})};this.events.once(I,C),this.events.once(B,A);let U;try{if(o){let H=dr("wc_sessionAuthenticate",O,R);this.client.core.history.set(v,H);let k=await this.client.core.crypto.encode("",H,{type:tw,encoding:wf});U=G8(n,v,k)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:O,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:R}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:M,expiry:$o.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:M.id})])}catch(H){throw this.events.off(I,C),this.events.off(B,A),H}return await this.setProposal(M.id,M),await this.setAuthRequest(R,{request:{...O,verifyContext:{}},pairingTopic:v,transportType:s}),{uri:U??T,response:N}},this.approveSessionAuthenticate=async r=>{let{id:n,auths:o}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ih.authenticated_session_approve_started]}});try{this.isInitialized()}catch(x){throw s.setError(yw.no_internet_connection),x}let i=this.getPendingAuthRequest(n);if(!i)throw s.setError(yw.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);let a=i.transportType||Dr.relay;a===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=i.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=rw(c),f={type:Mc,receiverPublicKey:c,senderPublicKey:u},p=[],h=[];for(let x of o){if(!await nk({cacao:x,projectId:this.client.core.projectId})){s.setError(yw.invalid_cacao);let _=Sr("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:_,encodeOpts:f}),new Error(_.message)}s.addTrace(Ih.cacaos_verified);let{p:v}=x,T=W8(v.resources),E=[QC(v.iss)],S=q8(v.iss);if(T){let _=sk(T),O=ik(T);p.push(..._),E.push(...O)}for(let _ of E)h.push(`${_}:${S}`)}let y=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Ih.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:i.requester.metadata},controller:c,expiry:ln(ww),authentication:o,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:hk([...new Set(p)],[...new Set(h)]),transportType:a},s.addTrace(Ih.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(x){throw s.setError(yw.subscribe_authenticated_session_topic_failure),x}s.addTrace(Ih.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),s.addTrace(Ih.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}s.addTrace(Ih.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:o,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,a)})}catch(x){throw s.setError(yw.authenticated_session_approve_publish_failure),x}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}},this.rejectSessionAuthenticate=async r=>{this.isInitialized();let{id:n,reason:o}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let i=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=rw(i),u={type:Mc,receiverPublicKey:i,senderPublicKey:a};await this.sendError({id:n,topic:c,error:o,encodeOpts:u,rpcOpts:$o.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:o}=r;return ok(n,o)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{let r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(s=>s.peerMetadata?.url&&s.peerMetadata?.url===r.peer.metadata.url&&s.topic&&s.topic!==n.topic);if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:o=!1,emitEvent:s=!0,id:i=0}=r,{self:a}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Sr("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),o||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Eee).catch(c=>this.client.logger.warn(c)),n===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=ql.idle),await Promise.all(this.getPendingSessionRequests().filter(c=>c.topic===n).map(c=>this.deletePendingSessionRequest(c.id,Sr("USER_DISCONNECTED")))),s&&this.client.events.emit("session_delete",{id:i,topic:n})},this.deleteProposal=async(r,n)=>{if(n)try{let o=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:o.pairingTopic})?.setError(Sh.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Sr("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),o&&(this.sessionRequestQueue.state=ql.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,n,o=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))},this.setProposal=async(r,n)=>{this.client.core.expirer.set(r,ln($o.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)},this.setAuthRequest=async(r,n)=>{let{request:o,pairingTopic:s,transportType:i=Dr.relay}=n;this.client.core.expirer.set(r,o.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:o.authPayload,requester:o.requester,expiryTimestamp:o.expiryTimestamp,id:r,pairingTopic:s,verifyContext:o.verifyContext,transportType:i})},this.setPendingSessionRequest=async r=>{let{id:n,topic:o,params:s,verifyContext:i}=r,a=s.request.expiryTimestamp||ln($o.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:o,params:s,verifyContext:i})},this.sendRequest=async r=>{let{topic:n,method:o,params:s,expiry:i,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:d,tvf:f,publishOpts:p={}}=r,h=dr(o,s,c),y,w=!!d;try{let T=w?wf:to;y=await this.client.core.crypto.encode(n,h,{encoding:T})}catch(T){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),T}let x;if($Be.includes(o)){let T=xi(JSON.stringify(h)),E=xi(y);x=await this.client.core.verify.register({id:E,decryptedId:T})}let v={...$o[o].req,...p};if(v.attestation=x,i&&(v.ttl=i),a&&(v.id=a),this.client.core.history.set(n,h),w){let T=G8(d,n,y);await global.Linking.openURL(T,this.client.name)}else v.tvf={...f,correlationId:h.id},u?(v.internal={...v.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(n,y,v)):this.client.core.relayer.publish(n,y,v).catch(T=>this.client.logger.error(T));return h.id},this.sendProposeSession=async r=>{let{proposal:n,publishOpts:o}=r,s=dr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);let i=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:to}),a=xi(JSON.stringify(s)),c=xi(i),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:i},opts:{...o,publishMethod:"wc_proposeSession",attestation:u}})},this.sendApproveSession=async r=>{let{sessionTopic:n,pairingProposalResponse:o,proposal:s,sessionSettleRequest:i,publishOpts:a}=r,c=bo(s.id,o),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:to}),d=dr("wc_sessionSettle",i,a?.id),f=await this.client.core.crypto.encode(n,d,{encoding:to});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:{...a,publishMethod:"wc_approveSession"}})},this.sendResult=async r=>{let{id:n,topic:o,result:s,throwOnFailedPublish:i,encodeOpts:a,appLink:c}=r,u=bo(n,s),d,f=c&&typeof global?.Linking<"u";try{let y=f?wf:to;d=await this.client.core.crypto.encode(o,u,{...a||{},encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${o} failed`),y}let p,h;try{p=await this.client.core.history.get(o,n);let y=p.request;try{h=this.getTVFParams(n,y.params,s)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${o}, ${n}) failed`),y}if(f){let y=G8(c,o,d);await global.Linking.openURL(y,this.client.name)}else{let y=p.request.method,w=$o[y].res;w.tvf={...h,correlationId:n},i?(w.internal={...w.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(o,d,w)):this.client.core.relayer.publish(o,d,w).catch(x=>this.client.logger.error(x))}await this.client.core.history.resolve(u)},this.sendError=async r=>{let{id:n,topic:o,error:s,encodeOpts:i,rpcOpts:a,appLink:c}=r,u=la(n,s),d,f=c&&typeof global?.Linking<"u";try{let h=f?wf:to;d=await this.client.core.crypto.encode(o,u,{...i||{},encoding:h})}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${o} failed`),h}let p;try{p=await this.client.core.history.get(o,n)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${o}, ${n}) failed`),h}if(f){let h=G8(c,o,d);await global.Linking.openURL(h,this.client.name)}else{let h=p.request.method,y=a||$o[h].res;this.client.core.relayer.publish(o,d,y)}await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(o=>{let s=!1;ca(o.expiry)&&(s=!0),this.client.core.crypto.keychain.has(o.topic)||(s=!0),s&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{ca(o.expiryTimestamp)&&n.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession({topic:o})),...n.map(o=>this.deleteProposal(o))])},this.onProviderMessageEvent=async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ql.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=ql.active;let r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=ql.idle},this.processRequest=async r=>{let{topic:n,payload:o,attestation:s,transportType:i,encryptedId:a}=r,c=o.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:o,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,o);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,o);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,o);case"wc_sessionPing":return await this.onSessionPingRequest(n,o);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,o);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(n,o);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});default:return this.client.logger.info(`Unsupported request method ${c}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:o,transportType:s}=r,i=(await this.client.core.history.get(n,o.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(n,o,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,o);case"wc_sessionExtend":return this.onSessionExtendResponse(n,o);case"wc_sessionPing":return this.onSessionPingResponse(n,o);case"wc_sessionRequest":return this.onSessionRequestResponse(n,o);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,o);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:o}=Se("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:o}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(o)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i}=r,{params:a,id:c}=o;try{let u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(zl.proposal_listener_not_found)),this.isValidConnect({...o.params});let d=a.expiryTimestamp||ln($o.wc_sessionPropose.req.ttl),f={id:c,pairingTopic:n,expiryTimestamp:d,attestation:s,encryptedId:i,...a};await this.setProposal(c,f);let p=await this.getVerifyContext({attestationId:s,hash:xi(JSON.stringify(o)),encryptedId:i,metadata:f.proposer.metadata});u?.addTrace(zc.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:p})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:$o.wc_sessionPropose.autoReject}),this.client.logger.error(u)}},this.onSessionProposeResponse=async(r,n,o)=>{let{id:s}=n;if(Jr(n)){let{result:i}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});let a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});let c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});let u=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let d=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:d,pairingTopic:r,proposalId:s,publicKey:c});let f=await this.client.core.relayer.subscribe(d,{transportType:o});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(Ir(n)){await this.deleteProposal(s);let i=ir("session_connect",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners, 954`);this.events.emit(i,{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:o,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:i,controller:a,expiry:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=n.params,y=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!y)return this.client.logger.error(`Pending session not found for topic ${r}`);let w=this.client.proposal.get(y.proposalId),x={topic:r,relay:i,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata},...d&&{sessionProperties:d},...f&&{scopedProperties:f},...p&&{sessionConfig:p},transportType:Dr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay};await this.client.session.set(x.topic,x),await this.setExpiry(x.topic,x.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:x.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(x),await this.sendResult({id:n.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:x}),this.events.emit(ir("session_connect",y.proposalId),{session:x})}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}},this.onSessionSettleResponse=async(r,n)=>{let{id:o}=n;Jr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ir("session_approve",o),{})):Ir(n)&&(await this.deleteSession({topic:r,emitEvent:!1}),this.events.emit(ir("session_approve",o),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:o,id:s}=n;try{let i=`${r}_session_update`,a=wh.get(i);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Sr("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate({topic:r,...o});try{wh.set(i,s),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw wh.delete(i),c}this.client.events.emit("session_update",{id:s,topic:r,params:o})}catch(i){await this.sendError({id:s,topic:r,error:i}),this.client.logger.error(i)}},this.isRequestOutOfSync=(r,n)=>n.toString().slice(0,-3){let{id:o}=n,s=ir("session_update",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_update",o),{}):Ir(n)&&this.events.emit(ir("session_update",o),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:o}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ln(ww)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:o}=n,s=ir("session_extend",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_extend",o),{}):Ir(n)&&this.events.emit(ir("session_extend",o),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:o}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:o}=n,s=ir("session_ping",o);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Jr(n)?this.events.emit(ir("session_ping",o),{}):Ir(n)&&this.events.emit(ir("session_ping",o),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:o}=n;try{await this.isValidDisconnect({topic:r,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Sr("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:o})}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i,transportType:a}=r,{id:c,params:u}=o;try{await this.isValidRequest({topic:n,...u});let d=this.client.session.get(n),f=await this.getVerifyContext({attestationId:s,hash:xi(JSON.stringify(dr("wc_sessionRequest",u,c))),encryptedId:i,metadata:d.peer.metadata,transportType:a}),p={id:c,topic:n,params:u,verifyContext:f};await this.setPendingSessionRequest(p),a===Dr.link_mode&&d.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(d.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(p):(this.addSessionRequestToSessionRequestQueue(p),this.processSessionRequestQueue())}catch(d){await this.sendError({id:c,topic:n,error:d}),this.client.logger.error(d)}},this.onSessionRequestResponse=(r,n)=>{let{id:o}=n,s=ir("session_request",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(ir("session_request",o),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:o,params:s}=n;try{let i=`${r}_session_event_${s.event.name}`,a=wh.get(i);if(a&&this.isRequestOutOfSync(a,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit({topic:r,...s}),this.client.events.emit("session_event",{id:o,topic:r,params:s}),wh.set(i,o)}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:o}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Jr(n)?this.events.emit(ir("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(ir("session_request",o),{error:n.error})},this.onSessionAuthenticateRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i,transportType:a}=r;try{let{requester:c,authPayload:u,expiryTimestamp:d}=o.params,f=await this.getVerifyContext({attestationId:s,hash:xi(JSON.stringify(o)),encryptedId:i,metadata:c.metadata,transportType:a}),p={requester:c,pairingTopic:n,id:o.id,authPayload:u,verifyContext:f,expiryTimestamp:d};await this.setAuthRequest(o.id,{request:p,pairingTopic:n,transportType:a}),a===Dr.link_mode&&c.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:o.params,id:o.id,verifyContext:f})}catch(c){this.client.logger.error(c);let u=o.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(o.params.requester.metadata,a),p={type:Mc,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:o.id,topic:n,error:c,encodeOpts:p,rpcOpts:$o.wc_sessionAuthenticate.autoReject,appLink:f})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ql.idle,this.processSessionRequestQueue()},(0,It.toMiliseconds)(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let o=this.client.core.history.pending;o.length>0&&o.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ir("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ql.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}},this.emitSessionRequest=r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=ql.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{let r=this.client.core.relayer.subscriber.topics;if(r.length===0)return;let n=new Set(this.client.session.keys),o=new Set(this.client.core.pairing.pairings.keys),s=new Set([...this.pendingSessions.values()].map(a=>a.sessionTopic)),i;if(this.client.auth.authKeys.keys.includes(Th)){let{responseTopic:a}=this.client.auth.authKeys.get(Th);i=a}for(let a of r)if(!n.has(a)&&!o.has(a)&&!s.has(a)&&a!==i){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${a}`);try{await this.client.core.relayer.subscriber.unsubscribe(a)}catch(c){this.client.logger.warn(c,`Failed to clean up orphaned subscription: ${a}`)}}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:dr("wc_sessionPropose",{...n,requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties},n.id),attestation:n.attestation,encryptedId:n.encryptedId})},this.isValidConnect=async r=>{if(!as(r)){let{message:u}=Se("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:s,sessionProperties:i,scopedProperties:a,relays:c}=r;if(In(n)||await this.isValidPairingTopic(n),!WQ(c,!0)){let{message:u}=Se("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(o&&!In(o)&&Ka(o)!==0){let u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(o,"requiredNamespaces")}if(s&&!In(s)&&Ka(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),i&&!In(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!In(a)){this.validateSessionProps(a,"scopedProperties");let u=Object.keys(o||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(d=>u.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}},this.validateNamespaces=(r,n)=>{let o=qQ(r,"connect()",n);if(o)throw new Error(o.message)},this.isValidApprove=async r=>{if(!as(r))throw new Error(Se("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:o,relayProtocol:s,sessionProperties:i,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let c=this.client.proposal.get(n),u=eS(o,"approve()");if(u)throw new Error(u.message);let d=wk(c.requiredNamespaces,o,"approve()");if(d)throw new Error(d.message);if(!gn(s,!0)){let{message:f}=Se("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(i&&!In(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!In(a)){this.validateSessionProps(a,"scopedProperties");let f=new Set(Object.keys(o));if(!Object.keys(a).every(p=>f.has(p.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}},this.isValidReject=async r=>{if(!as(r)){let{message:s}=Se("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:o}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!ZQ(o)){let{message:s}=Se("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!as(r)){let{message:u}=Se("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}let{relay:n,controller:o,namespaces:s,expiry:i}=r;if(!gk(n)){let{message:u}=Se("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}let a=VQ(o,"onSessionSettleRequest()");if(a)throw new Error(a.message);let c=eS(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ca(i)){let{message:u}=Se("EXPIRED","onSessionSettleRequest()");throw new Error(u)}},this.isValidUpdate=async r=>{if(!as(r)){let{message:c}=Se("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}let{topic:n,namespaces:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),i=eS(o,"update()");if(i)throw new Error(i.message);let a=wk(s.requiredNamespaces,o,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!as(r)){let{message:c}=Se("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}let{topic:n,request:o,chainId:s,expiry:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!yk(a,s)){let{message:c}=Se("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!GQ(o)){let{message:c}=Se("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(c)}if(!QQ(a,s,o.method)){let{message:c}=Se("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(c)}this.validateRequestExpiry(i)},this.isValidRespond=async r=>{if(!as(r)){let{message:i}=Se("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(i)}let{topic:n,response:o}=r;try{await this.isValidSessionTopic(n)}catch(i){throw r?.response?.id&&this.cleanupAfterResponse(r),i}if(!YQ(o)){let{message:i}=Se("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(i)}let s=this.client.pendingRequest.get(o.id);if(s.topic!==n){let{message:i}=Se("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${o.id}, expected topic: ${s.topic}, received topic: ${n}`);throw new Error(i)}},this.isValidPing=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!as(r)){let{message:a}=Se("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:o,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:i}=this.client.session.get(n);if(!yk(i,s)){let{message:a}=Se("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!JQ(o)){let{message:a}=Se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}if(!XQ(i,s,o.name)){let{message:a}=Se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:o,domain:s,nonce:i}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!gn(o,!1))throw new Error("uri is required parameter");if(!gn(s,!1))throw new Error("domain is required parameter");if(!gn(i,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Lc(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:a}=Lc(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{let{attestationId:n,hash:o,encryptedId:s,metadata:i,transportType:a}=r,c={verified:{verifyUrl:i.verifyUrl||gw,validation:"UNKNOWN",origin:i.url||""}};try{if(a===Dr.link_mode){let d=this.getAppLinkIfEnabled(i,a);return c.verified.validation=d&&new URL(d).origin===new URL(i.url).origin?"VALID":"INVALID",c}let u=await this.client.core.verify.resolve({attestationId:n,hash:o,encryptedId:s,verifyUrl:i.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c},this.validateSessionProps=(r,n)=>{Object.values(r).forEach((o,s)=>{if(o==null){let{message:i}=Se("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${o} for key ${Object.keys(r)[s]}`);throw new Error(i)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let o=0,s=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(o++>=s)break;this.recentlyDeletedMap.delete(i)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:o}=Se("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(o)}},this.isLinkModeEnabled=(r,n)=>!r||n!==Dr.link_mode?!1:this.client.metadata?.redirect?.linkMode===!0&&this.client.metadata?.redirect?.universal!==void 0&&this.client.metadata?.redirect?.universal!==""&&r?.redirect?.universal!==void 0&&r?.redirect?.universal!==""&&r?.redirect?.linkMode===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof global?.Linking<"u",this.getAppLinkIfEnabled=(r,n)=>this.isLinkModeEnabled(r,n)?r?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;let n=XB(r,"topic")||"",o=decodeURIComponent(XB(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:Dr.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:o,sessionExists:s})},this.registerLinkModeListeners=async()=>{if(j8()||gf()&&this.client.metadata.redirect?.linkMode){let r=global?.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);let n=await r.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}},this.getTVFApproveParams=r=>{try{let n=pk(r.namespaces),o=DQ(r.namespaces),s=LQ(r.namespaces),i=r.sessionProperties,a=r.scopedProperties;return{approvedChains:n,approvedMethods:o,approvedEvents:s,sessionProperties:i,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}},this.getTVFParams=(r,n,o)=>{if(!n.request?.method)return{};let s={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{let i=this.extractTxHashesFromResult(n.request,o);s.txHashes=i,s.contractAddresses=this.isValidContractData(n.request.params)?[n.request.params?.[0]?.to]:[]}catch(i){this.client.logger.warn(i,"Error getting TVF params")}return s},this.isValidContractData=r=>{if(!r)return!1;try{let n=r?.data||r?.[0]?.data;if(!n.startsWith("0x"))return!1;let o=n.slice(2);return/^[0-9a-fA-F]*$/.test(o)?o.length%2===0:!1}catch{}return!1},this.extractTxHashesFromResult=(r,n)=>{try{if(!n)return[];let o=r.method,s=MBe[o];if(o==="sui_signTransaction")return[gQ(n.transactionBytes)];if(o==="near_signTransaction")return[tk(n)];if(o==="near_signTransactions")return n.map(a=>tk(a));if(o==="xrpl_signTransactionFor"||o==="xrpl_signTransaction")return[n.tx_json?.hash];if(o==="polkadot_signTransaction")return[nX({transaction:r.params.transactionPayload,signature:n.signature})];if(o==="algo_signTxn")return zs(n)?n.map(a=>rk(a)):[rk(n)];if(o==="cosmos_signDirect")return[yQ(n)];if(o==="wallet_sendCalls")return wQ(n);if(typeof n=="string")return[n];let i=n[s.key];if(zs(i))return o==="solana_signAllTransactions"?i.map(a=>mQ(a)):i;if(typeof i=="string")return[i]}catch(o){this.client.logger.warn(o,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{let t=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(t);for(let[n,o]of Object.entries(r))for(let s of o)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(yn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){let{topic:r,message:n,attestation:o,transportType:s}=t,{publicKey:i}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{publicKey:void 0};try{let a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i,encoding:s===Dr.link_mode?wf:to});Hc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:o,transportType:s,encryptedId:xi(n)})):ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(pa.expired,async t=>{let{topic:r,id:n}=YC(t.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Se("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Se("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(t){this.client.logger.warn(t)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Ch.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(Ch.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!gn(t,!1)){let{message:r}=Se("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.core.pairing.pairings.get(t).expiry)){let{message:r}=Se("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!gn(t,!1)){let{message:r}=Se("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});let{message:r}=Se("EXPIRED",`session topic: ${t}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(t)){let{message:r}=Se("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(gn(t,!1)){let{message:r}=Se("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{let{message:r}=Se("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!KQ(t)){let{message:r}=Se("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);let{message:r}=Se("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}validateRequestExpiry(t){if(t&&!eX(t,aU)){let{message:r}=Se("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${aU.min} and ${aU.max}`);throw new Error(r)}}},lU=class extends jl{constructor(t,r){super(t,r,UBe,gU),this.core=t,this.logger=r}},uU=class extends jl{constructor(t,r){super(t,r,DBe,gU),this.core=t,this.logger=r}},dU=class extends jl{constructor(t,r){super(t,r,HBe,gU,n=>n.id),this.core=t,this.logger=r}},fU=class extends jl{constructor(t,r){super(t,r,VBe,XS,()=>Th),this.core=t,this.logger=r}},pU=class extends jl{constructor(t,r){super(t,r,jBe,XS),this.core=t,this.logger=r}},hU=class extends jl{constructor(t,r){super(t,r,qBe,XS,n=>n.id),this.core=t,this.logger=r}},mU=class{constructor(t,r){this.core=t,this.logger=r,this.authKeys=new fU(this.core,this.logger),this.pairingTopics=new pU(this.core,this.logger),this.requests=new hU(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},WBe=class Tee extends mS{constructor(t){super(t),this.protocol=Cee,this.version=See,this.name=iU.name,this.events=new QS.EventEmitter,this.on=(n,o)=>this.events.on(n,o),this.once=(n,o)=>this.events.once(n,o),this.off=(n,o)=>this.events.off(n,o),this.removeListener=(n,o)=>this.events.removeListener(n,o),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(o){throw this.logger.error(o.message),o}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(o){throw this.logger.error(o.message),o}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(o){throw this.logger.error(o.message),o}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(o){throw this.logger.error(o.message),o}},this.update=async n=>{try{return await this.engine.update(n)}catch(o){throw this.logger.error(o.message),o}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(o){throw this.logger.error(o.message),o}},this.request=async n=>{try{return await this.engine.request(n)}catch(o){throw this.logger.error(o.message),o}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(o){throw this.logger.error(o.message),o}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(o){throw this.logger.error(o.message),o}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(o){throw this.logger.error(o.message),o}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(o){throw this.logger.error(o.message),o}},this.find=n=>{try{return this.engine.find(n)}catch(o){throw this.logger.error(o.message),o}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async(n,o)=>{try{return await this.engine.authenticate(n,o)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(o){throw this.logger.error(o.message),o}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}},this.name=t?.name||iU.name,this.metadata=sQ(t?.metadata),this.signConfig=t?.signConfig;let r=sw({logger:t?.logger||iU.logger,name:this.name});this.logger=r,this.core=t?.core||new vee(t),this.session=new uU(this.core,this.logger),this.proposal=new lU(this.core,this.logger),this.pendingRequest=new dU(this.core,this.logger),this.engine=new cU(this),this.auth=new mU(this.core,this.logger)}static async init(t){let r=new Tee(t);return await r.initialize(),r}get context(){return sr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}};var _ee=WBe;$c();cw();rI();var qee=Ht(ks(),1),Mee="error",eke="wss://relay.walletconnect.org",tke="wc",Wee="universal_provider",nI=`${tke}@2:${Wee}:`,Kee="https://rpc.walletconnect.org/v1/",Zee="generic",rke=`${Kee}bundler`,xw="call_status",nke=86400,SU={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Gee(e,t,r){let n=Lc(e);return t.rpcMap?.[n.reference]||`${Kee}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function oke(e){return e.includes(":")?e.split(":")[1]:e}function Yee(e){return e.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function ske(e,t){let r=Object.keys(t.namespaces).filter(o=>o.includes(e));if(!r.length)return[];let n=[];return r.forEach(o=>{let s=t.namespaces[o].accounts;n.push(...s)}),n}function Hee(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r?.chains?.length&&r?.chains?.length>0))}function oI(e={},t={}){let r=Hee($ee(e)),n=Hee($ee(t));return jk(r,n)}function $ee(e){let t={};if(!Ka(e))return t;for(let[r,n]of Object.entries(e)){let o=Y8(r)?[r]:n.chains,s=n.methods||[],i=n.events||[],a=n.rpcMap||{},c=H1(r);t[c]={...t[c],...n,chains:Uc(o,t[c]?.chains),methods:Uc(s,t[c]?.methods),events:Uc(i,t[c]?.events)},(Ka(a)||Ka(t[c]?.rpcMap||{}))&&(t[c].rpcMap={...a,...t[c]?.rpcMap})}return t}function Fee(e){return e.includes(":")?e.split(":")[2]:e}function zee(e){let t={};for(let[r,n]of Object.entries(e)){let o=n.methods||[],s=n.events||[],i=n.accounts||[],a=Y8(r)?[r]:n.chains?n.chains:Yee(n.accounts);t[r]={chains:a,methods:o,events:s,accounts:i}}return t}function wU(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function ike(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}var Jee={},vw=e=>Jee[e],bU=(e,t)=>{Jee[e]=t},Vee="eip155",ake=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],cke=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,xU=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,jee=e=>Object.keys(e).filter(t=>ake.includes(t)).reduce((t,r)=>(t[r]=lke(e[r]),t),{}),lke=e=>typeof e=="string"&&ike(e)?JSON.parse(e):e,uke=(e,t,r)=>{let{sessionProperties:n={},scopedProperties:o={}}=e,s={};if(!Ka(o)&&!Ka(n))return;let i=jee(n);for(let a of r){let c=cke(a);if(!c)continue;s[xU(c)]=i;let u=o?.[`${Vee}:${c}`];if(u){let d=u?.[`${Vee}:${c}:${t}`];s[xU(c)]={...s[xU(c)],...jee(d||u)}}}for(let[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0},vU,EU=class e{constructor(t){this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,r){return await this.storage.setItem(t,r)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return vU||(vU=new e(t)),vU}};async function dke(e,t){let r=Lc(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,o=await Promise.allSettled(n.map(f=>fke(r.reference,f,t))),s=o.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);o.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));let i=!s.length||s.some(f=>!f),a=s.every(f=>f?.status==="0x1"),c=s.every(f=>f?.status==="0x0"),u=s.some(f=>f?.status==="0x0"),d;return i?d=100:a?d=200:c?d=500:u&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function fke(e,t,r){return await r(parseInt(e)).request(dr("eth_getTransactionReceipt",[t]))}async function pke({sendCalls:e,storage:t}){let r=await t.getItem(xw);await t.setItem(xw,{...r,[e.result.id]:{request:e.request,result:e.result,expiry:ln(nke)}})}async function hke({resultId:e,storage:t}){let r=await t.getItem(xw);if(r){delete r[e],await t.setItem(xw,r);for(let n in r)ca(r[n].expiry)&&delete r[n];await t.setItem(xw,r)}}async function mke({resultId:e,storage:t}){let r=(await t.getItem(xw))?.[e];if(r&&!ca(r.expiry))return r;await hke({resultId:e,storage:t})}var AU=class{constructor(t){this.name="eip155",this.namespace=t.namespace,this.events=vw("events"),this.client=vw("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=EU.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r);let n=this.chainId;this.chainId=parseInt(t),this.events.emit(SU.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){let n=r||Gee(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,vw("disableProviderPing")))}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProviders(){let t={};return this.namespace.chains.forEach(r=>{let n=parseInt(oke(r));t[n]=this.createHttpProvider(n,this.namespace.rpcMap?.[r])}),t}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(t){let r=t||this.chainId;return this.httpProviders[r]||(this.httpProviders={...this.httpProviders,[r]:this.createHttpProvider(r)},this.httpProviders[r])}async handleSwitchChain(t){let r=t.request.params?t.request.params[0]?.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;let n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:r}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){let r=t.request?.params?.[0],n=t.request?.params?.[1]||[];if(!r)throw new Error("Missing address parameter in `wallet_getCapabilities` request");let o=this.client.session.get(t.topic),s=o?.sessionProperties?.capabilities||{},i=n.length>0?n.join(","):`0x${this.chainId.toString(16)}`,a=`${r}${i}`,c=s?.[a];if(c)return c;let u;try{u=uke(o,r,n)}catch(f){console.warn("Failed to extract capabilities from session",f)}if(u)return u;let d=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:{...o.sessionProperties||{},capabilities:{...s||{},[a]:d}}})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(t){let r=this.client.session.get(t.topic),n=r.sessionProperties?.bundler_name;if(n){let i=this.getBundlerUrl(t.chainId,n);try{return await this.getUserOperationReceipt(i,t)}catch(a){console.warn("Failed to fetch call status from bundler",a,i)}}let o=r.sessionProperties?.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,t)}catch(i){console.warn("Failed to fetch call status from custom bundler",i,o)}let s=await mke({resultId:t.request.params?.[0],storage:this.storage});if(s)try{return await dke(s,this.getHttpProvider.bind(this))}catch(i){console.warn("Failed to fetch call status from stored send calls",i,s)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,r){let n=new URL(t),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dr("eth_getUserOperationReceipt",[r.request.params?.[0]]))});if(!o.ok)throw new Error(`Failed to fetch user operation receipt - ${o.status}`);return await o.json()}getBundlerUrl(t,r){return`${rke}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${r}`}async sendCalls(t){let r=await this.client.request(t),n=t.request.params?.[0],o=r?.id,s=r?.capabilities||{},i=s?.caip345?.caip2,a=s?.caip345?.transactionHashes;return!o||!i||!a?.length||await pke({sendCalls:{request:n,result:r},storage:this.storage}),r}},CU=class{constructor(t){this.name=Zee,this.namespace=t.namespace,this.events=vw("events"),this.client=vw("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r);let n=this.chainId;this.chainId=t,this.events.emit(SU.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return Lc(t).namespace}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){let t={};return this.namespace?.accounts?.forEach(r=>{let n=Lc(r),o=this.namespace?.rpcMap?.[`${n.namespace}:${n.reference}`];t[n.reference]=this.createHttpProvider(r,o)}),t}getHttpProvider(t){let r=Lc(t).reference,n=this.httpProviders[r];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return n}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProvider(t,r){let n=r||Gee(t,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,vw("disableProviderPing")))}},gke=class Qee{constructor(t){this.events=new qee.default,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=t,this.logger=sw({logger:t.logger??Mee,name:this.providerOpts.name??Wee}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){let r=new Qee(t);return await r.initialize(),r}async request(t,r,n){let[o,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(o).request({request:{...t},chainId:`${o}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(t,r,n,o){let s=new Date().getTime();this.request(t,n,o).then(i=>r(null,bo(s,i))).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Sr("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();let{uri:n,response:o}=await this.client.authenticate(t,r);n&&(this.uri=n,this.events.emit("display_uri",n));let s=await o();if(this.session=s.session,this.session){let i=zee(this.session.namespaces);this.namespaces=oI(this.namespaces,i),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){let{uri:r,approval:n}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});r&&(this.uri=r,this.events.emit("display_uri",r));let o=await n();this.session=o;let s=zee(o.namespaces);return this.namespaces=oI(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;let[n,o]=this.validateChain(t),s=this.getProvider(n);s?s.setDefaultChain(o,r):this.session&&this.logger.warn(`Provider for namespace '${n}' not found in setDefaultChain`)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");let r=this.client.pairing.getAll();if(!zs(r))return;for(let n of r)t.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){if(this.client=this.providerOpts.client||await _ee.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Mee,relayUrl:this.providerOpts.relayUrl||eke,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(t){throw this.logger.error(t,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{let t=this.client.session.getAll();this.session=t[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");let t=[...new Set(Object.keys(this.session.namespaces).map(r=>H1(r)))];bU("client",this.client),bU("events",this.events),bU("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;let n=ske(r,this.session);if(n?.length===0)return;let o=Yee(n),s={...oI(this.namespaces,this.optionalNamespaces)[r],accounts:n,chains:o};r==="eip155"?this.rpcProviders[r]=new AU({namespace:s}):this.rpcProviders[r]=new CU({namespace:s})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{let{topic:r}=t;r===this.session?.topic&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{let{params:r,topic:n}=t;if(n!==this.session?.topic)return;let{event:o}=r;if(o.name==="accountsChanged"){let s=o.data;s&&zs(s)&&this.events.emit("accountsChanged",s.map(Fee))}else if(o.name==="chainChanged"){let s=r.chainId,i=r.event.data,a=H1(s),c=wU(s)!==wU(i)?`${a}:${wU(i)}`:s;this.onChainChanged({currentCaipChainId:c})}else this.events.emit(o.name,o.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{if(t!==this.session?.topic)return;let{namespaces:n}=r,o=this.client?.session.get(t);this.session={...o,namespaces:n},this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{t.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",{...Sr("USER_DISCONNECTED"),data:t.topic}))}),this.on(SU.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged({...t,internal:!0})})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[Zee]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{this.getProvider(t).updateNamespace(this.session?.namespaces[t])})}setNamespaces(t){let{namespaces:r={},optionalNamespaces:n={},sessionProperties:o,scopedProperties:s}=t;this.optionalNamespaces=oI(r,n),this.sessionProperties=o,this.scopedProperties=s}validateChain(t){let[r,n]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(i=>H1(i)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];let o=H1(Object.keys(this.namespaces)[0]),s=this.rpcProviders[o].getDefaultChain();return[o,s]}async requestAccounts(){let[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:r,internal:n=!1}){if(!this.namespaces)return;let[o,s]=this.validateChain(t);if(s){if(this.updateNamespaceChain(o,s),n)this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:o,currentCaipChainId:t,previousCaipChainId:r});else{let i=this.getProvider(o);i?i.setDefaultChain(s):this.session&&this.logger.warn(`Provider for namespace '${o}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:r,previousCaipChainId:n}){try{if(n===r)return;let o=this.session?.namespaces[t]?.accounts;if(!o)return;let s=o.filter(i=>i.includes(`${r}:`)).map(Fee);if(!zs(s))return;this.events.emit("accountsChanged",s)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,r){if(!this.namespaces)return;let n=this.namespaces[t]?t:`${t}:${r}`,o={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=o}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,r){let n=this.session?.topic||"";await this.client.core.storage.setItem(`${nI}/${t}${n}`,r)}async getFromStore(t){let r=this.session?.topic||"";return await this.client.core.storage.getItem(`${nI}/${t}${r}`)}async deleteFromStore(t){let r=this.session?.topic||"";await this.client.core.storage.removeItem(`${nI}/${t}${r}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;let t=await this.client.core.storage.getKeys();for(let r of t)r.startsWith(nI)&&await this.client.core.storage.removeItem(r)}catch(t){this.logger.warn(t,"Failed to cleanup storage")}}},Xee=gke;var qtt="wc",Wtt="ethereum_provider",Ktt=`${qtt}@2:${Wtt}:`,Ztt="https://rpc.walletconnect.org/v1/",Oq=["eth_sendTransaction","personal_sign"],Gtt=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Bq=["chainChanged","accountsChanged"],Ytt=["chainChanged","accountsChanged","message","disconnect","connect"],Jtt=async()=>{let{createAppKit:e}=await Promise.resolve().then(()=>(gAe(),mAe));return e};function PN(e){return Number(e[0].split(":")[1])}function _N(e){return`0x${e.toString(16)}`}function Qtt(e){let{chains:t,optionalChains:r,methods:n,optionalMethods:o,events:s,optionalEvents:i,rpcMap:a}=e;if(!zs(t))throw new Error("Invalid chains");let c={chains:t,methods:n||Oq,events:s||Bq,rpcMap:{...t.length?{[PN(t)]:a[PN(t)]}:{}}},u=s?.filter(h=>!Bq.includes(h)),d=n?.filter(h=>!Oq.includes(h));if(!r&&!i&&!o&&!u?.length&&!d?.length)return{required:t.length?c:void 0};let f=u?.length&&d?.length||!r,p={chains:[...new Set(f?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(o?.length?o:Gtt))],events:[...new Set(c.events.concat(i?.length?i:Ytt))],rpcMap:a};return{required:t.length?c:void 0,optional:r.length?p:void 0}}var Xtt=class wAe{constructor(){this.events=new yAe.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=Ktt,this.on=(t,r)=>(this.events.on(t,r),this),this.once=(t,r)=>(this.events.once(t,r),this),this.removeListener=(t,r)=>(this.events.removeListener(t,r),this),this.off=(t,r)=>(this.events.off(t,r),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){let r=new wAe;return await r.initialize(t),r}async request(t,r){return await this.signer.request(t,this.formatChainId(this.chainId),r)}sendAsync(t,r,n){this.signer.sendAsync(t,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);let{required:r,optional:n}=Qtt(this.rpc);try{let o=await new Promise(async(i,a)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))}));let c=t?.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect({namespaces:{...r&&{[this.namespace]:r}},...n&&{optionalNamespaces:{[this.namespace]:n}},pairingTopic:t?.pairingTopic,scopedProperties:c}).then(u=>{i(u)}).catch(u=>{this.modal?.showErrorMessage("Unable to connect"),a(new Error(u.message))})});if(!o)return;let s=GB(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:_N(this.chainId)})}catch(o){throw this.signer.logger.error(o),o}finally{this.modal?.close()}}async authenticate(t,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{let n=await new Promise(async(s,i)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),i(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate({...t,chains:this.rpc.chains},r).then(a=>{s(a)}).catch(a=>{this.modal?.showErrorMessage("Unable to connect"),i(new Error(a.message))})}),o=n.session;if(o){let s=GB(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:_N(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{this.modal?.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{let{params:r}=t,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",t)}),this.signer.on("accountsChanged",t=>{this.accounts=this.parseAccounts(t),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",t=>{let r=parseInt(t);this.chainId=r,this.events.emit("chainChanged",_N(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",{...Sr("USER_DISCONNECTED"),data:t.topic,name:"USER_DISCONNECTED"})}),this.signer.on("display_uri",t=>{this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){let r=t.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",_N(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){let r=this.parseChainId(t);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(t){let[r,n,o]=t.split(":");return{chainId:`${r}:${n}`,address:o}}setAccounts(t){this.accounts=t.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){let r=t?.chains??[],n=t?.optionalChains??[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");let s=r.length?t?.methods||Oq:[],i=r.length?t?.events||Bq:[],a=t?.optionalMethods||[],c=t?.optionalEvents||[],u=t?.rpcMap||this.buildRpcMap(o,t.projectId),d=t?.qrModalOptions||void 0;return{chains:r?.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:s,events:i,optionalMethods:a,optionalEvents:c,rpcMap:u,showQrModal:!!t?.showQrModal,qrModalOptions:d,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,r){let n={};return t.forEach(o=>{n[o]=this.getRpcUrl(o,r)}),n}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?PN(this.rpc.chains):PN(this.rpc.optionalChains),this.signer=await Xee.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storage:t.storage,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{let n=await Jtt(),{convertWCMToAppKitOptions:o}=await Promise.resolve().then(function(){return nrt}),s=o({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!s.networks.length)throw new Error("No networks found for WalletConnect");r=n({...s,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:this.rpc.qrModalOptions?.enableMobileFullScreen===!0})}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;let{chains:r,optionalChains:n,rpcMap:o}=t;r&&zs(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=o?.[s]||this.getRpcUrl(s)})),n&&zs(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=o?.[s]||this.getRpcUrl(s)}))}getRpcUrl(t,r){return this.rpc.rpcMap?.[t]||`${Ztt}?chainId=eip155:${t}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{let t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:r?.accounts),this.setAccounts(r?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(r=>this.parseAccount(r))}},bAe=Xtt;function ert(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}var trt=e=>{let[t,r]=e.split(":");return xAe({id:r,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function rrt(e){let t=e.chains?.map(trt).filter(Boolean);if(t.length===0)throw new Error("At least one chain must be specified");let r=t.find(o=>o.id===e.defaultChain?.id),n={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:ert(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:r,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:e.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:e.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){let o=[...(e.mobileWallets||[]).map(a=>({id:a.id,name:a.name,links:a.links})),...(e.desktopWallets||[]).map(a=>({id:a.id,name:a.name,links:{native:a.links.native,universal:a.links.universal}}))],s=[...n.featuredWalletIds||[],...n.excludeWalletIds||[]],i=o.filter(a=>!s.includes(a.id));i.length&&(n.customWallets=i)}return n}function xAe(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var nrt=Object.freeze({__proto__:null,convertWCMToAppKitOptions:rrt,defineChain:xAe});var ECe=Ht(bCe(),1);l();l();function xCe(e){let t=Promise.resolve(),r=o=>{let s=t.then(()=>e("storage",{method:"POST",body:JSON.stringify(o)}));return t=s.catch(()=>{}),s},n=async()=>(await t,e("storage"));return{async getKeys(){return Object.keys(await n())},async getEntries(){return Object.entries(await n())},async getItem(o){return(await n())[o]},async setItem(o,s){await r({key:o,value:s})},async removeItem(o){await r({key:o,value:null})}}}var ta,vCe,rW,Jrt=(...e)=>rW(...e);async function aFr(e){if(vCe!==e.contextKey&&(ta=null,vCe=e.contextKey),rW=e.api,g({url:e.relayUrl,authorize:()=>e.api("relay-admission",{method:"POST"})}),ta?.connected)return ta;ta??=await bAe.init({projectId:e.projectId,customStoragePrefix:e.contextKey,chains:[e.chains[0]],optionalChains:e.chains.slice(1),methods:["personal_sign","eth_sendTransaction"],optionalMethods:[],disableProviderPing:!0,events:["accountsChanged","chainChanged"],showQrModal:!1,storage:xCe(Jrt),logger:"silent",telemetryEnabled:!1,metadata:e.metadata,rpcMap:Object.fromEntries(e.chains.map(d=>[d,`${e.runtimeUrl}/unavailable-rpc`]))});let t=document.createElement("dialog"),r=document.createElement("p");r.textContent="Scan with your phone wallet, then approve the connection there.";let n=document.createElement("canvas"),o=document.createElement("button");o.textContent="Cancel",o.type="button",t.append(r,n,o);let s,i=new Promise((d,f)=>{s=f}),a=()=>{ta.signer.abortPairingAttempt(),ta.signer.client.core.relayer.transportClose().catch(()=>{}),s(new Error("Wallet connection cancelled."))};o.onclick=a,t.addEventListener("cancel",a);let c=d=>{ECe.default.toCanvas(n,d,{width:280,margin:2}).catch(a),t.open||t.showModal()};ta.on("display_uri",c),document.body.append(t);let u;try{return await ta.signer.client.core.relayer.transportOpen(),await Promise.race([ta.connect(),i,new Promise((d,f)=>{u=setTimeout(()=>{a(),f(new Error("Wallet connection expired."))},18e4)})]),ta}finally{clearTimeout(u),ta.removeListener("display_uri",c),t.remove()}}async function cFr(e){rW=e.api;try{ta?.session&&await ta.disconnect()}finally{await ta?.signer.client.core.relayer.transportClose()}}export{aFr as connectWalletConnectEvm,cFr as disconnectWalletConnectEvm}; + Approved: ${p.toString()}`))}),i.forEach(f=>{n||(U1(o[f].methods,s[f].methods)?U1(o[f].events,s[f].events)||(n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=Se("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function oOe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:e[r].chains?.forEach(n=>{t[n]={methods:e[r].methods,events:e[r].events}})}),t}function XJ(e){return[...new Set(e.map(t=>t.includes(":")?t.split(":")[0]:t))]}function sOe(e){let t={};return Object.keys(e).forEach(r=>{r.includes(":")?t[r]=e[r]:ow(e[r].accounts)?.forEach(n=>{t[n]={accounts:e[r].accounts.filter(o=>o.includes(`${n}:`)),methods:e[r].methods,events:e[r].events}})}),t}function eX(e,t){return mk(e,!1)&&e<=t.max&&e>=t.min}function bk(){let e=V8();return new Promise(t=>{switch(e){case xi.browser:t(iOe());break;case xi.reactNative:t(aOe());break;case xi.node:t(cOe());break;default:t(!0)}})}function iOe(){return L1()&&navigator?.onLine}async function aOe(){return gf()&&typeof global<"u"&&global?.NetInfo?(await global?.NetInfo.fetch())?.isConnected:!0}function cOe(){return!0}function tX(e){switch(V8()){case xi.browser:lOe(e);break;case xi.reactNative:uOe(e);break;case xi.node:break}}function lOe(e){!gf()&&L1()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}function uOe(e){gf()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener(t=>e(t?.isConnected))}function rX(){return L1()&&(0,Dc.getDocument)()?(0,Dc.getDocument)()?.visibilityState==="visible":!0}var ZB={},wh=class{static get(t){return ZB[t]}static set(t,r){ZB[t]=r}static delete(t){delete ZB[t]}};function dOe(e){let t=B2.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}function fOe({publicKey:e,signature:t,payload:r}){let n=KC(r.method),o=128|parseInt(r.version?.toString()||"4"),s=mOe(r.address),i=r.era==="00"?new Uint8Array([0]):KC(r.era);if(i.length!==1&&i.length!==2)throw new Error("Invalid era length");let a=parseInt(r.nonce,16),c=new Uint8Array([a&255,a>>8&255]),u=BigInt(`0x${hOe(r.tip)}`),d=yOe(u),f=new Uint8Array([0,...e,s,...t,...i,...c,...d,...n]),p=gOe(f.length+1);return new Uint8Array([...p,o,...f])}function pOe(e){let t=KC(e),r=(0,tQ.blake2b)(t,void 0,32);return"0x"+Ut(r,"base16")}function KC(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map(t=>parseInt(t,16)))}function hOe(e){return e.startsWith("0x")?e.slice(2):e}function mOe(e){let t=B2.decode(e)[0];return t===42?0:t===60?2:1}function gOe(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){let t=e<<2|1;return new Uint8Array([t&255,t>>8&255])}else if(e<1<<30){let t=e<<2|2;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function yOe(e){if(e<1n<<6n)return new Uint8Array([Number(e<<2n)]);if(e<1n<<14n){let t=e<<2n|0x01n;return new Uint8Array([Number(t&0xffn),Number(t>>8n&0xffn)])}else if(e<1n<<30n){let t=e<<2n|0x02n;return new Uint8Array([Number(t&0xffn),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}else throw new Error("BigInt compact encoding not supported > 2^30")}function nX(e){let t=KC(e.signature),r=dOe(e.transaction.address),n=fOe({publicKey:r,signature:t,payload:e.transaction}),o=Ut(n,"base16");return pOe(o)}function sw({logger:e,name:t}){let r=typeof e=="string"?Fl({opts:{level:e,name:t}}).logger:e;return r.level=typeof e=="string"?e:e.level,r}l();l();var QS=Ht(ks(),1);l();var xf=Ht(ks(),1);vk();Rk();gh();l();tS();var CX=Ht(ks()),oS=class extends yo{constructor(t){super(),this.opts=t,this.protocol="wc",this.version=2}};var sS=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r,this.records=new Map}},iS=class{constructor(t,r){this.logger=t,this.core=r}},aS=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}},cS=class extends yo{constructor(t){super()}},lS=class{constructor(t,r,n,o){this.core=t,this.logger=r,this.name=n}};var uS=class extends yo{constructor(t,r){super(),this.relayer=t,this.logger=r}};var dS=class extends yo{constructor(t,r){super(),this.core=t,this.logger=r}};var fS=class{constructor(t,r,n){this.core=t,this.logger=r,this.store=n}},pS=class{constructor(t,r){this.projectId=t,this.logger=r}},hS=class{constructor(t,r,n){this.core=t,this.logger=r,this.telemetryEnabled=n}};var mS=class{constructor(t){this.opts=t,this.protocol="wc",this.version=2}};var gS=class{constructor(t){this.client=t}};var Ge=Ht(jd(),1);R1();B1();B1();BO();I8();cw();$c();Hk();l();l();l();function XX(e){return Number.isSafeInteger(e)&&e>=0}function eee(e){return e!=null&&typeof e!="function"&&XX(e.length)}l();function tee(e){return e==="__proto__"}l();function uw(e){return e==null||typeof e!="object"&&typeof e!="function"}l();function ree(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}l();l();function F1(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}l();function bf(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}l();var PS="[object RegExp]",dw="[object String]",fw="[object Number]",pw="[object Boolean]",z1="[object Arguments]",NS="[object Symbol]",RS="[object Date]",OS="[object Map]",BS="[object Set]",kS="[object Array]",nee="[object Function]",US="[object ArrayBuffer]",Ah="[object Object]",oee="[object Error]",DS="[object DataView]",LS="[object Uint8Array]",MS="[object Uint8ClampedArray]",HS="[object Uint16Array]",$S="[object Uint32Array]",see="[object BigUint64Array]",FS="[object Int8Array]",zS="[object Int16Array]",VS="[object Int32Array]",iee="[object BigInt64Array]",jS="[object Float32Array]",qS="[object Float64Array]";l();function hw(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function aee(e,t){return mw(e,void 0,e,new Map,t)}function mw(e,t,r,n=new Map,o=void 0){let s=o?.(e,t,r,n);if(s!==void 0)return s;if(uw(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){let i=new Array(e.length);n.set(e,i);for(let a=0;a{let i=t?.(r,n,o,s);if(i!==void 0)return i;if(typeof e=="object"){if(bf(e)===Ah&&typeof e.constructor!="function"){let a={};return s.set(e,a),Za(a,e,o,s),a}switch(Object.prototype.toString.call(e)){case fw:case dw:case pw:{let a=new e.constructor(e?.valueOf());return Za(a,e),a}case z1:{let a={};return Za(a,e),a.length=e.length,a[Symbol.iterator]=e[Symbol.iterator],a}default:return}}})}function $k(e){return cee(e)}l();function Fk(e){return e!==null&&typeof e=="object"&&bf(e)==="[object Arguments]"}l();l();function s4(e){return typeof e=="object"&&e!==null}function lee(e){return s4(e)&&eee(e)}l();l();l();function zk(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(e)==="[object Object]":!1}function uee(e,t,r){return i4(e,t,void 0,void 0,void 0,void 0,r)}function i4(e,t,r,n,o,s,i){let a=i(e,t,r,n,o,s);if(a!==void 0)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return e===t;case"number":return e===t||Object.is(e,t);case"function":return e===t;case"object":return a4(e,t,s,i)}return a4(e,t,s,i)}function a4(e,t,r,n){if(Object.is(e,t))return!0;let o=bf(e),s=bf(t);if(o===z1&&(o=Ah),s===z1&&(s=Ah),o!==s)return!1;switch(o){case dw:return e.toString()===t.toString();case fw:{let c=e.valueOf(),u=t.valueOf();return ree(c,u)}case pw:case RS:case NS:return Object.is(e.valueOf(),t.valueOf());case PS:return e.source===t.source&&e.flags===t.flags;case nee:return e===t}r=r??new Map;let i=r.get(e),a=r.get(t);if(i!=null&&a!=null)return i===t;r.set(e,t),r.set(t,e);try{switch(o){case OS:{if(e.size!==t.size)return!1;for(let[c,u]of e.entries())if(!t.has(c)||!i4(u,t.get(c),c,e,t,r,n))return!1;return!0}case BS:{if(e.size!==t.size)return!1;let c=Array.from(e.values()),u=Array.from(t.values());for(let d=0;di4(f,h,void 0,e,t,r,n));if(p===-1)return!1;u.splice(p,1)}return!0}case kS:case LS:case MS:case HS:case $S:case see:case FS:case zS:case VS:case iee:case jS:case qS:{if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let c=0;c{if(!this.initialized){let n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}},this.has=n=>(this.isInitialized(),this.keychain.has(n)),this.set=async(n,o)=>{this.isInitialized(),this.keychain.set(n,o),await this.persist()},this.get=n=>{this.isInitialized();let o=this.keychain.get(n);if(typeof o>"u"){let{message:s}=Se("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return o},this.del=async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()},this.core=t,this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(t){await this.core.storage.setItem(this.storageKey,ZC(t))}async getKeyChain(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?GC(t):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Kk=class{constructor(t,r,n){this.core=t,this.logger=r,this.name=rBe,this.randomSessionIdentifier=XC(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=o=>(this.isInitialized(),this.keychain.has(o)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;let o=await this.getClientSeed(),s=J2(o),i=U8(s.publicKey);return this.clientId=i,i},this.generateKeyPair=()=>{this.isInitialized();let o=SQ();return this.setPrivateKey(o.publicKey,o.privateKey)},this.signJWT=async o=>{this.isInitialized();let s=await this.getClientSeed(),i=J2(s),a=this.randomSessionIdentifier;return await BC(a,o,nBe,i)},this.generateSharedKey=(o,s,i)=>{this.isInitialized();let a=this.getPrivateKey(o),c=IQ(a,s);return this.setSymKey(c,i)},this.setSymKey=async(o,s)=>{this.isInitialized();let i=s||rw(o);return await this.keychain.set(i,o),i},this.deleteKeyPair=async o=>{this.isInitialized(),await this.keychain.del(o)},this.deleteSymKey=async o=>{this.isInitialized(),await this.keychain.del(o)},this.encode=async(o,s,i)=>{this.isInitialized();let a=ck(i),c=wi(s);if(uk(a))return RQ(c,i?.encoding);if(lk(a)){let p=a.senderPublicKey,h=a.receiverPublicKey;o=await this.generateSharedKey(p,h)}let u=this.getSymKey(o),{type:d,senderPublicKey:f}=a;return PQ({type:d,symKey:u,message:c,senderPublicKey:f,encoding:i?.encoding})},this.decode=async(o,s,i)=>{this.isInitialized();let a=kQ(s,i);if(uk(a)){let c=OQ(s,i?.encoding);return Fs(c)}if(lk(a)){let c=a.receiverPublicKey,u=a.senderPublicKey;o=await this.generateSharedKey(c,u)}try{let c=this.getSymKey(o),u=NQ({symKey:c,encoded:s,encoding:i?.encoding});return Fs(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${o}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(o,s=to)=>{let i=nw({encoded:o,encoding:s});return yh(i.type)},this.getPayloadSenderPublicKey=(o,s=to)=>{let i=nw({encoded:o,encoding:s});return i.senderPublicKey?Ut(i.senderPublicKey,is):void 0},this.core=t,this.logger=Cr(r,this.name),this.keychain=n||new Wk(this.core,this.logger)}get context(){return sr(this.logger)}async setPrivateKey(t,r){return await this.keychain.set(t,r),t}getPrivateKey(t){return this.keychain.get(t)}async getClientSeed(){let t="";try{t=this.keychain.get(pee)}catch{t=XC(),await this.keychain.set(pee,t)}return Qt(t,"base16")}getSymKey(t){return this.keychain.get(t)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Zk=class extends iS{constructor(t,r){super(t,r),this.logger=t,this.core=r,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name=iBe,this.version=aBe,this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{let n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);let o=await this.getRelayerMessagesWithoutClientAck();typeof o<"u"&&(this.messagesWithoutClientAck=o),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}},this.set=async(n,o,s)=>{this.isInitialized();let i=vi(o),a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[i]<"u")return i;if(a[i]=o,this.messages.set(n,a),s===YS.inbound){let c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,{...c,[i]:o})}return await this.persist(),i},this.get=n=>{this.isInitialized();let o=this.messages.get(n);return typeof o>"u"&&(o={}),o},this.getWithoutAck=n=>{this.isInitialized();let o={};for(let s of n){let i=this.messagesWithoutClientAck.get(s)||{};o[s]=Object.values(i)}return o},this.has=(n,o)=>{this.isInitialized();let s=this.get(n),i=vi(o);return typeof s[i]<"u"},this.ack=async(n,o)=>{this.isInitialized();let s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;let i=vi(o);delete s[i],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()},this.del=async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()},this.logger=Cr(t,this.name),this.core=r}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(t){await this.core.storage.setItem(this.storageKey,ZC(t))}async setRelayerMessagesWithoutClientAck(t){await this.core.storage.setItem(this.storageKeyWithoutClientAck,ZC(t))}async getRelayerMessages(){let t=await this.core.storage.getItem(this.storageKey);return typeof t<"u"?GC(t):void 0}async getRelayerMessagesWithoutClientAck(){let t=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof t<"u"?GC(t):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Gk=class extends aS{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.events=new xf.EventEmitter,this.name=lBe,this.queue=new Map,this.publishTimeout=(0,Ge.toMiliseconds)(Ge.ONE_MINUTE),this.initialPublishTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(n,o,s)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:o,opts:s}});let i=s?.ttl||cBe,a=s?.prompt||!1,c=s?.tag||0,u=s?.id||_n().toString(),d=M1(Z8().protocol),f={id:u,method:s?.publishMethod||d.publish,params:{topic:n,message:o,ttl:i,prompt:a,tag:c,attestation:s?.attestation,...s?.tvf}},p=`Failed to publish payload, please try again. id:${u} tag:${c}`;try{In(f.params?.prompt)&&delete f.params?.prompt,In(f.params?.tag)&&delete f.params?.tag;let h=new Promise(async y=>{let w=({id:v})=>{f.id?.toString()===v.toString()&&(this.removeRequestFromQueue(v),this.relayer.events.removeListener(yn.publish,w),y())};this.relayer.events.on(yn.publish,w);let x=Wa(new Promise((v,T)=>{this.rpcPublish(f,s).then(v).catch(E=>{this.logger.warn(E,E?.message),T(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${c}`);try{await x,this.events.removeListener(yn.publish,w)}catch(v){this.queue.set(u,{request:f,opts:s,attempt:1}),this.logger.warn(v,v?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:n,message:o,opts:s}}),await Wa(h,this.publishTimeout,p)}catch(h){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(h),s?.internal?.throwOnFailedPublish)throw h}finally{this.queue.delete(u)}},this.publishCustom=async n=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});let{payload:o,opts:s={}}=n,{attestation:i,tvf:a,publishMethod:c,prompt:u,tag:d,ttl:f=Ge.FIVE_MINUTES}=s,p=s.id||_n().toString(),h=M1(Z8().protocol),y=c||h.publish,w={id:p,method:y,params:{...o,ttl:f,prompt:u,tag:d,attestation:i,...a}},x=`Failed to publish custom payload, please try again. id:${p} tag:${d}`;try{In(w.params?.prompt)&&delete w.params?.prompt,In(w.params?.tag)&&delete w.params?.tag;let v=new Promise(async T=>{let E=({id:_})=>{w.id?.toString()===_.toString()&&(this.removeRequestFromQueue(_),this.relayer.events.removeListener(yn.publish,E),T())};this.relayer.events.on(yn.publish,E);let S=Wa(new Promise((_,O)=>{this.rpcPublish(w,s).then(_).catch(D=>{this.logger.warn(D,D?.message),O(D)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${p} tag:${d}`);try{await S,this.events.removeListener(yn.publish,E)}catch(_){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(_,_?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,payload:o,opts:s}}),await Wa(v,this.publishTimeout,x)}catch(v){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(v),s?.internal?.throwOnFailedPublish)throw v}finally{this.queue.delete(p)}},this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.relayer=t,this.logger=Cr(r,this.name),this.registerEventListeners()}get context(){return sr(this.logger)}async rpcPublish(t,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:t});let n=await this.relayer.request(t);return this.relayer.events.emit(yn.publish,{...t,...r}),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(t){this.queue.delete(t)}checkQueue(){this.queue.forEach(async(t,r)=>{let n=t.attempt+1;this.queue.set(r,{...t,attempt:n}),this.logger.warn({},`Publisher: queue->publishing: ${t.request.id}, tag: ${t.request.params?.tag}, attempt: ${n}`),await this.rpcPublish(t.request,t.opts),this.logger.warn({},`Publisher: queue->published: ${t.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vs.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(yn.connection_stalled);return}this.checkQueue()}),this.relayer.on(yn.message_ack,t=>{this.removeRequestFromQueue(t.id.toString())})}},Yk=class{constructor(){this.map=new Map,this.set=(t,r)=>{let n=this.get(t);this.exists(t,r)||this.map.set(t,[...n,r])},this.get=t=>this.map.get(t)||[],this.exists=(t,r)=>this.get(t).includes(r),this.delete=(t,r)=>{if(typeof r>"u"){this.map.delete(t);return}if(!this.map.has(t))return;let n=this.get(t);if(!this.exists(t,r))return;let o=n.filter(s=>s!==r);if(!o.length){this.map.delete(t);return}this.map.set(t,o)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}},Jk=class extends uS{constructor(t,r){super(t,r),this.relayer=t,this.logger=r,this.subscriptions=new Map,this.topicMap=new Yk,this.events=new xf.EventEmitter,this.name=gBe,this.version=yBe,this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.subscribeTimeout=(0,Ge.toMiliseconds)(Ge.ONE_MINUTE),this.initialSubscribeTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(n,o)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}});try{let s=Z8(o),i={topic:n,relay:s,transportType:o?.transportType};o?.internal?.skipSubscribe||this.pending.set(n,i);let a=await this.rpcSubscribe(n,s,o);return typeof a=="string"&&(this.onSubscribe(a,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:o}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}},this.unsubscribe=async(n,o)=>{this.isInitialized(),typeof o?.id<"u"?await this.unsubscribeById(n,o.id,o):await this.unsubscribeByTopic(n,o)},this.isSubscribed=n=>new Promise(o=>{o(this.topicMap.topics.includes(n))}),this.isKnownTopic=n=>new Promise(o=>{o(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))}),this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;let n=[];this.pending.forEach(o=>{n.push(o)}),await this.batchSubscribe(n)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(Vs.pulse,async()=>{await this.checkPending()}),this.events.on(fa.created,async n=>{let o=fa.created;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()}),this.events.on(fa.deleted,async n=>{let o=fa.deleted;this.logger.info(`Emitting ${o}`),this.logger.debug({type:"event",event:o,data:n}),await this.persist()})},this.relayer=t,this.logger=Cr(r,this.name),this.clientId=""}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(t,r){let n=!1;try{n=this.getSubscription(t).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(t,r){let n=this.topicMap.get(t);await Promise.all(n.map(async o=>await this.unsubscribeById(t,o,r)))}async unsubscribeById(t,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}});try{let o=Sr("USER_DISCONNECTED",`${this.name}, ${t}`);await this.onUnsubscribe(t,r,o);let s=Z8(n);await this.restartToComplete({topic:t,id:r,relay:s}),await this.rpcUnsubscribe(t,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:t,id:r,opts:n}})}catch(o){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(o),o}}async rpcSubscribe(t,r,n){let o=await this.getSubscriptionId(t);if(n?.internal?.skipSubscribe)return o;(!n||n?.transportType===Dr.relay)&&await this.restartToComplete({topic:t,id:t,relay:r});let s={method:M1(r.protocol).subscribe,params:{topic:t}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let i=n?.internal?.throwOnFailedPublish;try{if(n?.transportType===Dr.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(u=>this.logger.warn(u))},(0,Ge.toMiliseconds)(Ge.ONE_SECOND)),o;let a=new Promise(async u=>{let d=f=>{f.topic===t&&(this.events.removeListener(fa.created,d),u(f.id))};this.events.on(fa.created,d);try{let f=await Wa(new Promise((p,h)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),h(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${t} failed, please try again`);this.events.removeListener(fa.created,d),u(f)}catch{}}),c=await Wa(a,this.subscribeTimeout,`Subscribing to ${t} failed, please try again`);if(!c&&i)throw new Error(`Subscribing to ${t} failed, please try again`);return c?o:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(yn.connection_stalled),i)throw a}return null}async rpcBatchSubscribe(t){if(!t.length)return!0;let r=t[0].relay,n={method:M1(r.protocol).batchSubscribe,params:{topics:t.map(o=>o.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{return await Wa(new Promise((o,s)=>{this.relayer.request(n).then(o).catch(i=>{this.logger.warn(i),s(i)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(yn.connection_stalled),!1}}async rpcBatchFetchMessages(t){if(!t.length)return;let r=t[0].relay,n={method:M1(r.protocol).batchFetchMessages,params:{topics:t.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let o;try{o=await await Wa(new Promise((s,i)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),i(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(yn.connection_stalled)}return o}rpcUnsubscribe(t,r,n){let o={method:M1(n.protocol).unsubscribe,params:{topic:t,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:o}),this.relayer.request(o)}onSubscribe(t,r){this.setSubscription(t,{...r,id:t}),this.pending.delete(r.topic)}onBatchSubscribe(t){t.length&&t.forEach(r=>{this.setSubscription(r.id,{...r}),this.pending.delete(r.topic)})}async onUnsubscribe(t,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,t)&&this.deleteSubscription(r,n),await this.relayer.messages.del(t)}async setRelayerSubscriptions(t){await this.relayer.core.storage.setItem(this.storageKey,t)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(t,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:t,subscription:r}),this.addSubscription(t,r)}addSubscription(t,r){this.subscriptions.set(t,{...r}),this.topicMap.set(r.topic,t),this.events.emit(fa.created,r)}getSubscription(t){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:t});let r=this.subscriptions.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}deleteSubscription(t,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:t,reason:r});let n=this.getSubscription(t);this.subscriptions.delete(t),this.topicMap.delete(n.topic,t),this.events.emit(fa.deleted,{...n,reason:r})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(fa.sync)}async onRestart(){if(this.cached.length){let t=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n"u"||!t.length)return;if(this.subscriptions.size&&!t.every(r=>r.topic===this.subscriptions.get(r.id)?.topic)){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(t){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(t)}}async batchSubscribe(t){if(t.length){if(!await this.rpcBatchSubscribe(t)){this.logger.warn(`Batch subscribe failed for ${t.length} topics, adding to pending for retry`),t.forEach(r=>{this.pending.set(r.topic,r)});return}this.onBatchSubscribe(await Promise.all(t.map(async r=>({...r,id:await this.getSubscriptionId(r.topic)}))))}}async batchFetchMessages(t){if(!t.length)return;this.logger.trace(`Fetching batch messages for ${t.length} subscriptions`);let r=await this.rpcBatchFetchMessages(t);r&&r.messages&&(await pQ((0,Ge.toMiliseconds)(Ge.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async restartToComplete(t){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(t),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(t){return vi(t+await this.getClientId())}},Qk=class extends cS{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new xf.EventEmitter,this.name=dBe,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=(0,Ge.toMiliseconds)(Ge.THIRTY_SECONDS+Ge.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*15),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=(0,Ge.toMiliseconds)(Ge.ONE_SECOND*2),this.stalledRestartMaxInterval=(0,Ge.toMiliseconds)(Ge.THIRTY_SECONDS),this.request=async r=>{this.logger.debug("Publishing Request Payload");let n=r.id||_n().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:r.method,topic:r.params?.topic},"relayer.request - publishing...");let o=`${n}:${r.params?.tag||""}`;this.requestsInFlight.push(o);let s=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(i=>i!==o),s}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}},this.resetPingTimeout=()=>{z8()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(r){this.logger.warn(r,r?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=r=>{this.onProviderPayload(r),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(yn.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(yn.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(n=>this.logger.warn(n))},this.registerProviderListeners=()=>{this.provider.on(Ga.payload,this.onPayloadHandler),this.provider.on(Ga.connect,this.onConnectHandler),this.provider.on(Ga.disconnect,this.onDisconnectHandler),this.provider.on(Ga.error,this.onProviderErrorHandler)},this.core=t.core,this.logger=sw({logger:t.logger??uBe,name:this.name}),this.messages=new Zk(this.logger,t.core),this.subscriber=new Jk(this,this.logger),this.publisher=new Gk(this,this.logger),this.projectId=t.projectId,this.relayUrl=t.relayUrl||wee,nQ()?this.packageName=YB():oQ()&&(this.bundleId=YB()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(t=>this.logger.warn(t,t?.message))}get context(){return sr(this.logger)}get connected(){return this.provider?.connection?.socket?.readyState===1}get connecting(){return this.provider?.connection?.socket?.readyState===0||this.connectPromise!==void 0}async publish(t,r,n){this.isInitialized(),await this.publisher.publish(t,r,n),await this.recordMessageEvent({topic:t,message:r,publishedAt:Date.now(),transportType:Dr.relay},YS.outbound)}async publishCustom(t){this.isInitialized(),await this.publisher.publishCustom(t)}async subscribe(t,r){this.isInitialized(),(!r?.transportType||r?.transportType==="relay")&&await this.toEstablishConnection();let n=r?.internal?.throwOnFailedPublish??!0,o=this.subscriber.topicMap.get(t)?.[0]||"",s,i=a=>{a.topic===t&&(this.subscriber.off(fa.created,i),s())};return await Promise.all([new Promise(a=>{s=a,this.subscriber.on(fa.created,i)}),new Promise((a,c)=>{this.subscriber.subscribe(t,{internal:{throwOnFailedPublish:n},...r}).then(u=>{o=u||o,a()}).catch(u=>{n?c(u):a()})})]),o}async unsubscribe(t,r){this.isInitialized(),await this.subscriber.unsubscribe(t,r)}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}off(t,r){this.events.off(t,r)}removeListener(t,r){this.events.removeListener(t,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Wa(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(t){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=this.connect(t).finally(()=>{this.connectPromise=void 0}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(t){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=t||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await bk())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(t){if(t?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}let r=t.sort((n,o)=>n.publishedAt-o.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(let n of r)try{await this.onMessageEvent(n)}catch(o){this.logger.warn(o,"Error while processing batch message event: "+o?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(t,r){let{topic:n}=t;if(!r.sessionExists){let o=ln(Ge.FIVE_MINUTES),s={topic:n,expiry:o,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(yn.message,t),await this.recordMessageEvent(t,YS.inbound)}async connect(t){await this.confirmOnlineStateOrThrow(),t&&t!==this.relayUrl&&(this.relayUrl=t,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let r=1;try{for(;r<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise((n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ga.disconnect,s),Wa(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>n()).catch(o).finally(()=>{this.provider.off(Ga.disconnect,s),clearTimeout(this.reconnectTimeout)})}),await new Promise((n,o)=>{let s=()=>{o(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ga.disconnect,s),this.subscriber.start().then(n).catch(o).finally(()=>{this.provider.off(Ga.disconnect,s)})}),this.hasExperiencedNetworkDisruption=!1}catch(n){await this.subscriber.stop();let o=n;this.logger.warn({},o.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,(0,Ge.toMiliseconds)(r*1))),r++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(z8())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(t){this.logger.warn(t,t?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await Wa(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}let t=await this.core.crypto.signJWT(this.relayUrl);this.provider=new da(new lw(iQ({sdkVersion:qk,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:t,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(t,r){let{topic:n,message:o}=t;await this.messages.set(n,o,r)}async shouldIgnoreMessageEvent(t){let{topic:r,message:n}=t;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;let o=this.messages.has(r,n);return o&&this.logger.warn(`Ignoring duplicate message: ${n}`),o}async onProviderPayload(t){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:t}),Hc(t)){if(!t.method.endsWith(fBe))return;let r=t.params,{topic:n,message:o,publishedAt:s,attestation:i}=r.data,a={topic:n,message:o,publishedAt:s,transportType:Dr.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:r.id,...a}),this.events.emit(r.id,a),await this.acknowledgePayload(t),await this.onMessageEvent(a)}else ua(t)&&this.events.emit(yn.message_ack,t)}async onMessageEvent(t){await this.shouldIgnoreMessageEvent(t)||(await this.recordMessageEvent(t,YS.inbound),this.events.emit(yn.message,t))}async acknowledgePayload(t){let r=bo(t.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Ga.payload,this.onPayloadHandler),this.provider.off(Ga.connect,this.onConnectHandler),this.provider.off(Ga.disconnect,this.onDisconnectHandler),this.provider.off(Ga.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let t=await bk();tX(async r=>{t!==r&&(t=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vs.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&rX())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}}),this.events.on(yn.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;let r=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${r?` in ${r}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(n){this.logger.error(n,n?.message)}finally{this.stalledRestartInProgress=!1}},r)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(yn.disconnect),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(t){this.logger.warn(t,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed){this.reconnectInProgress=!1;return}this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(t=>this.logger.error(t,t?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},(0,Ge.toMiliseconds)(pBe))}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}},jl=class extends lS{constructor(t,r,n,o=Vl,s=void 0){super(t,r,n,o),this.core=t,this.logger=r,this.name=n,this.map=new Map,this.version=hBe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>{this.getKey&&i!==null&&!In(i)?this.map.set(this.getKey(i),i):FQ(i)?this.map.set(i.id,i):zQ(i)&&this.map.set(i.topic,i)}),this.cached=[],this.initialized=!0)},this.set=async(i,a)=>{this.isInitialized(),this.map.has(i)?await this.update(i,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:i,value:a}),this.map.set(i,a),await this.persist())},this.get=i=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:i}),this.getData(i)),this.getAll=i=>(this.isInitialized(),i?this.values.filter(a=>Object.keys(i).every(c=>Vk(a[c],i[c]))):this.values),this.update=async(i,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:i,update:a});let c={...this.getData(i),...a};this.map.set(i,c),await this.persist()},this.delete=async(i,a)=>{this.isInitialized(),this.map.has(i)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:i,reason:a}),this.map.delete(i),this.addToRecentlyDeleted(i),await this.persist())},this.logger=Cr(r,this.name),this.storagePrefix=o,this.getKey=s}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(t){this.recentlyDeleted.push(t),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(t){await this.core.storage.setItem(this.storageKey,t)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(t){let r=this.map.get(t);if(!r){if(this.recentlyDeleted.includes(t)){let{message:o}=Se("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${t}`);throw this.logger.error(o),new Error(o)}let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{let t=await this.getDataStore();if(typeof t>"u"||!t.length)return;if(this.map.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(t){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(t)}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},Xk=class{constructor(t,r){this.core=t,this.logger=r,this.name=wBe,this.version=bBe,this.events=new xf.default,this.initialized=!1,this.storagePrefix=Vl,this.ignoredPayloadTypes=[Mc],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]},this.create=async n=>{this.isInitialized();let o=XC(),s=await this.core.crypto.setSymKey(o),i=ln(Ge.FIVE_MINUTES),a={protocol:sU},c={topic:s,expiry:i,relay:a,active:!1,methods:n?.methods},u=fk({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:o,relay:a,expiryTimestamp:i,methods:n?.methods});return this.events.emit(Ch.create,c),this.core.expirer.set(s,i),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}},this.pair=async n=>{this.isInitialized();let o=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[zc.pairing_started]}});this.isValidPair(n,o);let{topic:s,symKey:i,relay:a,expiryTimestamp:c,methods:u}=dk(n.uri);o.props.properties.topic=s,o.addTrace(zc.pairing_uri_validation_success),o.addTrace(zc.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(s)){if(d=this.pairings.get(s),o.addTrace(zc.existing_pairing),d.active)throw o.setError(zl.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);o.addTrace(zc.pairing_not_expired)}let f=c||ln(Ge.FIVE_MINUTES),p={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,p),o.addTrace(zc.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Ch.create,p),o.addTrace(zc.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),o.addTrace(zc.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{o.setError(zl.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw o.setError(zl.subscribe_pairing_topic_failure),h}return o.addTrace(zc.subscribe_pairing_topic_success),p},this.activate=async({topic:n})=>{this.isInitialized();let o=ln(Ge.FIVE_MINUTES);this.core.expirer.set(n,o),await this.pairings.update(n,{active:!0,expiry:o})},this.ping=async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");let{topic:o}=n;if(this.pairings.keys.includes(o)){let s=await this.sendRequest(o,"wc_pairingPing",{}),{done:i,resolve:a,reject:c}=yf();this.events.once(ir("pairing_ping",s),({error:u})=>{u?c(u):a()}),await i()}},this.updateExpiry=async({topic:n,expiry:o})=>{this.isInitialized(),await this.pairings.update(n,{expiry:o})},this.updateMetadata=async({topic:n,metadata:o})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:o})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async n=>{this.isInitialized(),await this.isValidDisconnect(n);let{topic:o}=n;this.pairings.keys.includes(o)&&(await this.sendRequest(o,"wc_pairingDelete",Sr("USER_DISCONNECTED")),await this.deletePairing(o))},this.formatUriFromPairing=n=>{this.isInitialized();let{topic:o,relay:s,expiry:i,methods:a}=n,c=this.core.crypto.keychain.get(o);return fk({protocol:this.core.protocol,version:this.core.version,topic:o,symKey:c,relay:s,expiryTimestamp:i,methods:a})},this.sendRequest=async(n,o,s)=>{let i=dr(o,s),a=await this.core.crypto.encode(n,i),c=c4[o].req;return this.core.history.set(n,i),this.core.relayer.publish(n,a,c),i.id},this.sendResult=async(n,o,s)=>{let i=bo(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=c4[c].res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)},this.sendError=async(n,o,s)=>{let i=la(n,s),a=await this.core.crypto.encode(o,i),c=(await this.core.history.get(o,n)).request.method,u=c4[c]?c4[c].res:c4.unregistered_method.res;await this.core.relayer.publish(o,a,u),await this.core.history.resolve(i)},this.deletePairing=async(n,o)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Sr("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),o?Promise.resolve():this.core.expirer.del(n)])},this.cleanup=async()=>{let n=this.pairings.getAll().filter(o=>ca(o.expiry));await Promise.all(n.map(o=>this.deletePairing(o.topic)))},this.onRelayEventRequest=async n=>{let{topic:o,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(o,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(o,s);default:return await this.onUnknownRpcMethodRequest(o,s)}},this.onRelayEventResponse=async n=>{let{topic:o,payload:s}=n,i=(await this.core.history.get(o,s.id)).request.method;return i==="wc_pairingPing"?this.onPairingPingResponse(o,s):this.onUnknownRpcMethodResponse(i)},this.onPairingPingRequest=async(n,o)=>{let{id:s}=o;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Ch.ping,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}},this.onPairingPingResponse=(n,o)=>{let{id:s}=o;setTimeout(()=>{Jr(o)?this.events.emit(ir("pairing_ping",s),{}):Ir(o)&&this.events.emit(ir("pairing_ping",s),{error:o.error})},500)},this.onPairingDeleteRequest=async(n,o)=>{let{id:s}=o;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Ch.delete,{id:s,topic:n})}catch(i){await this.sendError(s,n,i),this.logger.error(i)}},this.onUnknownRpcMethodRequest=async(n,o)=>{let{id:s,method:i}=o;try{if(this.registeredMethods.includes(i))return;let a=Sr("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=n=>{this.registeredMethods.includes(n)||this.logger.error(Sr("WC_METHOD_UNSUPPORTED",n))},this.isValidPair=(n,o)=>{if(!as(n)){let{message:i}=Se("MISSING_OR_INVALID",`pair() params: ${n}`);throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(!$Q(n.uri)){let{message:i}=Se("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw o.setError(zl.malformed_pairing_uri),new Error(i)}let s=dk(n?.uri);if(!s?.relay?.protocol){let{message:i}=Se("MISSING_OR_INVALID","pair() uri#relay-protocol");throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(!s?.symKey){let{message:i}=Se("MISSING_OR_INVALID","pair() uri#symKey");throw o.setError(zl.malformed_pairing_uri),new Error(i)}if(s?.expiryTimestamp&&(0,Ge.toMiliseconds)(s?.expiryTimestamp){if(!as(n)){let{message:s}=Se("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)},this.isValidDisconnect=async n=>{if(!as(n)){let{message:s}=Se("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}let{topic:o}=n;await this.isValidPairingTopic(o)},this.isValidPairingTopic=async n=>{if(!gn(n,!1)){let{message:o}=Se("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(o)}if(!this.pairings.keys.includes(n)){let{message:o}=Se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(o)}if(ca(this.pairings.get(n).expiry)){await this.deletePairing(n);let{message:o}=Se("EXPIRED",`pairing topic: ${n}`);throw new Error(o)}},this.core=t,this.logger=Cr(r,this.name),this.pairings=new jl(this.core,this.logger,this.name,this.storagePrefix)}get context(){return sr(this.logger)}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}registerRelayerEvents(){this.core.relayer.on(yn.message,async t=>{let{topic:r,message:n,transportType:o}=t;if(this.pairings.keys.includes(r)&&o!==Dr.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{let s=await this.core.crypto.decode(r,n);Hc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ua(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(pa.expired,async t=>{let{topic:r}=YC(t.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ch.expire,{topic:r}))})}},eU=class extends sS{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.records=new Map,this.events=new xf.EventEmitter,this.name=xBe,this.version=vBe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(n,o,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:o,chainId:s}),this.records.has(o.id))return;let i={id:o.id,topic:n,request:{method:o.method,params:o.params||null},chainId:s,expiry:ln(Ge.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Fc.created,i)},this.resolve=async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;let o=await this.getRecord(n.id);typeof o.response<"u"||(o.response=Ir(n)?{error:n.error}:{result:n.result},this.records.set(o.id,o),this.persist(),this.events.emit(Fc.updated,o))},this.get=async(n,o)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:o}),await this.getRecord(o)),this.delete=(n,o)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:o}),this.values.forEach(s=>{if(s.topic===n){if(typeof o<"u"&&s.id!==o)return;this.records.delete(s.id),this.events.emit(Fc.deleted,s)}}),this.persist()},this.exists=async(n,o)=>(this.isInitialized(),this.records.has(o)?(await this.getRecord(o)).topic===n:!1),this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){let t=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;let n={topic:r.topic,request:dr(r.request.method,r.request.params,r.id),chainId:r.chainId};return t.push(n)}),t}async setJsonRpcRecords(t){await this.core.storage.setItem(this.storageKey,t)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(t){this.isInitialized();let r=this.records.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fc.sync)}async restore(){try{let t=await this.getJsonRpcRecords();if(typeof t>"u"||!t.length)return;if(this.records.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(t){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(t)}}registerEventListeners(){this.events.on(Fc.created,t=>{let r=Fc.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Fc.updated,t=>{let r=Fc.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.events.on(Fc.deleted,t=>{let r=Fc.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:t})}),this.core.heartbeat.on(Vs.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let t=!1;this.records.forEach(r=>{(0,Ge.toMiliseconds)(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Fc.deleted,r,!1),t=!0)}),t&&this.persist()}catch(t){this.logger.warn(t)}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},tU=class extends dS{constructor(t,r){super(t,r),this.core=t,this.logger=r,this.expirations=new Map,this.events=new xf.EventEmitter,this.name=EBe,this.version=ABe,this.cached=[],this.initialized=!1,this.storagePrefix=Vl,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=n=>{try{let o=this.formatTarget(n);return typeof this.getExpiration(o)<"u"}catch{return!1}},this.set=(n,o)=>{this.isInitialized();let s=this.formatTarget(n),i={target:s,expiry:o};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(pa.created,{target:s,expiration:i})},this.get=n=>{this.isInitialized();let o=this.formatTarget(n);return this.getExpiration(o)},this.del=n=>{if(this.isInitialized(),this.has(n)){let o=this.formatTarget(n),s=this.getExpiration(o);this.expirations.delete(o),this.events.emit(pa.deleted,{target:o,expiration:s})}},this.on=(n,o)=>{this.events.on(n,o)},this.once=(n,o)=>{this.events.once(n,o)},this.off=(n,o)=>{this.events.off(n,o)},this.removeListener=(n,o)=>{this.events.removeListener(n,o)},this.logger=Cr(r,this.name)}get context(){return sr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(t){if(typeof t=="string")return cQ(t);if(typeof t=="number")return lQ(t);let{message:r}=Se("UNKNOWN_TYPE",`Target type: ${typeof t}`);throw new Error(r)}async setExpirations(t){await this.core.storage.setItem(this.storageKey,t)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(pa.sync)}async restore(){try{let t=await this.getExpirations();if(typeof t>"u"||!t.length)return;if(this.expirations.size){let{message:r}=Se("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=t,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(t){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(t)}}getExpiration(t){let r=this.expirations.get(t);if(!r){let{message:n}=Se("NO_MATCHING_KEY",`${this.name}: ${t}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(t,r){let{expiry:n}=r;(0,Ge.toMiliseconds)(n)-Date.now()<=0&&this.expire(t,r)}expire(t,r){this.expirations.delete(t),this.events.emit(pa.expired,{target:t,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((t,r)=>this.checkExpiry(r,t))}registerEventListeners(){this.core.heartbeat.on(Vs.pulse,()=>this.checkExpirations()),this.events.on(pa.created,t=>{let r=pa.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(pa.expired,t=>{let r=pa.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()}),this.events.on(pa.deleted,t=>{let r=pa.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:t}),this.persist()})}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}},rU=class extends fS{constructor(t,r,n){super(t,r,n),this.core=t,this.logger=r,this.store=n,this.name=CBe,this.verifyUrlV3=IBe,this.storagePrefix=Vl,this.version=yee,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&(0,Ge.toMiliseconds)(this.publicKey?.expiresAt){if(!L1()||this.isDevEnv)return;let s=window.location.origin,{id:i,decryptedId:a}=o,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${i}&decryptedId=${a}`;try{let u=(0,mee.getDocument)(),d=this.startAbortTimer(Ge.ONE_SECOND*5),f=await new Promise((p,h)=>{let y=()=>{window.removeEventListener("message",x),u.body.removeChild(w),h("attestation aborted")};this.abortController.signal.addEventListener("abort",y);let w=u.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",y,{signal:this.abortController.signal});let x=v=>{if(v.data&&typeof v.data=="string")try{let T=JSON.parse(v.data);if(T.type==="verify_attestation"){if(Hl(T.attestation).payload.id!==i)return;clearInterval(d),u.body.removeChild(w),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",x),p(T.attestation===null?"":T.attestation)}}catch(T){this.logger.warn(T)}};u.body.appendChild(w),window.addEventListener("message",x,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""},this.resolve=async o=>{if(this.isDevEnv)return"";let{attestationId:s,hash:i,encryptedId:a}=o;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Hl(s).payload.id!==a)return;let u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!i)return;let c=this.getVerifyUrl(o?.verifyUrl);return this.fetchAttestation(i,c)},this.fetchAttestation=async(o,s)=>{this.logger.debug(`resolving attestation: ${o} from url: ${s}`);let i=this.startAbortTimer(Ge.ONE_SECOND*5),a=await fetch(`${s}/attestation/${o}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),a.status===200?await a.json():void 0},this.getVerifyUrl=o=>{let s=o||gw;return TBe.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gw}`),s=gw),s},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);let o=this.startAbortTimer(Ge.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(o),await s.json()}catch(o){this.logger.warn(o)}},this.persistPublicKey=async o=>{this.logger.debug(o,"persisting public key to local storage"),await this.store.setItem(this.storeKey,o),this.publicKey=o},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async o=>{let s=await this.getPublicKey();try{if(s)return this.validateAttestation(o,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}let i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(o,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{let i=await this.fetchPublicKey();i&&(await this.persistPublicKey(i),s(i))});let o=await this.fetchPromise;return this.fetchPromise=void 0,o},this.validateAttestation=(o,s)=>{let i=UQ(o,s.publicKey),a={hasExpired:(0,Ge.toMiliseconds)(i.exp)this.abortController.abort(),(0,Ge.toMiliseconds)(t))}},nU=class extends pS{constructor(t,r){super(t,r),this.projectId=t,this.logger=r,this.context=_Be,this.registerDeviceToken=async n=>{let{clientId:o,token:s,notificationType:i,enableEncrypted:a=!1}=n,c=`${PBe}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:o,type:i,token:s,always_raw:a})})},this.logger=Cr(r,this.context)}},oU=class extends hS{constructor(t,r,n=!0){super(t,r,n),this.core=t,this.logger=r,this.context=RBe,this.storagePrefix=Vl,this.storageVersion=NBe,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!j8())try{let o={eventId:ek(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:QB(this.core.relayer.protocol,this.core.relayer.version,qk)}}};await this.sendEvent([o])}catch(o){this.logger.warn(o)}},this.createEvent=o=>{let{event:s="ERROR",type:i="",properties:{topic:a,trace:c}}=o,u=ek(),d=this.core.projectId||"",f=Date.now(),p={eventId:u,timestamp:f,props:{event:s,type:i,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain(),...this.setMethods(u)};return this.telemetryEnabled&&(this.events.set(u,p),this.shouldPersist=!0),p},this.getEvent=o=>{let{eventId:s,topic:i}=o;if(s)return this.events.get(s);let a=Array.from(this.events.values()).find(c=>c.props.properties.topic===i);if(a)return{...a,...this.setMethods(a.eventId)}},this.deleteEvent=o=>{let{eventId:s}=o;this.events.delete(s),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(Vs.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(o=>{(0,Ge.fromMiliseconds)(Date.now())-(0,Ge.fromMiliseconds)(o.timestamp)>OBe&&(this.events.delete(o.eventId),this.shouldPersist=!0)})})},this.setMethods=o=>({addTrace:s=>this.addTrace(o,s),setError:s=>this.setError(o,s)}),this.addTrace=(o,s)=>{let i=this.events.get(o);i&&(i.props.properties.trace.push(s),this.events.set(o,i),this.shouldPersist=!0)},this.setError=(o,s)=>{let i=this.events.get(o);i&&(i.props.type=s,i.timestamp=Date.now(),this.events.set(o,i),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{let o=await this.core.storage.getItem(this.storageKey)||[];if(!o.length)return;o.forEach(s=>{this.events.set(s.eventId,{...s,...this.setMethods(s.eventId)})})}catch(o){this.logger.warn(o)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;let o=[];for(let[s,i]of this.events)i.props.type&&o.push(i);if(o.length!==0)try{if((await this.sendEvent(o)).ok)for(let s of o)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}},this.sendEvent=async o=>{let s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${BBe}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${qk}${s}`,{method:"POST",body:JSON.stringify(o)})},this.getAppDomain=()=>JB().url,this.logger=Cr(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}},kBe=class xee extends oS{constructor(t){super(t),this.protocol=gee,this.version=yee,this.name=JS,this.events=new xf.EventEmitter,this.initialized=!1,this.on=(i,a)=>this.events.on(i,a),this.once=(i,a)=>this.events.once(i,a),this.off=(i,a)=>this.events.off(i,a),this.removeListener=(i,a)=>this.events.removeListener(i,a),this.dispatchEnvelope=({topic:i,message:a,sessionExists:c})=>{if(!i||!a)return;let u={topic:i,message:a,publishedAt:Date.now(),transportType:Dr.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:c})};let r=this.getGlobalCore(t?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(i){console.warn("Failed to copy global core",i)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||wee,this.customStoragePrefix=t?.customStoragePrefix?`:${t.customStoragePrefix}`:"";let n=X2({level:typeof t?.logger=="string"&&t.logger?t.logger:eBe.logger,name:JS}),{logger:o,chunkLoggerController:s}=Fl({opts:n,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=s,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Cr(o,this.name),this.heartbeat=new iw,this.crypto=new Kk(this,this.logger,t?.keychain),this.history=new eU(this,this.logger),this.expirer=new tU(this,this.logger),this.storage=t?.storage?t.storage:new aw({...tBe,...t?.storageOptions}),this.relayer=new Qk({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Xk(this,this.logger),this.verify=new rU(this,this.logger,this.storage),this.echoClient=new nU(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new oU(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){let r=new xee(t);await r.initialize();let n=await r.crypto.getClientId();return await r.storage.setItem(mBe,n),r}get context(){return sr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(t){this.linkModeSupportedApps.includes(t)||(this.linkModeSupportedApps.push(t),await this.storage.setItem(hee,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(hee)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(t){throw this.logger.warn(t,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(t.message),t}}getGlobalCore(t=""){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(t){try{if(this.isGlobalCoreDisabled())return;let r=`_walletConnectCore_${t.opts?.customStoragePrefix||""}`;globalThis[r]=t}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},vee=kBe;gh();var It=Ht(jd(),1);$c();var Cee="wc",See=2,Iee="client",gU=`${Cee}@${See}:${Iee}:`,iU={name:Iee,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"};var Eee="WALLETCONNECT_DEEPLINK_CHOICE";var UBe="proposal";var Aee="Proposal expired",DBe="session",ww=It.SEVEN_DAYS,LBe="engine",$o={wc_sessionPropose:{req:{ttl:It.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1104},res:{ttl:It.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1106},res:{ttl:It.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:It.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:It.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:It.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1112},res:{ttl:It.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:It.ONE_DAY,prompt:!1,tag:1114},res:{ttl:It.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:It.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:It.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:It.FIVE_MINUTES,prompt:!1,tag:1119}}},aU={min:It.FIVE_MINUTES,max:It.SEVEN_DAYS},ql={idle:"IDLE",active:"ACTIVE"},MBe={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},HBe="request",$Be=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],FBe="wc";var zBe="auth",VBe="authKeys",jBe="pairingTopics",qBe="requests",XS=`${FBe}@${1.5}:${zBe}:`,Th=`${XS}:PUB_KEY`,cU=class extends gS{constructor(t){super(t),this.name=LBe,this.events=new QS.default,this.initialized=!1,this.requestQueue={state:ql.idle,queue:[]},this.sessionRequestQueue={state:ql.idle,queue:[]},this.emittedSessionRequests=new jC({limit:500}),this.requestQueueDelay=It.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys($o)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},(0,It.toMiliseconds)(this.requestQueueDelay)))},this.connect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();let n={...r,requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}};await this.isValidConnect(n),n.optionalNamespaces=MQ(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};let{pairingTopic:o,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:a,scopedProperties:c,relays:u,authentication:d,walletPay:f}=n,p=d?.[0]?.ttl||$o.wc_sessionPropose.req.ttl||It.FIVE_MINUTES;this.validateRequestExpiry(p);let h=o,y,w=!1;try{if(h){let M=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=M.active}}catch(M){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),M}if(!h||!w){let{topic:M,uri:N}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});h=M,y=N}if(!h){let{message:M}=Se("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(M)}let x=await this.client.core.crypto.generateKeyPair(),v=ln(p),T={requiredNamespaces:s,optionalNamespaces:i,relays:u??[{protocol:sU}],proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:v,pairingTopic:h,...a&&{sessionProperties:a},...c&&{scopedProperties:c},id:Tn(),...(d||f)&&{requests:{authentication:d?.map(M=>{let{domain:N,chains:L,nonce:P,uri:R,exp:I,nbf:B,type:C,statement:A,requestId:U,resources:H,signatureTypes:k}=M;return{domain:N,chains:L,nonce:P,type:C??"caip122",aud:R,version:"1",iat:new Date().toISOString(),exp:I,nbf:B,statement:A,requestId:U,resources:H,signatureTypes:k}}),walletPay:f}}},E=ir("session_connect",T.id),{reject:S,resolve:_,done:O}=yf(p,Aee),D=({id:M})=>{if(M===T.id){this.client.events.off("proposal_expire",D);let N=this.pendingSessions.get(T.id);if(N){let{sessionTopic:L,publicKey:P}=N;Promise.all([this.client.core.relayer.unsubscribe(L),this.client.core.crypto.keychain.has(L)?this.client.core.crypto.deleteSymKey(L):Promise.resolve(),this.client.core.crypto.keychain.has(P)?this.client.core.crypto.deleteKeyPair(P):Promise.resolve()]).catch(R=>this.client.logger.warn(R))}this.pendingSessions.delete(T.id),this.events.emit(E,{error:{message:Aee,code:0}})}};return this.client.events.on("proposal_expire",D),this.events.once(E,({error:M,session:N})=>{this.client.events.off("proposal_expire",D),M?S(M):N&&_(N)}),await this.setProposal(T.id,T),await this.sendProposeSession({proposal:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:T.id}}}).catch(M=>{throw this.deleteProposal(T.id),M}),{uri:y,approval:O}},this.pair=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}},this.approve=async r=>{let n=this.client.core.eventClient.createEvent({properties:{topic:r?.id?.toString(),trace:[Ya.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(D){throw n.setError(Sh.no_internet_connection),D}try{await this.isValidProposalId(r?.id)}catch(D){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),n.setError(Sh.proposal_not_found),D}try{await this.isValidApprove(r)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),n.setError(Sh.session_approve_namespace_validation_failure),D}let{id:o,relayProtocol:s,namespaces:i,sessionProperties:a,scopedProperties:c,sessionConfig:u,proposalRequestsResponses:d}=r,f=this.client.proposal.get(o);this.client.core.eventClient.deleteEvent({eventId:n.eventId});let{pairingTopic:p,proposer:h,requiredNamespaces:y,optionalNamespaces:w}=f,x=this.client.core.eventClient?.getEvent({topic:p});x||(x=this.client.core.eventClient?.createEvent({type:Ya.session_approve_started,properties:{topic:p,trace:[Ya.session_approve_started,Ya.session_namespaces_validation_success]}}));let v=await this.client.core.crypto.generateKeyPair(),T=h.publicKey,E=await this.client.core.crypto.generateSharedKey(v,T),S={relay:{protocol:s??"irn"},namespaces:i,controller:{publicKey:v,metadata:this.client.metadata},expiry:ln(ww),...a&&{sessionProperties:a},...c&&{scopedProperties:c},...u&&{sessionConfig:u},proposalRequestsResponses:d},_=Dr.relay;x.addTrace(Ya.subscribing_session_topic);try{await this.client.core.relayer.subscribe(E,{transportType:_,internal:{skipSubscribe:!0}})}catch(D){throw x.setError(Sh.subscribe_session_topic_failure),D}x.addTrace(Ya.subscribe_session_topic_success);let O={...S,topic:E,requiredNamespaces:y,optionalNamespaces:w,pairingTopic:p,acknowledged:!1,self:S.controller,peer:{publicKey:h.publicKey,metadata:h.metadata},controller:v,transportType:Dr.relay,authentication:d?.authentication,walletPayResult:d?.walletPay};await this.client.session.set(E,O),x.addTrace(Ya.store_session);try{await this.sendApproveSession({sessionTopic:E,proposal:f,pairingProposalResponse:{relay:{protocol:s??"irn"},responderPublicKey:v},sessionSettleRequest:S,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:o,...this.getTVFApproveParams(O)}}}),x.addTrace(Ya.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(E,Sr("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(E),D}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:h.metadata}),await this.deleteProposal(o),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(E,ln(ww)),{topic:E,acknowledged:()=>Promise.resolve(this.client.session.get(E))}},this.reject=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(i){throw this.client.logger.error("reject() -> isValidReject() failed"),i}let{id:n,reason:o}=r,s;try{s=this.client.proposal.get(n).pairingTopic}catch(i){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),i}s&&await this.sendError({id:n,topic:s,error:o,rpcOpts:$o.wc_sessionPropose.reject}),await this.deleteProposal(n)},this.update=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}let{topic:n,namespaces:o}=r,{done:s,resolve:i,reject:a}=yf(It.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tn(),u=_n().toString(),d=this.client.session.get(n).namespaces;return this.events.once(ir("session_update",c),({error:f})=>{f?a(f):i()}),await this.client.session.update(n,{namespaces:o}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:o},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:d}),a(f)}),{acknowledged:s}},this.extend=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}let{topic:n}=r,o=Tn(),{done:s,resolve:i,reject:a}=yf(It.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ir("session_extend",o),({error:c})=>{c?a(c):i()}),await this.setExpiry(n,ln(ww)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:o,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}},this.request=async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(x){throw this.client.logger.error("request() -> isValidRequest() failed"),x}let{chainId:n,request:o,topic:s,expiry:i=$o.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=Tn(),u=_n().toString(),{done:d,resolve:f,reject:p}=yf(i,"Request expired. Please try again.");this.events.once(ir("session_request",c),({error:x,result:v})=>{x?p(x):f(v)});let h="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:{...o,expiryTimestamp:ln(i)},chainId:n},expiry:i,throwOnFailedPublish:!0,appLink:y}).catch(x=>p(x)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),await d();let w={request:{...o,expiryTimestamp:ln(i)},chainId:n};return await Promise.all([new Promise(async x=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:w,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:s,request:o,chainId:n,id:c}),x()}),new Promise(async x=>{if(!a.sessionConfig?.disableDeepLink){let v=await dQ(this.client.core.storage,Eee);await uQ({id:c,topic:s,wcDeepLink:v})}x()}),d()]).then(x=>x[2])},this.respond=async r=>{this.isInitialized();let n=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||r?.response?.id?.toString(),trace:[Ya.session_request_response_started]}});try{await this.isValidRespond(r)}catch(u){throw n.addTrace(u?.message),n.setError(Sh.session_request_response_validation_failure),u}n.addTrace(Ya.session_request_response_validation_success);let{topic:o,response:s}=r,{id:i}=s,a=this.client.session.get(o);a.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{n.addTrace(Ya.session_request_response_publish_started),Jr(s)?await this.sendResult({id:i,topic:o,result:s.result,throwOnFailedPublish:!0,appLink:c}):Ir(s)&&await this.sendError({id:i,topic:o,error:s.error,appLink:c}),this.cleanupAfterResponse(r)}catch(u){throw n.addTrace(u?.message),n.setError(Sh.session_request_response_publish_failure),u}},this.ping=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(o){throw this.client.logger.error("ping() -> isValidPing() failed"),o}let{topic:n}=r;if(this.client.session.keys.includes(n)){let o=Tn(),s=_n().toString(),{done:i,resolve:a,reject:c}=yf(It.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ir("session_ping",o),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))},this.emit=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);let{topic:n,event:o,chainId:s}=r,i=_n().toString(),a=Tn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:o,chainId:s},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:a})},this.disconnect=async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);let{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Sr("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{let{message:o}=Se("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(o)}},this.find=r=>(this.isInitialized(),this.client.session.getAll().filter(n=>HQ(n,r))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(r,n)=>{this.isInitialized(),this.isValidAuthenticate(r);let o=n&&this.client.core.linkModeSupportedApps.includes(n)&&this.client.metadata.redirect?.linkMode,s=o?Dr.link_mode:Dr.relay;s===Dr.relay&&await this.confirmOnlineStateOrThrow();let{chains:i,statement:a="",uri:c,domain:u,nonce:d,type:f,exp:p,nbf:h,methods:y=[],expiry:w}=r,x=[...r.resources||[]],{topic:v,uri:T}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:s});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:T}}),this.client.auth.authKeys.keys.includes(Th)){let{responseTopic:H,publicKey:k}=this.client.auth.authKeys.get(Th);H&&(await this.client.core.relayer.unsubscribe(H).catch(F=>this.client.logger.warn(F)),await this.client.auth.pairingTopics.delete(H,{message:"replaced",code:0}).catch(F=>this.client.logger.warn(F))),k&&this.client.core.crypto.keychain.has(k)&&await this.client.core.crypto.deleteKeyPair(k)}let E=await this.client.core.crypto.generateKeyPair(),S=rw(E);if(await Promise.all([this.client.auth.authKeys.set(Th,{responseTopic:S,publicKey:E}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:v})]),await this.client.core.relayer.subscribe(S,{transportType:s}),this.client.logger.info(`sending request to new pairing topic: ${v}`),y.length>0){let{namespace:H}=Lc(i[0]),k=vQ(H,"request",y);W8(x)&&(k=EQ(k,x.pop())),x.push(k)}let _=w&&w>$o.wc_sessionAuthenticate.req.ttl?w:$o.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:f??"caip122",chains:i,statement:a,aud:c,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:p,nbf:h,resources:x},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:ln(_)},D={eip155:{chains:i,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},M={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:ln($o.wc_sessionPropose.req.ttl),id:Tn()},{done:N,resolve:L,reject:P}=yf(_,"Request expired"),R=Tn(),I=ir("session_connect",M.id),B=ir("session_request",R),C=async({error:H,session:k})=>{this.events.off(B,A),H?P(H):k&&L({session:k})},A=async H=>{if(await this.deletePendingAuthRequest(R,{message:"fulfilled",code:0}),H.error){let X=Sr("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return H.error.code===X.code?void 0:(this.events.off(I,C),P(H.error.message))}await this.deleteProposal(M.id),this.events.off(I,C);let{cacaos:k,responder:F}=H.result,j=[],W=[];for(let X of k){await nk({cacao:X,projectId:this.client.core.projectId})||(this.client.logger.error(X,"Signature verification failed"),P(Sr("SESSION_SETTLEMENT_FAILED","Signature verification failed")));let{p:pe}=X,me=W8(pe.resources),Ne=[QC(pe.iss)],ye=q8(pe.iss);if(me){let Re=sk(me),Et=ik(me);j.push(...Re),Ne.push(...Et)}for(let Re of Ne)W.push(`${Re}:${ye}`)}let ae=await this.client.core.crypto.generateSharedKey(E,F.publicKey),te;j.length>0&&(te={topic:ae,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:F,controller:F.publicKey,expiry:ln(ww),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:hk([...new Set(j)],[...new Set(W)]),transportType:s},await this.client.core.relayer.subscribe(ae,{transportType:s}),await this.client.session.set(ae,te),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:F.metadata}),te=this.client.session.get(ae)),this.client.metadata.redirect?.linkMode&&F.metadata.redirect?.linkMode&&F.metadata.redirect?.universal&&n&&(this.client.core.addLinkModeSupportedApp(F.metadata.redirect.universal),this.client.session.update(ae,{transportType:Dr.link_mode})),L({auths:k,session:te})};this.events.once(I,C),this.events.once(B,A);let U;try{if(o){let H=dr("wc_sessionAuthenticate",O,R);this.client.core.history.set(v,H);let k=await this.client.core.crypto.encode("",H,{type:tw,encoding:wf});U=G8(n,v,k)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:O,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:R}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:M,expiry:$o.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:M.id})])}catch(H){throw this.events.off(I,C),this.events.off(B,A),H}return await this.setProposal(M.id,M),await this.setAuthRequest(R,{request:{...O,verifyContext:{}},pairingTopic:v,transportType:s}),{uri:U??T,response:N}},this.approveSessionAuthenticate=async r=>{let{id:n,auths:o}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ih.authenticated_session_approve_started]}});try{this.isInitialized()}catch(x){throw s.setError(yw.no_internet_connection),x}let i=this.getPendingAuthRequest(n);if(!i)throw s.setError(yw.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);let a=i.transportType||Dr.relay;a===Dr.relay&&await this.confirmOnlineStateOrThrow();let c=i.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=rw(c),f={type:Mc,receiverPublicKey:c,senderPublicKey:u},p=[],h=[];for(let x of o){if(!await nk({cacao:x,projectId:this.client.core.projectId})){s.setError(yw.invalid_cacao);let _=Sr("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:_,encodeOpts:f}),new Error(_.message)}s.addTrace(Ih.cacaos_verified);let{p:v}=x,T=W8(v.resources),E=[QC(v.iss)],S=q8(v.iss);if(T){let _=sk(T),O=ik(T);p.push(..._),E.push(...O)}for(let _ of E)h.push(`${_}:${S}`)}let y=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Ih.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:y,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:i.requester.metadata},controller:c,expiry:ln(ww),authentication:o,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:i.pairingTopic,namespaces:hk([...new Set(p)],[...new Set(h)]),transportType:a},s.addTrace(Ih.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(x){throw s.setError(yw.subscribe_authenticated_session_topic_failure),x}s.addTrace(Ih.subscribe_authenticated_session_topic_success),await this.client.session.set(y,w),s.addTrace(Ih.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:i.pairingTopic,metadata:i.requester.metadata})}s.addTrace(Ih.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:o,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(i.requester.metadata,a)})}catch(x){throw s.setError(yw.authenticated_session_approve_publish_failure),x}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:i.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:w}},this.rejectSessionAuthenticate=async r=>{this.isInitialized();let{id:n,reason:o}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===Dr.relay&&await this.confirmOnlineStateOrThrow();let i=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=rw(i),u={type:Mc,receiverPublicKey:i,senderPublicKey:a};await this.sendError({id:n,topic:c,error:o,encodeOpts:u,rpcOpts:$o.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)},this.formatAuthMessage=r=>{this.isInitialized();let{request:n,iss:o}=r;return ok(n,o)},this.processRelayMessageCache=()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{let r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)},this.cleanupDuplicatePairings=async r=>{if(r.pairingTopic)try{let n=this.client.core.pairing.pairings.get(r.pairingTopic),o=this.client.core.pairing.pairings.getAll().filter(s=>s.peerMetadata?.url&&s.peerMetadata?.url===r.peer.metadata.url&&s.topic&&s.topic!==n.topic);if(o.length===0)return;this.client.logger.info(`Cleaning up ${o.length} duplicate pairing(s)`),await Promise.all(o.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}},this.deleteSession=async r=>{let{topic:n,expirerHasDeleted:o=!1,emitEvent:s=!0,id:i=0}=r,{self:a}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,Sr("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),o||this.client.core.expirer.del(n),this.client.core.storage.removeItem(Eee).catch(c=>this.client.logger.warn(c)),n===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=ql.idle),await Promise.all(this.getPendingSessionRequests().filter(c=>c.topic===n).map(c=>this.deletePendingSessionRequest(c.id,Sr("USER_DISCONNECTED")))),s&&this.client.events.emit("session_delete",{id:i,topic:n})},this.deleteProposal=async(r,n)=>{if(n)try{let o=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:o.pairingTopic})?.setError(Sh.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,Sr("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")},this.deletePendingSessionRequest=async(r,n,o=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),o&&(this.sessionRequestQueue.state=ql.idle,this.client.events.emit("session_request_expire",{id:r}))},this.deletePendingAuthRequest=async(r,n,o=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),o?Promise.resolve():this.client.core.expirer.del(r)])},this.setExpiry=async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))},this.setProposal=async(r,n)=>{this.client.core.expirer.set(r,ln($o.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)},this.setAuthRequest=async(r,n)=>{let{request:o,pairingTopic:s,transportType:i=Dr.relay}=n;this.client.core.expirer.set(r,o.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:o.authPayload,requester:o.requester,expiryTimestamp:o.expiryTimestamp,id:r,pairingTopic:s,verifyContext:o.verifyContext,transportType:i})},this.setPendingSessionRequest=async r=>{let{id:n,topic:o,params:s,verifyContext:i}=r,a=s.request.expiryTimestamp||ln($o.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:o,params:s,verifyContext:i})},this.sendRequest=async r=>{let{topic:n,method:o,params:s,expiry:i,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:d,tvf:f,publishOpts:p={}}=r,h=dr(o,s,c),y,w=!!d;try{let T=w?wf:to;y=await this.client.core.crypto.encode(n,h,{encoding:T})}catch(T){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),T}let x;if($Be.includes(o)){let T=vi(JSON.stringify(h)),E=vi(y);x=await this.client.core.verify.register({id:E,decryptedId:T})}let v={...$o[o].req,...p};if(v.attestation=x,i&&(v.ttl=i),a&&(v.id=a),this.client.core.history.set(n,h),w){let T=G8(d,n,y);await global.Linking.openURL(T,this.client.name)}else v.tvf={...f,correlationId:h.id},u?(v.internal={...v.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(n,y,v)):this.client.core.relayer.publish(n,y,v).catch(T=>this.client.logger.error(T));return h.id},this.sendProposeSession=async r=>{let{proposal:n,publishOpts:o}=r,s=dr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);let i=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:to}),a=vi(JSON.stringify(s)),c=vi(i),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:i},opts:{...o,publishMethod:"wc_proposeSession",attestation:u}})},this.sendApproveSession=async r=>{let{sessionTopic:n,pairingProposalResponse:o,proposal:s,sessionSettleRequest:i,publishOpts:a}=r,c=bo(s.id,o),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:to}),d=dr("wc_sessionSettle",i,a?.id),f=await this.client.core.crypto.encode(n,d,{encoding:to});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:{...a,publishMethod:"wc_approveSession"}})},this.sendResult=async r=>{let{id:n,topic:o,result:s,throwOnFailedPublish:i,encodeOpts:a,appLink:c}=r,u=bo(n,s),d,f=c&&typeof global?.Linking<"u";try{let y=f?wf:to;d=await this.client.core.crypto.encode(o,u,{...a||{},encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${o} failed`),y}let p,h;try{p=await this.client.core.history.get(o,n);let y=p.request;try{h=this.getTVFParams(n,y.params,s)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w?.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${o}, ${n}) failed`),y}if(f){let y=G8(c,o,d);await global.Linking.openURL(y,this.client.name)}else{let y=p.request.method,w=$o[y].res;w.tvf={...h,correlationId:n},i?(w.internal={...w.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(o,d,w)):this.client.core.relayer.publish(o,d,w).catch(x=>this.client.logger.error(x))}await this.client.core.history.resolve(u)},this.sendError=async r=>{let{id:n,topic:o,error:s,encodeOpts:i,rpcOpts:a,appLink:c}=r,u=la(n,s),d,f=c&&typeof global?.Linking<"u";try{let h=f?wf:to;d=await this.client.core.crypto.encode(o,u,{...i||{},encoding:h})}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${o} failed`),h}let p;try{p=await this.client.core.history.get(o,n)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${o}, ${n}) failed`),h}if(f){let h=G8(c,o,d);await global.Linking.openURL(h,this.client.name)}else{let h=p.request.method,y=a||$o[h].res;this.client.core.relayer.publish(o,d,y)}await this.client.core.history.resolve(u)},this.cleanup=async()=>{let r=[],n=[];this.client.session.getAll().forEach(o=>{let s=!1;ca(o.expiry)&&(s=!0),this.client.core.crypto.keychain.has(o.topic)||(s=!0),s&&r.push(o.topic)}),this.client.proposal.getAll().forEach(o=>{ca(o.expiryTimestamp)&&n.push(o.id)}),await Promise.all([...r.map(o=>this.deleteSession({topic:o})),...n.map(o=>this.deleteProposal(o))])},this.onProviderMessageEvent=async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)},this.onRelayEventRequest=async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===ql.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=ql.active;let r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=ql.idle},this.processRequest=async r=>{let{topic:n,payload:o,attestation:s,transportType:i,encryptedId:a}=r,c=o.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:o,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,o);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,o);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,o);case"wc_sessionPing":return await this.onSessionPingRequest(n,o);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,o);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});case"wc_sessionEvent":return await this.onSessionEventRequest(n,o);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:o,attestation:s,encryptedId:a,transportType:i});default:return this.client.logger.info(`Unsupported request method ${c}`)}},this.onRelayEventResponse=async r=>{let{topic:n,payload:o,transportType:s}=r,i=(await this.client.core.history.get(n,o.id)).request.method;switch(i){case"wc_sessionPropose":return this.onSessionProposeResponse(n,o,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,o);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,o);case"wc_sessionExtend":return this.onSessionExtendResponse(n,o);case"wc_sessionPing":return this.onSessionPingResponse(n,o);case"wc_sessionRequest":return this.onSessionRequestResponse(n,o);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,o);default:return this.client.logger.info(`Unsupported response method ${i}`)}},this.onRelayEventUnknownPayload=r=>{let{topic:n}=r,{message:o}=Se("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(o)},this.shouldIgnorePairingRequest=r=>{let{topic:n,requestMethod:o}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(o)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i}=r,{params:a,id:c}=o;try{let u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(zl.proposal_listener_not_found)),this.isValidConnect({...o.params});let d=a.expiryTimestamp||ln($o.wc_sessionPropose.req.ttl),f={id:c,pairingTopic:n,expiryTimestamp:d,attestation:s,encryptedId:i,...a};await this.setProposal(c,f);let p=await this.getVerifyContext({attestationId:s,hash:vi(JSON.stringify(o)),encryptedId:i,metadata:f.proposer.metadata});u?.addTrace(zc.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:p})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:$o.wc_sessionPropose.autoReject}),this.client.logger.error(u)}},this.onSessionProposeResponse=async(r,n,o)=>{let{id:s}=n;if(Jr(n)){let{result:i}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:i});let a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});let c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});let u=i.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});let d=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:d,pairingTopic:r,proposalId:s,publicKey:c});let f=await this.client.core.relayer.subscribe(d,{transportType:o});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(Ir(n)){await this.deleteProposal(s);let i=ir("session_connect",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners, 954`);this.events.emit(i,{error:n.error})}},this.onSessionSettleRequest=async(r,n)=>{let{id:o,params:s}=n;try{this.isValidSessionSettleRequest(s);let{relay:i,controller:a,expiry:c,namespaces:u,sessionProperties:d,scopedProperties:f,sessionConfig:p,proposalRequestsResponses:h}=n.params,y=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!y)return this.client.logger.error(`Pending session not found for topic ${r}`);let w=this.client.proposal.get(y.proposalId),x={topic:r,relay:i,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:y.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:y.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata},...d&&{sessionProperties:d},...f&&{scopedProperties:f},...p&&{sessionConfig:p},transportType:Dr.relay,authentication:h?.authentication,walletPayResult:h?.walletPay};await this.client.session.set(x.topic,x),await this.setExpiry(x.topic,x.expiry),await this.client.core.pairing.updateMetadata({topic:y.pairingTopic,metadata:x.peer.metadata}),this.pendingSessions.delete(y.proposalId),this.deleteProposal(y.proposalId,!1),this.cleanupDuplicatePairings(x),await this.sendResult({id:n.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:x}),this.events.emit(ir("session_connect",y.proposalId),{session:x})}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}},this.onSessionSettleResponse=async(r,n)=>{let{id:o}=n;Jr(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ir("session_approve",o),{})):Ir(n)&&(await this.deleteSession({topic:r,emitEvent:!1}),this.events.emit(ir("session_approve",o),{error:n.error}))},this.onSessionUpdateRequest=async(r,n)=>{let{params:o,id:s}=n;try{let i=`${r}_session_update`,a=wh.get(i);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:Sr("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate({topic:r,...o});try{wh.set(i,s),await this.client.session.update(r,{namespaces:o.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw wh.delete(i),c}this.client.events.emit("session_update",{id:s,topic:r,params:o})}catch(i){await this.sendError({id:s,topic:r,error:i}),this.client.logger.error(i)}},this.isRequestOutOfSync=(r,n)=>n.toString().slice(0,-3){let{id:o}=n,s=ir("session_update",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_update",o),{}):Ir(n)&&this.events.emit(ir("session_update",o),{error:n.error})},this.onSessionExtendRequest=async(r,n)=>{let{id:o}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ln(ww)),await this.sendResult({id:o,topic:r,result:!0}),this.client.events.emit("session_extend",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionExtendResponse=(r,n)=>{let{id:o}=n,s=ir("session_extend",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_extend",o),{}):Ir(n)&&this.events.emit(ir("session_extend",o),{error:n.error})},this.onSessionPingRequest=async(r,n)=>{let{id:o}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:o,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:o,topic:r})}catch(s){await this.sendError({id:o,topic:r,error:s}),this.client.logger.error(s)}},this.onSessionPingResponse=(r,n)=>{let{id:o}=n,s=ir("session_ping",o);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Jr(n)?this.events.emit(ir("session_ping",o),{}):Ir(n)&&this.events.emit(ir("session_ping",o),{error:n.error})},500)},this.onSessionDeleteRequest=async(r,n)=>{let{id:o}=n;try{await this.isValidDisconnect({topic:r,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:Sr("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:o})}catch(s){this.client.logger.error(s)}},this.onSessionRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i,transportType:a}=r,{id:c,params:u}=o;try{await this.isValidRequest({topic:n,...u});let d=this.client.session.get(n),f=await this.getVerifyContext({attestationId:s,hash:vi(JSON.stringify(dr("wc_sessionRequest",u,c))),encryptedId:i,metadata:d.peer.metadata,transportType:a}),p={id:c,topic:n,params:u,verifyContext:f};await this.setPendingSessionRequest(p),a===Dr.link_mode&&d.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(d.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(p):(this.addSessionRequestToSessionRequestQueue(p),this.processSessionRequestQueue())}catch(d){await this.sendError({id:c,topic:n,error:d}),this.client.logger.error(d)}},this.onSessionRequestResponse=(r,n)=>{let{id:o}=n,s=ir("session_request",o);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Jr(n)?this.events.emit(ir("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(ir("session_request",o),{error:n.error})},this.onSessionEventRequest=async(r,n)=>{let{id:o,params:s}=n;try{let i=`${r}_session_event_${s.event.name}`,a=wh.get(i);if(a&&this.isRequestOutOfSync(a,o)){this.client.logger.info(`Discarding out of sync request - ${o}`);return}this.isValidEmit({topic:r,...s}),this.client.events.emit("session_event",{id:o,topic:r,params:s}),wh.set(i,o)}catch(i){await this.sendError({id:o,topic:r,error:i}),this.client.logger.error(i)}},this.onSessionAuthenticateResponse=(r,n)=>{let{id:o}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),Jr(n)?this.events.emit(ir("session_request",o),{result:n.result}):Ir(n)&&this.events.emit(ir("session_request",o),{error:n.error})},this.onSessionAuthenticateRequest=async r=>{let{topic:n,payload:o,attestation:s,encryptedId:i,transportType:a}=r;try{let{requester:c,authPayload:u,expiryTimestamp:d}=o.params,f=await this.getVerifyContext({attestationId:s,hash:vi(JSON.stringify(o)),encryptedId:i,metadata:c.metadata,transportType:a}),p={requester:c,pairingTopic:n,id:o.id,authPayload:u,verifyContext:f,expiryTimestamp:d};await this.setAuthRequest(o.id,{request:p,pairingTopic:n,transportType:a}),a===Dr.link_mode&&c.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:o.params,id:o.id,verifyContext:f})}catch(c){this.client.logger.error(c);let u=o.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(o.params.requester.metadata,a),p={type:Mc,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:o.id,topic:n,error:c,encodeOpts:p,rpcOpts:$o.wc_sessionAuthenticate.autoReject,appLink:f})}},this.addSessionRequestToSessionRequestQueue=r=>{this.sessionRequestQueue.queue.push(r)},this.cleanupAfterResponse=r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ql.idle,this.processSessionRequestQueue()},(0,It.toMiliseconds)(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:r,error:n})=>{let o=this.client.core.history.pending;o.length>0&&o.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ir("session_request",s.request.id),{error:n})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===ql.active){this.client.logger.info("session request queue is already active.");return}let r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}},this.emitSessionRequest=r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=ql.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{let r=this.client.core.relayer.subscriber.topics;if(r.length===0)return;let n=new Set(this.client.session.keys),o=new Set(this.client.core.pairing.pairings.keys),s=new Set([...this.pendingSessions.values()].map(a=>a.sessionTopic)),i;if(this.client.auth.authKeys.keys.includes(Th)){let{responseTopic:a}=this.client.auth.authKeys.get(Th);i=a}for(let a of r)if(!n.has(a)&&!o.has(a)&&!s.has(a)&&a!==i){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${a}`);try{await this.client.core.relayer.subscriber.unsubscribe(a)}catch(c){this.client.logger.warn(c,`Failed to clean up orphaned subscription: ${a}`)}}},this.onPairingCreated=r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;let n=this.client.proposal.getAll().find(o=>o.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:dr("wc_sessionPropose",{...n,requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties},n.id),attestation:n.attestation,encryptedId:n.encryptedId})},this.isValidConnect=async r=>{if(!as(r)){let{message:u}=Se("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}let{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:s,sessionProperties:i,scopedProperties:a,relays:c}=r;if(In(n)||await this.isValidPairingTopic(n),!WQ(c,!0)){let{message:u}=Se("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(o&&!In(o)&&Ka(o)!==0){let u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(o,"requiredNamespaces")}if(s&&!In(s)&&Ka(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),i&&!In(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!In(a)){this.validateSessionProps(a,"scopedProperties");let u=Object.keys(o||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(d=>u.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}},this.validateNamespaces=(r,n)=>{let o=qQ(r,"connect()",n);if(o)throw new Error(o.message)},this.isValidApprove=async r=>{if(!as(r))throw new Error(Se("MISSING_OR_INVALID",`approve() params: ${r}`).message);let{id:n,namespaces:o,relayProtocol:s,sessionProperties:i,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);let c=this.client.proposal.get(n),u=eS(o,"approve()");if(u)throw new Error(u.message);let d=wk(c.requiredNamespaces,o,"approve()");if(d)throw new Error(d.message);if(!gn(s,!0)){let{message:f}=Se("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(i&&!In(i)&&this.validateSessionProps(i,"sessionProperties"),a&&!In(a)){this.validateSessionProps(a,"scopedProperties");let f=new Set(Object.keys(o));if(!Object.keys(a).every(p=>f.has(p.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}},this.isValidReject=async r=>{if(!as(r)){let{message:s}=Se("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}let{id:n,reason:o}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!ZQ(o)){let{message:s}=Se("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(o)}`);throw new Error(s)}},this.isValidSessionSettleRequest=r=>{if(!as(r)){let{message:u}=Se("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}let{relay:n,controller:o,namespaces:s,expiry:i}=r;if(!gk(n)){let{message:u}=Se("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}let a=VQ(o,"onSessionSettleRequest()");if(a)throw new Error(a.message);let c=eS(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ca(i)){let{message:u}=Se("EXPIRED","onSessionSettleRequest()");throw new Error(u)}},this.isValidUpdate=async r=>{if(!as(r)){let{message:c}=Se("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}let{topic:n,namespaces:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let s=this.client.session.get(n),i=eS(o,"update()");if(i)throw new Error(i.message);let a=wk(s.requiredNamespaces,o,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(o)}let{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)},this.isValidRequest=async r=>{if(!as(r)){let{message:c}=Se("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}let{topic:n,request:o,chainId:s,expiry:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);let{namespaces:a}=this.client.session.get(n);if(!yk(a,s)){let{message:c}=Se("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!GQ(o)){let{message:c}=Se("MISSING_OR_INVALID",`request() ${JSON.stringify(o)}`);throw new Error(c)}if(!QQ(a,s,o.method)){let{message:c}=Se("MISSING_OR_INVALID",`request() method: ${o.method}`);throw new Error(c)}this.validateRequestExpiry(i)},this.isValidRespond=async r=>{if(!as(r)){let{message:i}=Se("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(i)}let{topic:n,response:o}=r;try{await this.isValidSessionTopic(n)}catch(i){throw r?.response?.id&&this.cleanupAfterResponse(r),i}if(!YQ(o)){let{message:i}=Se("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(o)}`);throw new Error(i)}let s=this.client.pendingRequest.get(o.id);if(s.topic!==n){let{message:i}=Se("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${o.id}, expected topic: ${s.topic}, received topic: ${n}`);throw new Error(i)}},this.isValidPing=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidEmit=async r=>{if(!as(r)){let{message:a}=Se("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}let{topic:n,event:o,chainId:s}=r;await this.isValidSessionTopic(n);let{namespaces:i}=this.client.session.get(n);if(!yk(i,s)){let{message:a}=Se("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!JQ(o)){let{message:a}=Se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}if(!XQ(i,s,o.name)){let{message:a}=Se("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(o)}`);throw new Error(a)}},this.isValidDisconnect=async r=>{if(!as(r)){let{message:o}=Se("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(o)}let{topic:n}=r;await this.isValidSessionOrPairingTopic(n)},this.isValidAuthenticate=r=>{let{chains:n,uri:o,domain:s,nonce:i}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!gn(o,!1))throw new Error("uri is required parameter");if(!gn(s,!1))throw new Error("domain is required parameter");if(!gn(i,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Lc(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");let{namespace:a}=Lc(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async r=>{let{attestationId:n,hash:o,encryptedId:s,metadata:i,transportType:a}=r,c={verified:{verifyUrl:i.verifyUrl||gw,validation:"UNKNOWN",origin:i.url||""}};try{if(a===Dr.link_mode){let d=this.getAppLinkIfEnabled(i,a);return c.verified.validation=d&&new URL(d).origin===new URL(i.url).origin?"VALID":"INVALID",c}let u=await this.client.core.verify.resolve({attestationId:n,hash:o,encryptedId:s,verifyUrl:i.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(i.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c},this.validateSessionProps=(r,n)=>{Object.values(r).forEach((o,s)=>{if(o==null){let{message:i}=Se("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${o} for key ${Object.keys(r)[s]}`);throw new Error(i)}})},this.getPendingAuthRequest=r=>{let n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0},this.addToRecentlyDeleted=(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let o=0,s=this.recentlyDeletedLimit/2;for(let i of this.recentlyDeletedMap.keys()){if(o++>=s)break;this.recentlyDeletedMap.delete(i)}}},this.checkRecentlyDeleted=r=>{let n=this.recentlyDeletedMap.get(r);if(n){let{message:o}=Se("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(o)}},this.isLinkModeEnabled=(r,n)=>!r||n!==Dr.link_mode?!1:this.client.metadata?.redirect?.linkMode===!0&&this.client.metadata?.redirect?.universal!==void 0&&this.client.metadata?.redirect?.universal!==""&&r?.redirect?.universal!==void 0&&r?.redirect?.universal!==""&&r?.redirect?.linkMode===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof global?.Linking<"u",this.getAppLinkIfEnabled=(r,n)=>this.isLinkModeEnabled(r,n)?r?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;let n=XB(r,"topic")||"",o=decodeURIComponent(XB(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:Dr.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:o,sessionExists:s})},this.registerLinkModeListeners=async()=>{if(j8()||gf()&&this.client.metadata.redirect?.linkMode){let r=global?.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);let n=await r.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}},this.getTVFApproveParams=r=>{try{let n=pk(r.namespaces),o=DQ(r.namespaces),s=LQ(r.namespaces),i=r.sessionProperties,a=r.scopedProperties;return{approvedChains:n,approvedMethods:o,approvedEvents:s,sessionProperties:i,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}},this.getTVFParams=(r,n,o)=>{if(!n.request?.method)return{};let s={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{let i=this.extractTxHashesFromResult(n.request,o);s.txHashes=i,s.contractAddresses=this.isValidContractData(n.request.params)?[n.request.params?.[0]?.to]:[]}catch(i){this.client.logger.warn(i,"Error getting TVF params")}return s},this.isValidContractData=r=>{if(!r)return!1;try{let n=r?.data||r?.[0]?.data;if(!n.startsWith("0x"))return!1;let o=n.slice(2);return/^[0-9a-fA-F]*$/.test(o)?o.length%2===0:!1}catch{}return!1},this.extractTxHashesFromResult=(r,n)=>{try{if(!n)return[];let o=r.method,s=MBe[o];if(o==="sui_signTransaction")return[gQ(n.transactionBytes)];if(o==="near_signTransaction")return[tk(n)];if(o==="near_signTransactions")return n.map(a=>tk(a));if(o==="xrpl_signTransactionFor"||o==="xrpl_signTransaction")return[n.tx_json?.hash];if(o==="polkadot_signTransaction")return[nX({transaction:r.params.transactionPayload,signature:n.signature})];if(o==="algo_signTxn")return zs(n)?n.map(a=>rk(a)):[rk(n)];if(o==="cosmos_signDirect")return[yQ(n)];if(o==="wallet_sendCalls")return wQ(n);if(typeof n=="string")return[n];let i=n[s.key];if(zs(i))return o==="solana_signAllTransactions"?i.map(a=>mQ(a)):i;if(typeof i=="string")return[i]}catch(o){this.client.logger.warn(o,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{let t=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(t);for(let[n,o]of Object.entries(r))for(let s of o)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(t){this.client.logger.warn(t,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){let{message:t}=Se("NOT_INITIALIZED",this.name);throw new Error(t)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(yn.message,t=>{this.onProviderMessageEvent(t)})}async onRelayMessage(t){let{topic:r,message:n,attestation:o,transportType:s}=t,{publicKey:i}=this.client.auth.authKeys.keys.includes(Th)?this.client.auth.authKeys.get(Th):{publicKey:void 0};try{let a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:i,encoding:s===Dr.link_mode?wf:to});Hc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:o,transportType:s,encryptedId:vi(n)})):ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(pa.expired,async t=>{let{topic:r,id:n}=YC(t.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Se("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Se("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(t){this.client.logger.warn(t)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Ch.create,t=>this.onPairingCreated(t)),this.client.core.pairing.events.on(Ch.delete,t=>{this.addToRecentlyDeleted(t.topic,"pairing")})}isValidPairingTopic(t){if(!gn(t,!1)){let{message:r}=Se("MISSING_OR_INVALID",`pairing topic should be a string: ${t}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`pairing topic doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.core.pairing.pairings.get(t).expiry)){let{message:r}=Se("EXPIRED",`pairing topic: ${t}`);throw new Error(r)}}async isValidSessionTopic(t){if(!gn(t,!1)){let{message:r}=Se("MISSING_OR_INVALID",`session topic should be a string: ${t}`);throw new Error(r)}if(this.checkRecentlyDeleted(t),!this.client.session.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`session topic doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.session.get(t).expiry)){await this.deleteSession({topic:t});let{message:r}=Se("EXPIRED",`session topic: ${t}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(t)){let{message:r}=Se("MISSING_OR_INVALID",`session topic does not exist in keychain: ${t}`);throw await this.deleteSession({topic:t}),new Error(r)}}async isValidSessionOrPairingTopic(t){if(this.checkRecentlyDeleted(t),this.client.session.keys.includes(t))await this.isValidSessionTopic(t);else if(this.client.core.pairing.pairings.keys.includes(t))this.isValidPairingTopic(t);else if(gn(t,!1)){let{message:r}=Se("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${t}`);throw new Error(r)}else{let{message:r}=Se("MISSING_OR_INVALID",`session or pairing topic should be a string: ${t}`);throw new Error(r)}}async isValidProposalId(t){if(!KQ(t)){let{message:r}=Se("MISSING_OR_INVALID",`proposal id should be a number: ${t}`);throw new Error(r)}if(!this.client.proposal.keys.includes(t)){let{message:r}=Se("NO_MATCHING_KEY",`proposal id doesn't exist: ${t}`);throw new Error(r)}if(ca(this.client.proposal.get(t).expiryTimestamp)){await this.deleteProposal(t);let{message:r}=Se("EXPIRED",`proposal id: ${t}`);throw new Error(r)}}validateRequestExpiry(t){if(t&&!eX(t,aU)){let{message:r}=Se("MISSING_OR_INVALID",`request() expiry: ${t}. Expiry must be a number (in seconds) between ${aU.min} and ${aU.max}`);throw new Error(r)}}},lU=class extends jl{constructor(t,r){super(t,r,UBe,gU),this.core=t,this.logger=r}},uU=class extends jl{constructor(t,r){super(t,r,DBe,gU),this.core=t,this.logger=r}},dU=class extends jl{constructor(t,r){super(t,r,HBe,gU,n=>n.id),this.core=t,this.logger=r}},fU=class extends jl{constructor(t,r){super(t,r,VBe,XS,()=>Th),this.core=t,this.logger=r}},pU=class extends jl{constructor(t,r){super(t,r,jBe,XS),this.core=t,this.logger=r}},hU=class extends jl{constructor(t,r){super(t,r,qBe,XS,n=>n.id),this.core=t,this.logger=r}},mU=class{constructor(t,r){this.core=t,this.logger=r,this.authKeys=new fU(this.core,this.logger),this.pairingTopics=new pU(this.core,this.logger),this.requests=new hU(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}},WBe=class Tee extends mS{constructor(t){super(t),this.protocol=Cee,this.version=See,this.name=iU.name,this.events=new QS.EventEmitter,this.on=(n,o)=>this.events.on(n,o),this.once=(n,o)=>this.events.once(n,o),this.off=(n,o)=>this.events.off(n,o),this.removeListener=(n,o)=>this.events.removeListener(n,o),this.removeAllListeners=n=>this.events.removeAllListeners(n),this.connect=async n=>{try{return await this.engine.connect(n)}catch(o){throw this.logger.error(o.message),o}},this.pair=async n=>{try{return await this.engine.pair(n)}catch(o){throw this.logger.error(o.message),o}},this.approve=async n=>{try{return await this.engine.approve(n)}catch(o){throw this.logger.error(o.message),o}},this.reject=async n=>{try{return await this.engine.reject(n)}catch(o){throw this.logger.error(o.message),o}},this.update=async n=>{try{return await this.engine.update(n)}catch(o){throw this.logger.error(o.message),o}},this.extend=async n=>{try{return await this.engine.extend(n)}catch(o){throw this.logger.error(o.message),o}},this.request=async n=>{try{return await this.engine.request(n)}catch(o){throw this.logger.error(o.message),o}},this.respond=async n=>{try{return await this.engine.respond(n)}catch(o){throw this.logger.error(o.message),o}},this.ping=async n=>{try{return await this.engine.ping(n)}catch(o){throw this.logger.error(o.message),o}},this.emit=async n=>{try{return await this.engine.emit(n)}catch(o){throw this.logger.error(o.message),o}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(o){throw this.logger.error(o.message),o}},this.find=n=>{try{return this.engine.find(n)}catch(o){throw this.logger.error(o.message),o}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}},this.authenticate=async(n,o)=>{try{return await this.engine.authenticate(n,o)}catch(s){throw this.logger.error(s.message),s}},this.formatAuthMessage=n=>{try{return this.engine.formatAuthMessage(n)}catch(o){throw this.logger.error(o.message),o}},this.approveSessionAuthenticate=async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}},this.rejectSessionAuthenticate=async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(o){throw this.logger.error(o.message),o}},this.name=t?.name||iU.name,this.metadata=sQ(t?.metadata),this.signConfig=t?.signConfig;let r=sw({logger:t?.logger||iU.logger,name:this.name});this.logger=r,this.core=t?.core||new vee(t),this.session=new uU(this.core,this.logger),this.proposal=new lU(this.core,this.logger),this.pendingRequest=new dU(this.core,this.logger),this.engine=new cU(this),this.auth=new mU(this.core,this.logger)}static async init(t){let r=new Tee(t);return await r.initialize(),r}get context(){return sr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(t){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(t.message),t}}};var _ee=WBe;$c();cw();rI();var qee=Ht(ks(),1),Mee="error",eke="wss://relay.walletconnect.org",tke="wc",Wee="universal_provider",nI=`${tke}@2:${Wee}:`,Kee="https://rpc.walletconnect.org/v1/",Zee="generic",rke=`${Kee}bundler`,xw="call_status",nke=86400,SU={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Gee(e,t,r){let n=Lc(e);return t.rpcMap?.[n.reference]||`${Kee}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function oke(e){return e.includes(":")?e.split(":")[1]:e}function Yee(e){return e.map(t=>`${t.split(":")[0]}:${t.split(":")[1]}`)}function ske(e,t){let r=Object.keys(t.namespaces).filter(o=>o.includes(e));if(!r.length)return[];let n=[];return r.forEach(o=>{let s=t.namespaces[o].accounts;n.push(...s)}),n}function Hee(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>r?.chains?.length&&r?.chains?.length>0))}function oI(e={},t={}){let r=Hee($ee(e)),n=Hee($ee(t));return jk(r,n)}function $ee(e){let t={};if(!Ka(e))return t;for(let[r,n]of Object.entries(e)){let o=Y8(r)?[r]:n.chains,s=n.methods||[],i=n.events||[],a=n.rpcMap||{},c=H1(r);t[c]={...t[c],...n,chains:Uc(o,t[c]?.chains),methods:Uc(s,t[c]?.methods),events:Uc(i,t[c]?.events)},(Ka(a)||Ka(t[c]?.rpcMap||{}))&&(t[c].rpcMap={...a,...t[c]?.rpcMap})}return t}function Fee(e){return e.includes(":")?e.split(":")[2]:e}function zee(e){let t={};for(let[r,n]of Object.entries(e)){let o=n.methods||[],s=n.events||[],i=n.accounts||[],a=Y8(r)?[r]:n.chains?n.chains:Yee(n.accounts);t[r]={chains:a,methods:o,events:s,accounts:i}}return t}function wU(e){return typeof e=="number"?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}function ike(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)}catch{return!1}}var Jee={},vw=e=>Jee[e],bU=(e,t)=>{Jee[e]=t},Vee="eip155",ake=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],cke=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,xU=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,jee=e=>Object.keys(e).filter(t=>ake.includes(t)).reduce((t,r)=>(t[r]=lke(e[r]),t),{}),lke=e=>typeof e=="string"&&ike(e)?JSON.parse(e):e,uke=(e,t,r)=>{let{sessionProperties:n={},scopedProperties:o={}}=e,s={};if(!Ka(o)&&!Ka(n))return;let i=jee(n);for(let a of r){let c=cke(a);if(!c)continue;s[xU(c)]=i;let u=o?.[`${Vee}:${c}`];if(u){let d=u?.[`${Vee}:${c}:${t}`];s[xU(c)]={...s[xU(c)],...jee(d||u)}}}for(let[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0},vU,EU=class e{constructor(t){this.storage=t}async getItem(t){return await this.storage.getItem(t)}async setItem(t,r){return await this.storage.setItem(t,r)}async removeItem(t){return await this.storage.removeItem(t)}static getStorage(t){return vU||(vU=new e(t)),vU}};async function dke(e,t){let r=Lc(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,o=await Promise.allSettled(n.map(f=>fke(r.reference,f,t))),s=o.filter(f=>f.status==="fulfilled").map(f=>f.value).filter(f=>f);o.filter(f=>f.status==="rejected").forEach(f=>console.warn("Failed to fetch transaction receipt:",f.reason));let i=!s.length||s.some(f=>!f),a=s.every(f=>f?.status==="0x1"),c=s.every(f=>f?.status==="0x0"),u=s.some(f=>f?.status==="0x0"),d;return i?d=100:a?d=200:c?d=500:u&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:s,status:d}}async function fke(e,t,r){return await r(parseInt(e)).request(dr("eth_getTransactionReceipt",[t]))}async function pke({sendCalls:e,storage:t}){let r=await t.getItem(xw);await t.setItem(xw,{...r,[e.result.id]:{request:e.request,result:e.result,expiry:ln(nke)}})}async function hke({resultId:e,storage:t}){let r=await t.getItem(xw);if(r){delete r[e],await t.setItem(xw,r);for(let n in r)ca(r[n].expiry)&&delete r[n];await t.setItem(xw,r)}}async function mke({resultId:e,storage:t}){let r=(await t.getItem(xw))?.[e];if(r&&!ca(r.expiry))return r;await hke({resultId:e,storage:t})}var AU=class{constructor(t){this.name="eip155",this.namespace=t.namespace,this.events=vw("events"),this.client=vw("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=EU.getStorage(this.client.core.storage)}async request(t){switch(t.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(t);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(t);case"wallet_getCallsStatus":return await this.getCallStatus(t);case"wallet_sendCalls":return await this.sendCalls(t)}return this.namespace.methods.includes(t.request.method)?await this.client.request(t):this.getHttpProvider().request(t.request)}updateNamespace(t){this.namespace=Object.assign(this.namespace,t)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(parseInt(t),r);let n=this.chainId;this.chainId=parseInt(t),this.events.emit(SU.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}createHttpProvider(t,r){let n=r||Gee(`${this.name}:${t}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,vw("disableProviderPing")))}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProviders(){let t={};return this.namespace.chains.forEach(r=>{let n=parseInt(oke(r));t[n]=this.createHttpProvider(n,this.namespace.rpcMap?.[r])}),t}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(t){let r=t||this.chainId;return this.httpProviders[r]||(this.httpProviders={...this.httpProviders,[r]:this.createHttpProvider(r)},this.httpProviders[r])}async handleSwitchChain(t){let r=t.request.params?t.request.params[0]?.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;let n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:t.topic,request:{method:t.request.method,params:[{chainId:r}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(t){return this.namespace.chains.includes(`${this.name}:${t}`)}async getCapabilities(t){let r=t.request?.params?.[0],n=t.request?.params?.[1]||[];if(!r)throw new Error("Missing address parameter in `wallet_getCapabilities` request");let o=this.client.session.get(t.topic),s=o?.sessionProperties?.capabilities||{},i=n.length>0?n.join(","):`0x${this.chainId.toString(16)}`,a=`${r}${i}`,c=s?.[a];if(c)return c;let u;try{u=uke(o,r,n)}catch(f){console.warn("Failed to extract capabilities from session",f)}if(u)return u;let d=await this.client.request(t);try{await this.client.session.update(t.topic,{sessionProperties:{...o.sessionProperties||{},capabilities:{...s||{},[a]:d}}})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(t){let r=this.client.session.get(t.topic),n=r.sessionProperties?.bundler_name;if(n){let i=this.getBundlerUrl(t.chainId,n);try{return await this.getUserOperationReceipt(i,t)}catch(a){console.warn("Failed to fetch call status from bundler",a,i)}}let o=r.sessionProperties?.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,t)}catch(i){console.warn("Failed to fetch call status from custom bundler",i,o)}let s=await mke({resultId:t.request.params?.[0],storage:this.storage});if(s)try{return await dke(s,this.getHttpProvider.bind(this))}catch(i){console.warn("Failed to fetch call status from stored send calls",i,s)}if(this.namespace.methods.includes(t.request.method))return await this.client.request(t);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(t,r){let n=new URL(t),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(dr("eth_getUserOperationReceipt",[r.request.params?.[0]]))});if(!o.ok)throw new Error(`Failed to fetch user operation receipt - ${o.status}`);return await o.json()}getBundlerUrl(t,r){return`${rke}?projectId=${this.client.core.projectId}&chainId=${t}&bundler=${r}`}async sendCalls(t){let r=await this.client.request(t),n=t.request.params?.[0],o=r?.id,s=r?.capabilities||{},i=s?.caip345?.caip2,a=s?.caip345?.transactionHashes;return!o||!i||!a?.length||await pke({sendCalls:{request:n,result:r},storage:this.storage}),r}},CU=class{constructor(t){this.name=Zee,this.namespace=t.namespace,this.events=vw("events"),this.client=vw("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(t){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(t.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(t.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(t.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(t.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(t){return this.namespace.methods.includes(t.request.method)?this.client.request(t):this.getHttpProvider(t.chainId).request(t.request)}setDefaultChain(t,r){this.httpProviders[t]||this.setHttpProvider(t,r);let n=this.chainId;this.chainId=t,this.events.emit(SU.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${t}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return t.split(":")[1]}getNamespaceName(){let t=this.namespace.chains[0];if(!t)throw new Error("ChainId not found");return Lc(t).namespace}getAccounts(){let t=this.namespace.accounts;return t?[...new Set(t.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){let t={};return this.namespace?.accounts?.forEach(r=>{let n=Lc(r),o=this.namespace?.rpcMap?.[`${n.namespace}:${n.reference}`];t[n.reference]=this.createHttpProvider(r,o)}),t}getHttpProvider(t){let r=Lc(t).reference,n=this.httpProviders[r];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${t} not found`);return n}setHttpProvider(t,r){let n=this.createHttpProvider(t,r);n&&(this.httpProviders[t]=n)}createHttpProvider(t,r){let n=r||Gee(t,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${t}`);return new da(new Ja(n,vw("disableProviderPing")))}},gke=class Qee{constructor(t){this.events=new qee.default,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=t,this.logger=sw({logger:t.logger??Mee,name:this.providerOpts.name??Wee}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(t){let r=new Qee(t);return await r.initialize(),r}async request(t,r,n){let[o,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(o).request({request:{...t},chainId:`${o}:${s}`,topic:this.session.topic,expiry:n})}sendAsync(t,r,n,o){let s=new Date().getTime();this.request(t,n,o).then(i=>r(null,bo(s,i))).catch(i=>r(i,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Sr("USER_DISCONNECTED")}),await this.cleanup()}async connect(t){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=t,this.setNamespaces(t),this.cleanupPendingPairings(),!t.skipPairing)return await this.pair(t.pairingTopic)}async authenticate(t,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(t),await this.cleanupPendingPairings();let{uri:n,response:o}=await this.client.authenticate(t,r);n&&(this.uri=n,this.events.emit("display_uri",n));let s=await o();if(this.session=s.session,this.session){let i=zee(this.session.namespaces);this.namespaces=oI(this.namespaces,i),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(t,r){this.events.on(t,r)}once(t,r){this.events.once(t,r)}removeListener(t,r){this.events.removeListener(t,r)}off(t,r){this.events.off(t,r)}get isWalletConnect(){return!0}async pair(t){let{uri:r,approval:n}=await this.client.connect({pairingTopic:t,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});r&&(this.uri=r,this.events.emit("display_uri",r));let o=await n();this.session=o;let s=zee(o.namespaces);return this.namespaces=oI(this.namespaces,s),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(t,r){try{if(!this.session)return;let[n,o]=this.validateChain(t),s=this.getProvider(n);s?s.setDefaultChain(o,r):this.session&&this.logger.warn(`Provider for namespace '${n}' not found in setDefaultChain`)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(t={}){try{this.logger.info("Cleaning up inactive pairings...");let r=this.client.pairing.getAll();if(!zs(r))return;for(let n of r)t.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){if(this.client=this.providerOpts.client||await _ee.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Mee,relayUrl:this.providerOpts.relayUrl||eke,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(t){throw this.logger.error(t,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{let t=this.client.session.getAll();this.session=t[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");let t=[...new Set(Object.keys(this.session.namespaces).map(r=>H1(r)))];bU("client",this.client),bU("events",this.events),bU("disableProviderPing",this.disableProviderPing),t.forEach(r=>{if(!this.session)return;let n=ske(r,this.session);if(n?.length===0)return;let o=Yee(n),s={...oI(this.namespaces,this.optionalNamespaces)[r],accounts:n,chains:o};r==="eip155"?this.rpcProviders[r]=new AU({namespace:s}):this.rpcProviders[r]=new CU({namespace:s})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",t=>{let{topic:r}=t;r===this.session?.topic&&this.events.emit("session_ping",t)}),this.client.on("session_event",t=>{let{params:r,topic:n}=t;if(n!==this.session?.topic)return;let{event:o}=r;if(o.name==="accountsChanged"){let s=o.data;s&&zs(s)&&this.events.emit("accountsChanged",s.map(Fee))}else if(o.name==="chainChanged"){let s=r.chainId,i=r.event.data,a=H1(s),c=wU(s)!==wU(i)?`${a}:${wU(i)}`:s;this.onChainChanged({currentCaipChainId:c})}else this.events.emit(o.name,o.data);this.events.emit("session_event",t)}),this.client.on("session_update",({topic:t,params:r})=>{if(t!==this.session?.topic)return;let{namespaces:n}=r,o=this.client?.session.get(t);this.session={...o,namespaces:n},this.onSessionUpdate(),this.events.emit("session_update",{topic:t,params:r})}),this.client.on("session_delete",async t=>{t.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",t),this.events.emit("disconnect",{...Sr("USER_DISCONNECTED"),data:t.topic}))}),this.on(SU.DEFAULT_CHAIN_CHANGED,t=>{this.onChainChanged({...t,internal:!0})})}getProvider(t){return this.rpcProviders[t]||this.rpcProviders[Zee]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(t=>{this.getProvider(t).updateNamespace(this.session?.namespaces[t])})}setNamespaces(t){let{namespaces:r={},optionalNamespaces:n={},sessionProperties:o,scopedProperties:s}=t;this.optionalNamespaces=oI(r,n),this.sessionProperties=o,this.scopedProperties=s}validateChain(t){let[r,n]=t?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,n];if(r&&!Object.keys(this.namespaces||{}).map(i=>H1(i)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&n)return[r,n];let o=H1(Object.keys(this.namespaces)[0]),s=this.rpcProviders[o].getDefaultChain();return[o,s]}async requestAccounts(){let[t]=this.validateChain();return await this.getProvider(t).requestAccounts()}async onChainChanged({currentCaipChainId:t,previousCaipChainId:r,internal:n=!1}){if(!this.namespaces)return;let[o,s]=this.validateChain(t);if(s){if(this.updateNamespaceChain(o,s),n)this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:o,currentCaipChainId:t,previousCaipChainId:r});else{let i=this.getProvider(o);i?i.setDefaultChain(s):this.session&&this.logger.warn(`Provider for namespace '${o}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:t,currentCaipChainId:r,previousCaipChainId:n}){try{if(n===r)return;let o=this.session?.namespaces[t]?.accounts;if(!o)return;let s=o.filter(i=>i.includes(`${r}:`)).map(Fee);if(!zs(s))return;this.events.emit("accountsChanged",s)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(t,r){if(!this.namespaces)return;let n=this.namespaces[t]?t:`${t}:${r}`,o={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=r):this.namespaces[n]=o}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(t,r){let n=this.session?.topic||"";await this.client.core.storage.setItem(`${nI}/${t}${n}`,r)}async getFromStore(t){let r=this.session?.topic||"";return await this.client.core.storage.getItem(`${nI}/${t}${r}`)}async deleteFromStore(t){let r=this.session?.topic||"";await this.client.core.storage.removeItem(`${nI}/${t}${r}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;let t=await this.client.core.storage.getKeys();for(let r of t)r.startsWith(nI)&&await this.client.core.storage.removeItem(r)}catch(t){this.logger.warn(t,"Failed to cleanup storage")}}},Xee=gke;var qtt="wc",Wtt="ethereum_provider",Ktt=`${qtt}@2:${Wtt}:`,Ztt="https://rpc.walletconnect.org/v1/",Oq=["eth_sendTransaction","personal_sign"],Gtt=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Bq=["chainChanged","accountsChanged"],Ytt=["chainChanged","accountsChanged","message","disconnect","connect"],Jtt=async()=>{let{createAppKit:e}=await Promise.resolve().then(()=>(gAe(),mAe));return e};function PN(e){return Number(e[0].split(":")[1])}function _N(e){return`0x${e.toString(16)}`}function Qtt(e){let{chains:t,optionalChains:r,methods:n,optionalMethods:o,events:s,optionalEvents:i,rpcMap:a}=e;if(!zs(t))throw new Error("Invalid chains");let c={chains:t,methods:n||Oq,events:s||Bq,rpcMap:{...t.length?{[PN(t)]:a[PN(t)]}:{}}},u=s?.filter(h=>!Bq.includes(h)),d=n?.filter(h=>!Oq.includes(h));if(!r&&!i&&!o&&!u?.length&&!d?.length)return{required:t.length?c:void 0};let f=u?.length&&d?.length||!r,p={chains:[...new Set(f?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(o?.length?o:Gtt))],events:[...new Set(c.events.concat(i?.length?i:Ytt))],rpcMap:a};return{required:t.length?c:void 0,optional:r.length?p:void 0}}var Xtt=class wAe{constructor(){this.events=new yAe.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY=Ktt,this.on=(t,r)=>(this.events.on(t,r),this),this.once=(t,r)=>(this.events.once(t,r),this),this.removeListener=(t,r)=>(this.events.removeListener(t,r),this),this.off=(t,r)=>(this.events.off(t,r),this),this.parseAccount=t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t,this.signer={},this.rpc={}}static async init(t){let r=new wAe;return await r.initialize(t),r}async request(t,r){return await this.signer.request(t,this.formatChainId(this.chainId),r)}sendAsync(t,r,n){this.signer.sendAsync(t,r,this.formatChainId(this.chainId),n)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);let{required:r,optional:n}=Qtt(this.rpc);try{let o=await new Promise(async(i,a)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))}));let c=t?.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect({namespaces:{...r&&{[this.namespace]:r}},...n&&{optionalNamespaces:{[this.namespace]:n}},pairingTopic:t?.pairingTopic,scopedProperties:c}).then(u=>{i(u)}).catch(u=>{this.modal?.showErrorMessage("Unable to connect"),a(new Error(u.message))})});if(!o)return;let s=GB(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:_N(this.chainId)})}catch(o){throw this.signer.logger.error(o),o}finally{this.modal?.close()}}async authenticate(t,r){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{let n=await new Promise(async(s,i)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState(a=>{!a.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),i(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate({...t,chains:this.rpc.chains},r).then(a=>{s(a)}).catch(a=>{this.modal?.showErrorMessage("Unable to connect"),i(new Error(a.message))})}),o=n.session;if(o){let s=GB(o.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:s),this.setAccounts(s),this.events.emit("connect",{chainId:_N(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{this.modal?.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{let{params:r}=t,{event:n}=r;n.name==="accountsChanged"?(this.accounts=this.parseAccounts(n.data),this.events.emit("accountsChanged",this.accounts)):n.name==="chainChanged"?this.setChainId(this.formatChainId(n.data)):this.events.emit(n.name,n.data),this.events.emit("session_event",t)}),this.signer.on("accountsChanged",t=>{this.accounts=this.parseAccounts(t),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",t=>{let r=parseInt(t);this.chainId=r,this.events.emit("chainChanged",_N(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",{...Sr("USER_DISCONNECTED"),data:t.topic,name:"USER_DISCONNECTED"})}),this.signer.on("display_uri",t=>{this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){let r=t.filter(n=>this.isCompatibleChainId(n)).map(n=>this.parseChainId(n));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",_N(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){let r=this.parseChainId(t);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(t){let[r,n,o]=t.split(":");return{chainId:`${r}:${n}`,address:o}}setAccounts(t){this.accounts=t.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){let r=t?.chains??[],n=t?.optionalChains??[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");let s=r.length?t?.methods||Oq:[],i=r.length?t?.events||Bq:[],a=t?.optionalMethods||[],c=t?.optionalEvents||[],u=t?.rpcMap||this.buildRpcMap(o,t.projectId),d=t?.qrModalOptions||void 0;return{chains:r?.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:s,events:i,optionalMethods:a,optionalEvents:c,rpcMap:u,showQrModal:!!t?.showQrModal,qrModalOptions:d,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,r){let n={};return t.forEach(o=>{n[o]=this.getRpcUrl(o,r)}),n}async initialize(t){if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?PN(this.rpc.chains):PN(this.rpc.optionalChains),this.signer=await Xee.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storage:t.storage,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{let n=await Jtt(),{convertWCMToAppKitOptions:o}=await Promise.resolve().then(function(){return nrt}),s=o({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!s.networks.length)throw new Error("No networks found for WalletConnect");r=n({...s,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:this.rpc.qrModalOptions?.enableMobileFullScreen===!0})}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;let{chains:r,optionalChains:n,rpcMap:o}=t;r&&zs(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=o?.[s]||this.getRpcUrl(s)})),n&&zs(n)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=n?.map(s=>this.formatChainId(s)),n.forEach(s=>{this.rpc.rpcMap[s]=o?.[s]||this.getRpcUrl(s)}))}getRpcUrl(t,r){return this.rpc.rpcMap?.[t]||`${Ztt}?chainId=eip155:${t}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{let t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:r?.accounts),this.setAccounts(r?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(r=>this.parseAccount(r))}},bAe=Xtt;function ert(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}var trt=e=>{let[t,r]=e.split(":");return xAe({id:r,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function rrt(e){let t=e.chains?.map(trt).filter(Boolean);if(t.length===0)throw new Error("At least one chain must be specified");let r=t.find(o=>o.id===e.defaultChain?.id),n={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:ert(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:r,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:e.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:e.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){let o=[...(e.mobileWallets||[]).map(a=>({id:a.id,name:a.name,links:a.links})),...(e.desktopWallets||[]).map(a=>({id:a.id,name:a.name,links:{native:a.links.native,universal:a.links.universal}}))],s=[...n.featuredWalletIds||[],...n.excludeWalletIds||[]],i=o.filter(a=>!s.includes(a.id));i.length&&(n.customWallets=i)}return n}function xAe(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var nrt=Object.freeze({__proto__:null,convertWCMToAppKitOptions:rrt,defineChain:xAe});var ECe=Ht(bCe(),1);l();l();function xCe(e){let t=Promise.resolve(),r=o=>{let s=t.then(()=>e("storage",{method:"POST",body:JSON.stringify(o)}));return t=s.catch(()=>{}),s},n=async()=>(await t,e("storage"));return{async getKeys(){return Object.keys(await n())},async getEntries(){return Object.entries(await n())},async getItem(o){return(await n())[o]},async setItem(o,s){await r({key:o,value:s})},async removeItem(o){await r({key:o,value:null})}}}var mi,vCe,rW,Jrt=(...e)=>rW(...e);async function aFr(e){if(vCe!==e.contextKey&&(mi=null,vCe=e.contextKey),rW=e.api,g({url:e.relayUrl,authorize:()=>e.api("relay-admission",{method:"POST"})}),mi??=await bAe.init({projectId:e.projectId,customStoragePrefix:e.contextKey,chains:[e.chains[0]],optionalChains:e.chains.slice(1),methods:["personal_sign","eth_sendTransaction"],optionalMethods:[],disableProviderPing:!0,events:["accountsChanged","chainChanged"],showQrModal:!1,storage:xCe(Jrt),logger:"silent",telemetryEnabled:!1,metadata:e.metadata,rpcMap:Object.fromEntries(e.chains.map(d=>[d,`${e.runtimeUrl}/unavailable-rpc`]))}),await mi.signer.client.core.relayer.transportOpen(),mi.connected&&mi.session?.expiry>Date.now()/1e3)return mi;let t=document.createElement("dialog"),r=document.createElement("p");r.textContent="Scan with your phone wallet, then approve the connection there.";let n=document.createElement("canvas"),o=document.createElement("button");o.textContent="Cancel",o.type="button",t.append(r,n,o);let s,i=new Promise((d,f)=>{s=f}),a=()=>{mi.signer.abortPairingAttempt(),mi.signer.client.core.relayer.transportClose().catch(()=>{}),s(new Error("Wallet connection cancelled."))};o.onclick=a,t.addEventListener("cancel",a);let c=d=>{ECe.default.toCanvas(n,d,{width:280,margin:2}).catch(a),t.open||t.showModal()};mi.on("display_uri",c),document.body.append(t);let u;try{return await Promise.race([mi.connect(),i,new Promise((d,f)=>{u=setTimeout(()=>{a(),f(new Error("Wallet connection expired."))},18e4)})]),mi}finally{clearTimeout(u),mi.removeListener("display_uri",c),t.remove()}}async function cFr(e){rW=e.api;try{mi?.session&&await mi.disconnect()}finally{await mi?.signer.client.core.relayer.transportClose()}}export{aFr as connectWalletConnectEvm,cFr as disconnectWalletConnectEvm}; /*! Bundled license information: tslib/tslib.es6.js: From c283144f8d9f1d750f996b6338276fc79b9804ab Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 11:57:58 -0500 Subject: [PATCH 006/139] style(walletconnect): format Runtime transport and acceptance tests --- .../elastos-server/src/api/auth_gateway.rs | 3 +- .../api/gateway_tests/wallet/walletconnect.rs | 76 ++++++++++++++----- .../wallet/walletconnect_real_relay.rs | 35 +++++++-- .../src/api/gateway_walletconnect.rs | 2 +- .../elastos-server/src/setup/walletconnect.rs | 32 ++++---- 5 files changed, 105 insertions(+), 43 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index aebab491f..a43d8a6a8 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -6645,7 +6645,8 @@ mod tests { #[test] fn wallet_connector_bridge_refusal_is_typed_even_with_context() { - let error = anyhow::Error::new(WalletConnectorBridgeRequired).context("wallet link refused"); + let error = + anyhow::Error::new(WalletConnectorBridgeRequired).context("wallet link refused"); assert_eq!(auth_error_response(error).status(), StatusCode::FORBIDDEN); } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index e5ef05d82..a0ec745a4 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -1,7 +1,10 @@ use super::super::*; use futures_util::{SinkExt, StreamExt}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use tokio_tungstenite::{connect_async, tungstenite::{client::IntoClientRequest, Message}}; +use tokio_tungstenite::{ + connect_async, + tungstenite::{client::IntoClientRequest, Message}, +}; const INTERNET: &str = "/api/apps/wallet-walletconnect/internet"; const STORAGE: &str = "/api/apps/wallet-walletconnect/storage"; @@ -14,8 +17,17 @@ mod real_relay; async fn persistent_internet(data: &std::path::Path) -> Arc { use elastos_runtime::capability::{CapabilityManager, CapabilityStore}; use elastos_runtime::primitives::{audit::AuditLog, metrics::MetricsManager}; - let store = Arc::new(CapabilityStore::with_persistence(data.join("capability_store")).await.unwrap()); - let manager = Arc::new(CapabilityManager::load_or_generate(data, store, Arc::new(AuditLog::new()), Arc::new(MetricsManager::new()))); + let store = Arc::new( + CapabilityStore::with_persistence(data.join("capability_store")) + .await + .unwrap(), + ); + let manager = Arc::new(CapabilityManager::load_or_generate( + data, + store, + Arc::new(AuditLog::new()), + Arc::new(MetricsManager::new()), + )); Arc::new(BrowserInternetService::new(Some(manager))) } @@ -287,14 +299,13 @@ impl Fixture { relay: &str, ) -> tokio_tungstenite::WebSocketStream> { - let mut request = format!( - "ws://{}/api/apps/wallet-walletconnect/relay", - self.addr - ).into_client_request().unwrap(); - request.headers_mut().insert("origin", format!("http://{}", self.addr).parse().unwrap()); - let (mut socket, _) = connect_async(request) - .await - .unwrap(); + let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", self.addr) + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", format!("http://{}", self.addr).parse().unwrap()); + let (mut socket, _) = connect_async(request).await.unwrap(); socket .send(Message::Text( json!({"token":ticket,"relay":relay}).to_string(), @@ -325,17 +336,25 @@ async fn walletconnect_websocket_upgrade_requires_same_home_origin_and_first_fra let f = Fixture::new().await; for origin in [None, Some("null"), Some("https://other.example")] { let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) - .into_client_request().unwrap(); + .into_client_request() + .unwrap(); if let Some(origin) = origin { - request.headers_mut().insert("origin", origin.parse().unwrap()); + request + .headers_mut() + .insert("origin", origin.parse().unwrap()); } let result = connect_async(request).await; - assert!(matches!(result, Err(tokio_tungstenite::tungstenite::Error::Http(ref response)) if response.status() == StatusCode::FORBIDDEN)); + assert!( + matches!(result, Err(tokio_tungstenite::tungstenite::Error::Http(ref response)) if response.status() == StatusCode::FORBIDDEN) + ); } // This matches the browser API: same-Home Origin, no custom auth header, // and a refused first-frame ticket. Upgrading grants no Exit access. let mut socket = f.connect_ticket("refused", RELAY).await; - assert!(matches!(socket.next().await, Some(Ok(Message::Close(_))) | None)); + assert!(matches!( + socket.next().await, + Some(Ok(Message::Close(_))) | None + )); assert_eq!(f.calls.load(Ordering::SeqCst), 0); } @@ -412,9 +431,21 @@ async fn walletconnect_storage_is_principal_scoped_and_survives_service_restart( let (status, _) = f.route(&f.inbox, STORAGE, None).await; assert_ne!(status, StatusCode::OK); let other = passkey_authority_with_name_role_credential( - f.data.path(), Some("other-wc"), crate::auth::RuntimePrincipalRole::Admin, "other-wc-credential", + f.data.path(), + Some("other-wc"), + crate::auth::RuntimePrincipalRole::Admin, + "other-wc-credential", + ); + assert_ne!( + other.principal_id, + runtime_wallet_authority_for_app_token( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &f.connector + ) + .home_launch_context() + .principal_id ); - assert_ne!(other.principal_id, runtime_wallet_authority_for_app_token(f.data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &f.connector).home_launch_context().principal_id); let token = projection_launch_token_for_authority_context( f.data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, @@ -477,7 +508,11 @@ async fn walletconnect_relay_enforces_quota_and_tls_authentication() { refused.next().await, Some(Ok(Message::Close(_))) | None )); - assert_eq!(f.calls.load(Ordering::SeqCst), 3, "TLS refusal happens after Exit admission"); + assert_eq!( + f.calls.load(Ordering::SeqCst), + 3, + "TLS refusal happens after Exit admission" + ); } #[tokio::test] @@ -575,7 +610,10 @@ async fn walletconnect_refuses_malformed_writes_and_cross_principal_host_authori let (_, stored) = f.route(&f.connector, STORAGE, None).await; assert_eq!(stored, json!({})); let other = passkey_authority_with_name_role_credential( - f.data.path(), Some("different-host"), crate::auth::RuntimePrincipalRole::Admin, "different-host-credential", + f.data.path(), + Some("different-host"), + crate::auth::RuntimePrincipalRole::Admin, + "different-host-credential", ); for path in [ STORAGE, diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index f18dde740..004b48d43 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -19,7 +19,10 @@ fn relay_auth() -> String { .unwrap(), ); let data = format!("{header}.{payload}"); - format!("{data}.{}", URL_SAFE_NO_PAD.encode(key.sign(data.as_bytes()).to_bytes())) + format!( + "{data}.{}", + URL_SAFE_NO_PAD.encode(key.sign(data.as_bytes()).to_bytes()) + ) } #[tokio::test] @@ -30,7 +33,9 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { let project = std::fs::read_to_string(file).expect("read operator project file"); let project = project.trim(); assert!(project.len() >= 8 && project.len() <= 128); - assert!(project.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')); + assert!(project + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')); let mut f = Fixture::new().await; assert!(!f.addr.ends_with(":8090")); let config_path = f.data.path().join(WALLETCONNECT_CONFIG_PATH); @@ -72,14 +77,27 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { }); let registry = f.state.provider_registry.as_ref().unwrap(); registry.unregister_sub_provider("exit").await.unwrap(); - registry.register_sub_provider("exit", Arc::new(Exit { path, calls: f.calls.clone() })).await.unwrap(); + registry + .register_sub_provider( + "exit", + Arc::new(Exit { + path, + calls: f.calls.clone(), + }), + ) + .await + .unwrap(); f.allow().await; let mut url = url::Url::parse("wss://relay.walletconnect.org/").unwrap(); - url.query_pairs_mut().append_pair("projectId", project).append_pair("auth", &relay_auth()); + url.query_pairs_mut() + .append_pair("projectId", project) + .append_pair("auth", &relay_auth()); let mut socket = f.connect(&f.connector, url.as_str()).await; let first = tokio::time::timeout(Duration::from_secs(30), socket.next()).await; - assert!(matches!(first, Ok(Some(Ok(Message::Text(ref value)))) if value == "{\"ready\":true}"), - "Runtime did not confirm the authenticated upstream WebSocket upgrade"); + assert!( + matches!(first, Ok(Some(Ok(Message::Text(ref value)))) if value == "{\"ready\":true}"), + "Runtime did not confirm the authenticated upstream WebSocket upgrade" + ); // A successful relay RPC also excludes a post-upgrade authentication close. socket.send(Message::Text(json!({ "id": 1, "jsonrpc": "2.0", "method": "irn_subscribe", @@ -90,7 +108,10 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { panic!("real relay did not answer the subscription through Runtime"); }; let response: Value = serde_json::from_str(&response).expect("relay JSON response"); - assert!(response["id"] == 1 && response["result"].is_string(), "real relay subscription failed"); + assert!( + response["id"] == 1 && response["result"].is_string(), + "real relay subscription failed" + ); socket.close(None).await.unwrap(); println!("PASS: Runtime -> Exit harness -> authenticated Reown WSS upgrade and subscription; project ; ephemeral localhost port; no 401/403"); } diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 08cd08363..ecd16d459 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -1,6 +1,6 @@ //! WalletConnect transport consent. Wallet proofs and signing authority stay in wallet-provider. -use super::*; use super::gateway_browser::provider_response_data; +use super::*; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; use elastos_runtime::capability::{Action, CapabilityToken, ResourceId, TokenConstraints}; use serde_json::json; diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs index a4cc3ce85..f2657f9e0 100644 --- a/elastos/crates/elastos-server/src/setup/walletconnect.rs +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -3,21 +3,23 @@ use std::path::Path; pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, serde_json::Value)> { crate::api::gateway::ensure_wallet_connector_configured(data, "wallet-walletconnect").ok()?; - if !matches!(platform, "darwin-arm64" | "linux-amd64" | "linux-arm64") { return None; } - let socket = data.join("walletconnect-exit.sock"); - let hosts = ["relay.walletconnect.org", "relay.walletconnect.com"]; - let helper = serde_json::json!({ - "schema":"elastos.browser.local-exit.config/v1", "relay_ipc_path":socket, - "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], - "replace_existing_socket":true, - }); - let provider = serde_json::json!({"backends":[{ - "id":"walletconnect-local-exit", "kind":"stream_relay", - "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], - "adapter_ipc":{"kind":"unix_socket","path":socket}, - "relay_ipc":{"kind":"unix_socket","path":socket}, - }]}); - Some((helper, provider)) + if !matches!(platform, "darwin-arm64" | "linux-amd64" | "linux-arm64") { + return None; + } + let socket = data.join("walletconnect-exit.sock"); + let hosts = ["relay.walletconnect.org", "relay.walletconnect.com"]; + let helper = serde_json::json!({ + "schema":"elastos.browser.local-exit.config/v1", "relay_ipc_path":socket, + "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], + "replace_existing_socket":true, + }); + let provider = serde_json::json!({"backends":[{ + "id":"walletconnect-local-exit", "kind":"stream_relay", + "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], + "adapter_ipc":{"kind":"unix_socket","path":socket}, + "relay_ipc":{"kind":"unix_socket","path":socket}, + }]}); + Some((helper, provider)) } /// Keep the owner's existing Exit configuration and add only the relay-local backend. From f4ccc83ff470c0383ddb93c6d1f6026fb6bc7ec9 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:02:14 -0500 Subject: [PATCH 007/139] build(walletconnect): preserve vendored template literal whitespace --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitattributes b/.gitattributes index 6d732ee5d..33d27b9c9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,3 +7,5 @@ third-party/selkies/patches/*.patch -whitespace # Unified diff uses a single space for an unchanged blank context line. # Applied Rust is checked separately by formatting and target tests. scripts/build/crosvm-lifecycle-fds.patch whitespace=-blank-at-eol +# Minified upstream template literals retain meaningful whitespace in the bundle. +capsules/wallet-walletconnect/vendor/reown-appkit.js -whitespace linguist-generated=true From 4fda097e308c87d28852fe3063feb78684126d7c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:02:14 -0500 Subject: [PATCH 008/139] fix(release): scope WalletConnect provisioning to capsule build jobs --- .github/workflows/release-package.yml | 3 +-- scripts/ci-release-policy-test.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-package.yml b/.github/workflows/release-package.yml index 05beada41..84f59fbc5 100644 --- a/.github/workflows/release-package.yml +++ b/.github/workflows/release-package.yml @@ -624,8 +624,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} - ELASTOS_WALLETCONNECT_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} - RELEASE_PLATFORM: ${{ matrix.platform }} + RELEASE_PLATFORM: ${{ matrix.platform }} RELEASE_PREFIX: ${{ matrix.prefix }} run: | set -euo pipefail diff --git a/scripts/ci-release-policy-test.py b/scripts/ci-release-policy-test.py index 02a07b496..e8e89a9ed 100644 --- a/scripts/ci-release-policy-test.py +++ b/scripts/ci-release-policy-test.py @@ -875,6 +875,18 @@ def test_ci_actions_and_sccache_release_are_immutable(self): self.assertLess(setup_source.index('"${checksum[@]}" -c'), setup_source.index("tar -xzf")) self.assertLess(setup_source.index("tar -xzf"), setup_source.index('echo "RUSTC_WRAPPER=sccache"')) + def test_walletconnect_project_is_scoped_to_capsule_build_jobs(self): + source = (WORKFLOW.parent / "release-package.yml").read_text() + release_jobs = jobs(source) + for job, block in release_jobs.items(): + if job in {"mac", "linux"}: + self.assertEqual(block.count("secrets.REOWN_PROJECT_ID"), 1) + else: + self.assertNotIn("secrets.REOWN_PROJECT_ID", block, job) + seal = next(step for job in release_jobs for step in steps(job, release_jobs) + if step.startswith("name: hash native payloads and seal original-input receipts")) + self.assertRegex(seal, r"\n env:\n(?: [^\n]+\n)+ run:") + def test_release_builds_are_hermetic_with_fresh_outputs(self): source = (WORKFLOW.parent / "release-package.yml").read_text() validate_release_builds_are_hermetic(source) From e5116205f261db1953847a8de6664bcb75ce0a7e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:02:14 -0500 Subject: [PATCH 009/139] fix(walletconnect): select relay TLS crypto provider and trust roots explicitly --- elastos/Cargo.lock | 1 + elastos/crates/elastos-server/Cargo.toml | 1 + .../src/api/gateway_walletconnect.rs | 19 ++++++++++--------- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index 74118a8b2..c0a9d55d9 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -1846,6 +1846,7 @@ dependencies = [ "url", "wasm-encoder 0.236.1", "wasmparser 0.236.1", + "webpki-roots 1.0.10", "x-wing", "zeroize", "zip", diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index 5d11c023c..377df6694 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -32,6 +32,7 @@ axum-server = { version = "0.8", features = ["tls-rustls"] } # TLS (ring crypto provider) rustls = { version = "0.23", default-features = false, features = ["ring"] } +webpki-roots = "1" # HTTP client (for IPFS operations) reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "multipart", "rustls-tls"] } diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index ecd16d459..adbfe52ff 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -658,16 +658,10 @@ async fn transport( }; // Rustls authenticates the relay hostname using the release's root store; // Exit forwards TLS bytes and never holds WalletConnect session keys. + let config = relay_tls_config(); #[cfg(test)] - let connector = state - .walletconnect - .tls - .lock() - .unwrap() - .clone() - .map(tokio_tungstenite::Connector::Rustls); - #[cfg(not(test))] - let connector = None; + let config = state.walletconnect.tls.lock().unwrap().clone().unwrap_or(config); + let connector = Some(tokio_tungstenite::Connector::Rustls(config)); let mut request = url.as_str().into_client_request()?; request.headers_mut().insert( "origin", @@ -726,6 +720,13 @@ async fn transport( } Ok(()) } +fn relay_tls_config() -> Arc { + let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + Arc::new(rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )).with_safe_default_protocol_versions().expect("ring TLS versions") + .with_root_certificates(roots).with_no_client_auth()) +} #[cfg(not(unix))] async fn transport( _state: &GatewayState, From cf6166d7a2cd35e62cf5f171f5ea1dfda85c5431 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:04:44 -0500 Subject: [PATCH 010/139] fix(walletconnect): bound admissions and revalidate active transports without repeated SDK hashing --- .../src/api/gateway_home_wallet_connector.rs | 20 +++- .../api/gateway_tests/wallet/walletconnect.rs | 38 ++++++++ .../src/api/gateway_walletconnect.rs | 95 ++++++++++--------- 3 files changed, 105 insertions(+), 48 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index c777dd4aa..c9e09912d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -479,6 +479,21 @@ pub(super) fn require_home_wallet_connector_authority( connector_id: &str, connector_token: &str, expected_connector_id: &str, +) -> anyhow::Result { + let authority = revalidate_home_wallet_connector_authority(state, headers, schema, connector_id, connector_token, expected_connector_id)?; + ensure_wallet_connector_configured(&state.data_dir, connector_id)?; + Ok(authority) +} + +// Runtime transports verify the installed SDK at admission. Recurring checks +// still verify both live launch authorities and the configuration shape. +pub(super) fn revalidate_home_wallet_connector_authority( + state: &GatewayState, + headers: &HeaderMap, + schema: &str, + connector_id: &str, + connector_token: &str, + expected_connector_id: &str, ) -> anyhow::Result { if schema != HOME_WALLET_CONNECTOR_REQUEST_SCHEMA { anyhow::bail!("unsupported Home wallet-connector request schema"); @@ -487,7 +502,10 @@ pub(super) fn require_home_wallet_connector_authority( { anyhow::bail!("Home wallet-connector actor mismatch"); } - ensure_wallet_connector_configured(&state.data_dir, connector_id)?; + if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + let config = load_walletconnect_connector_config(&state.data_dir)?; + validate_walletconnect_connector_config(&config)?; + } let home = require_home_runtime_wallet_authority(&state.data_dir, headers)?; let connector_launch = diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index a0ec745a4..fdc2125ab 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -331,6 +331,44 @@ impl Fixture { } } +#[tokio::test] +async fn walletconnect_home_and_connector_share_one_consent_request() { + let f = Fixture::new().await; + let (status, host) = f.route(&f.connector, "/api/apps/wallet-walletconnect/host-config", Some(json!({}))).await; + assert_eq!(status, StatusCode::OK); + let (_, connector) = f.route(&f.connector, INTERNET, Some(json!({"action":"request"}))).await; + assert_eq!(host["internet"]["request"]["id"], connector["request"]["id"]); + assert_eq!(f.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn walletconnect_admitted_frames_do_not_reread_sdk_but_new_admissions_verify_it() { + let f = Fixture::new().await; + f.allow().await; + let mut socket = f.ready().await; + let sdk = f.data.path().join(WALLETCONNECT_SDK_PATH); + std::fs::rename(&sdk, sdk.with_extension("held")).unwrap(); + socket.send(Message::Text("admitted-frame".into())).await.unwrap(); + assert_eq!(socket.next().await.unwrap().unwrap(), Message::Text("admitted-frame".into())); + let (status, _) = f.route(&f.connector, "/api/apps/wallet-walletconnect/relay-admission", Some(json!({}))).await; + assert_ne!(status, StatusCode::OK); + assert_eq!(f.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn walletconnect_admission_quota_preserves_other_principals() { + let f = Fixture::new().await; + f.allow().await; + let path = "/api/apps/wallet-walletconnect/relay-admission"; + for _ in 0..8 { + assert_eq!(f.route(&f.connector, path, Some(json!({}))).await.0, StatusCode::OK); + } + assert_ne!(f.route(&f.connector, path, Some(json!({}))).await.0, StatusCode::OK); + let other = passkey_authority_with_name_role_credential(f.data.path(), Some("quota-other"), crate::auth::RuntimePrincipalRole::Admin, "quota-other-credential"); + let connector = projection_launch_token_for_authority_context(f.data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &other); + assert_eq!(f.route_as(&other.home_token, &connector, path, Some(json!({}))).await.0, StatusCode::OK); +} + #[tokio::test] async fn walletconnect_websocket_upgrade_requires_same_home_origin_and_first_frame_admission() { let f = Fixture::new().await; diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index adbfe52ff..b2887fb33 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -26,7 +26,7 @@ pub(crate) struct WalletConnectService { #[derive(Default)] struct Inner { sockets: BTreeMap, - admissions: BTreeMap, + admissions: BTreeMap, } struct SocketOwner { principal: String, @@ -108,7 +108,7 @@ fn public(c: Option<&Consent>) -> serde_json::Value { None => json!({"status":"off"}), } } -async fn check_owner(state: &GatewayState) -> anyhow::Result<()> { +async fn check_owner(state: &GatewayState, audit_success: bool) -> anyhow::Result<()> { let data = &state.data_dir; let c = load(data)? .ok_or_else(|| anyhow::anyhow!("Review WalletConnect internet access in Inbox"))?; @@ -130,12 +130,13 @@ async fn check_owner(state: &GatewayState) -> anyhow::Result<()> { state .browser_internet .capability_manager()? - .validate( + .validate_recurring( &token, &owner.principal_id, Action::Execute, &ResourceId::new(RESOURCE), None, + audit_success, ) .await?; Ok(()) @@ -219,14 +220,6 @@ pub(super) async fn answer( for socket in inner.sockets.values() { socket.cancel.send_replace(true); } - for socket in inner.sockets.values_mut() { - tokio::time::timeout( - Duration::from_secs(3), - socket.done.wait_for(|done| *done), - ) - .await??; - } - inner.sockets.clear(); if let Some(encoded) = &c.capability { let capability = CapabilityToken::from_base64(encoded).map_err(anyhow::Error::msg)?; @@ -236,6 +229,14 @@ pub(super) async fn answer( .revoke(*capability.id(), "WalletConnect internet stopped") .await?; } + for socket in inner.sockets.values_mut() { + tokio::time::timeout( + Duration::from_secs(3), + socket.done.wait_for(|done| *done), + ) + .await??; + } + inner.sockets.clear(); return Ok("WalletConnect connection turned off.".into()); } } @@ -321,26 +322,7 @@ pub(super) async fn internet( "Invalid WalletConnect internet action" ); ensure_admin_context(&state.data_dir, &authority.home_launch_context())?; - let c = load(&state.data_dir)?; - if c.as_ref().is_none_or(|c| { - c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts()) - }) { - anyhow::ensure!( - inner.sockets.values().all(|s| *s.done.borrow()), - "Finish stopping WalletConnect first" - ); - save( - &state.data_dir, - &Consent { - status: "requested".into(), - id: gateway_home_token::uuid_like_token(), - at: now_ts(), - principal: None, - proof: None, - capability: None, - }, - )?; - } + ensure_consent_request(&state, &authority.home_launch_context(), &inner)?; } Ok::<_, anyhow::Error>(public(load(&state.data_dir)?.as_ref())) } @@ -351,13 +333,30 @@ pub(super) async fn internet( } } +fn ensure_consent_request(state: &GatewayState, context: &HomeLaunchTokenContext, inner: &Inner) -> anyhow::Result<()> { + let current = load(&state.data_dir)?; + if current.as_ref().is_none_or(|c| c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts())) { + ensure_admin_context(&state.data_dir, context)?; + anyhow::ensure!(inner.sockets.values().all(|s| *s.done.borrow()), "Finish stopping WalletConnect first"); + save(&state.data_dir, &Consent { status: "requested".into(), id: gateway_home_token::uuid_like_token(), + at: now_ts(), principal: None, proof: None, capability: None })?; + } + Ok(()) +} + +async fn verify_sdk(state: &GatewayState) -> anyhow::Result<()> { + let data = state.data_dir.clone(); + tokio::task::spawn_blocking(move || ensure_wallet_connector_configured(&data, WALLET_WALLETCONNECT_CAPSULE_ID)).await??; + Ok(()) +} + fn hosted(state: &GatewayState, headers: &HeaderMap) -> anyhow::Result { let connector = headers .get("x-elastos-walletconnect-connector") .and_then(|h| h.to_str().ok()) .ok_or_else(|| anyhow::anyhow!("Home wallet connector authority is required"))?; Ok( - gateway_home_wallet_connector::require_home_wallet_connector_authority( + gateway_home_wallet_connector::revalidate_home_wallet_connector_authority( state, headers, "elastos.home.wallet-connector.effect.request/v1", @@ -370,7 +369,7 @@ fn hosted(state: &GatewayState, headers: &HeaderMap) -> anyhow::Result, headers: HeaderMap) -> Response { let result = async { - let _ = hosted(&state, &headers)?; + let authority = hosted(&state, &headers)?; + verify_sdk(&state).await?; + let principal = authority.home_launch_context().principal_id; let mut inner = state.walletconnect.inner.lock().await; - check_owner(&state).await?; - inner.admissions.retain(|_, (expiry, _)| *expiry > now_ts()); + check_owner(&state, true).await?; + inner.admissions.retain(|_, (expiry, _, _)| *expiry > now_ts()); anyhow::ensure!( - inner.admissions.len() < 128, + inner.admissions.len() < 128 && inner.admissions.values().filter(|(_, _, owner)| owner == &principal).count() < 8, "WalletConnect admission quota exceeded" ); let token = gateway_home_token::uuid_like_token(); inner .admissions - .insert(token.clone(), (now_ts() + 15, headers)); + .insert(token.clone(), (now_ts() + 15, headers, principal)); Ok::<_, anyhow::Error>(json!({"token":token})) } .await; @@ -407,12 +408,10 @@ pub(super) async fn host_config( ) -> Response { let result = async { let authority = hosted(&state, &headers)?; + if method == axum::http::Method::POST { verify_sdk(&state).await?; } let inner = state.walletconnect.inner.lock().await; - let c = load(&state.data_dir)?; - if method == axum::http::Method::POST && c.as_ref().is_none_or(|c| c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts())) { - ensure_admin_context(&state.data_dir, &authority.home_launch_context())?; - anyhow::ensure!(inner.sockets.values().all(|s| *s.done.borrow()), "Finish stopping WalletConnect first"); - save(&state.data_dir, &Consent { status:"requested".into(), id:gateway_home_token::uuid_like_token(), at:now_ts(), principal:None, proof:None, capability:None })?; + if method == axum::http::Method::POST { + ensure_consent_request(&state, &authority.home_launch_context(), &inner)?; } let config = load_walletconnect_connector_config(&state.data_dir)?; Ok::<_, anyhow::Error>(json!({"projectId":config.project_id, "principal_id":authority.home_launch_context().principal_id, @@ -554,7 +553,7 @@ async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyho let hello: RelayHello = serde_json::from_slice(&hello)?; let headers = { let mut inner = state.walletconnect.inner.lock().await; - let (expiry, headers) = inner + let (expiry, headers, _) = inner .admissions .remove(&hello.token) .ok_or_else(|| anyhow::anyhow!("Home transport admission required"))?; @@ -571,7 +570,7 @@ async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyho let completion = SocketCompletion(done); { let mut inner = state.walletconnect.inner.lock().await; - check_owner(state).await?; + check_owner(state, false).await?; inner.sockets.retain(|_, s| !*s.done.borrow()); anyhow::ensure!( inner @@ -598,6 +597,7 @@ async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyho _ = cancelled.changed() => Ok(()), result = transport(state, &headers, socket, url) => result, }; + if result.is_err() { tracing::warn!("WalletConnect relay transport failed"); } let _ = tokio::time::timeout(Duration::from_secs(1), socket.send(Message::Close(None))).await; // Turn Off can hold the lock while it waits for done, so signal before removal. drop(completion); @@ -687,7 +687,7 @@ async fn transport( tokio::select! { _ = heartbeat.tick() => { hosted(state, headers)?; - check_owner(state).await?; + check_owner(state, false).await?; check_liveness(pong.elapsed(), activity.elapsed())?; tokio::time::timeout(Duration::from_secs(5), upstream.send(Upstream::Ping(Vec::new()))).await??; } @@ -708,7 +708,7 @@ async fn transport( frame = socket.recv() => match frame.transpose()? { Some(Message::Text(text)) => { hosted(state, headers)?; - check_owner(state).await?; + check_owner(state, false).await?; activity = Instant::now(); tokio::time::timeout(Duration::from_secs(5), upstream.send(Upstream::Text(text))).await??; } @@ -720,6 +720,7 @@ async fn transport( } Ok(()) } +#[cfg(unix)] fn relay_tls_config() -> Arc { let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); Arc::new(rustls::ClientConfig::builder_with_provider(Arc::new( From 562d1cabe84064510b745c1f08a17bad8755a6fb Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:05:28 -0500 Subject: [PATCH 011/139] fix(walletconnect): recheck account chain and expiry after wallet replies --- .../browser/home-wallet-connector-host.js | 16 ++++++++-- scripts/walletconnect-home-host.test.mjs | 32 +++++++++++++++---- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/capsules/home/browser/home-wallet-connector-host.js b/capsules/home/browser/home-wallet-connector-host.js index e6296c5c4..93f0e6604 100644 --- a/capsules/home/browser/home-wallet-connector-host.js +++ b/capsules/home/browser/home-wallet-connector-host.js @@ -261,6 +261,14 @@ async function linkEvmWallet(connectorToken, provider = selectMetaMaskCompatible method: "personal_sign", params: [walletConnectSignData(challenge.message, connectorId), signer], }), 16 * 1024, "Wallet returned an invalid signature."); + if (connectorId === WALLETCONNECT_ID) { + const currentSigner = requireEvmAddress(await currentEvmAccount(provider)); + const currentChain = requireEvmChainId(await provider.request({ method: "eth_chainId" })); + ensureSameAddress(currentSigner, address, "Wallet account changed. Connect again."); + if (generation !== walletConnectGeneration || currentChain !== chainId || challenge.expires_at <= Date.now() / 1000) { + throw new Error("Wallet changed or the challenge expired. Connect again."); + } + } const verified = await runtimePost( "/api/apps/home/wallet-connector/evm/link/verify", connectorBody(connectorId, connectorToken, { @@ -329,15 +337,17 @@ async function completeApproval(connectorId, connectorToken, approvalRequestId) async function completeEvmApproval(provider, connectorToken, handoff, evmChains, connectorId = METAMASK_CONNECTOR_ID, binding) { const generation = walletConnectGeneration; - const checkBinding = async () => { + const checkBinding = async (startingRequest = true) => { if (connectorId !== WALLETCONNECT_ID) return; const chain = `eip155:${requireEvmChainId(await provider.request({ method: "eth_chainId" }))}`; + const account = requireEvmAddress(await currentEvmAccount(provider)); + ensureSameAddress(account, handoff.signer, "Wallet changed. Request a new review."); if (chain !== binding.chain_namespace || generation !== walletConnectGeneration || !Number.isSafeInteger(binding.expires_at) || binding.expires_at <= Date.now() / 1000) { throw new Error("Wallet request changed or expired. Request a new review."); } const ttl = binding.expires_at - Math.ceil(Date.now() / 1000); - if (ttl < 300) throw new Error("Wallet request expires soon. Request a fresh review."); + if (startingRequest && ttl < 300) throw new Error("Wallet request expires soon. Request a fresh review."); return ttl; }; const signer = requireEvmAddress(await currentEvmAccount(provider)); @@ -356,6 +366,7 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, method: "eth_sendTransaction", params: [handoff.transaction], }, expiry), 512, "Wallet returned an invalid transaction hash."); + await checkBinding(false); const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { payload_hash: handoff.payload_hash, signer: currentSigner, @@ -373,6 +384,7 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, const expiry = await checkBinding(); const signature = requireProviderResult(await provider.request({ method, params }, expiry), 16 * 1024, "Wallet returned an invalid signature."); + await checkBinding(false); const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { payload_hash: handoff.payload_hash, signature, diff --git a/scripts/walletconnect-home-host.test.mjs b/scripts/walletconnect-home-host.test.mjs index c0b50e103..0edf2c85a 100644 --- a/scripts/walletconnect-home-host.test.mjs +++ b/scripts/walletconnect-home-host.test.mjs @@ -13,6 +13,9 @@ const origin = "http://localhost:61180"; const connector = "wallet-walletconnect"; async function fixture(scenario) { + const clock = Date.now; + const events = new Map(); + let changed = false; globalThis.document = { querySelector() { return null; } }; globalThis.location = { origin }; globalThis.window = { addEventListener() {}, dispatchEvent() {} }; @@ -21,14 +24,20 @@ async function fixture(scenario) { const host = await import(`../capsules/home/browser/home-wallet-connector-host.js?fixture=${scenario}`); const calls = []; globalThis.__wcFixtureProvider = { - connected: true, on() {}, + connected: true, on(name, callback) { events.set(name, callback); }, async request(input, expiry) { calls.push({ ...input, expiry }); if (input.method === "eth_requestAccounts") return [address]; if (input.method === "personal_sign") return signature; - if (input.method === "eth_accounts") return [scenario === "wrong-account" ? `0x${"ab".repeat(20)}` : address]; - if (input.method === "eth_chainId") return scenario === "wrong-chain" ? "0x1" : "0x14"; - if (input.method === "eth_sendTransaction") return transactionHash; + if (input.method === "eth_accounts") return [scenario === "wrong-account" || changed && scenario === "account-change-during-send" ? `0x${"ab".repeat(20)}` : address]; + if (input.method === "eth_chainId") return scenario === "wrong-chain" || changed && scenario === "chain-change-during-send" ? "0x1" : "0x14"; + if (input.method === "eth_sendTransaction") { + changed = true; + if (scenario === "account-change-during-send") events.get("accountsChanged")?.([]); + if (scenario === "chain-change-during-send") events.get("chainChanged")?.("0x1"); + if (scenario === "expired-during-send") Date.now = () => clock() + 601000; + return transactionHash; + } throw new Error(`Unexpected wallet call: ${input.method}`); }, }; @@ -78,8 +87,10 @@ async function fixture(scenario) { requestId: "request:fixture", connectorId: scenario === "wrong-capsule" ? "wallet-metamask" : connector, connectorToken: "connector-fixture", action: scenario.startsWith("link") ? { kind: "link" } : { kind: "approve", approvalRequestId: "approval:fixture" } }; if (scenario === "injected-payload") data.action.payload = { to: "attacker" }; - assert.equal(host.handleHomeWalletConnectorEffect({ source: { postMessage: reply } }, context, data), true); - return { response: await complete, calls, routes }; + try { + assert.equal(host.handleHomeWalletConnectorEffect({ source: { postMessage: reply } }, context, data), true); + return { response: await complete, calls, routes }; + } finally { Date.now = clock; } } test("trusted Home signs the exact Runtime transaction once", async () => { @@ -99,6 +110,15 @@ for (const scenario of ["wrong-account", "wrong-chain", "wrong-capsule", "expire }); } +for (const scenario of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { + test(`trusted Home refuses completion after ${scenario}`, async () => { + const result = await fixture(scenario); + assert.equal(typeof result.response.error, "string"); + assert.equal(result.calls.filter(call => call.method === "eth_sendTransaction").length, 1); + assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 0); + }); +} + test("WalletConnect signs the exact UTF-8 ownership proof as EIP-1193 DATA", async () => { const result = await fixture("link"); assert.equal(result.response.error, undefined, result.response.error); From 8a7f35de36040e7d809d0ee95cb8c73c7e6b1e7c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:08:17 -0500 Subject: [PATCH 012/139] test(walletconnect): exercise Home review and exact handoff binding routes --- .../api/gateway_tests/wallet/connectors.rs | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 55ae43b9b..564f151ab 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1,5 +1,57 @@ use super::super::*; +#[tokio::test] +async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { + async fn call(app: &Router, home: &str, suffix: &str, input: Value) -> (StatusCode, Value) { + let response = app.clone().oneshot(test_browser_request("localhost:61180", "http://localhost:61180") + .method("POST").uri(format!("/api/apps/home/wallet-connector/approvals/wallet-approval%3Awc-reviewed/{suffix}")) + .header("x-elastos-home-token", home).header(CONTENT_TYPE, "application/json") + .body(Body::from(input.to_string())).unwrap()).await.unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024).await.unwrap(); + (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + } + for case in ["valid", "other-principal", "other-connector", "expired"] { + let dir = tempfile::tempdir().unwrap(); + let owner = passkey_authority(dir.path()); + seed_walletconnect_connector_config(dir.path()); + let connector = projection_launch_token_for_authority_context(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &owner); + let expiry = now_ts() + 600; + let payload_hash = format!("0x{}", "ab".repeat(32)); + let account = format!("wallet:eip155:20:0x{}", "12".repeat(20)); + let approval = json!({ + "request_id":"wallet-approval:wc-reviewed", "status":"pending", "intent":"publish_envelope", + "requested_by_actor":"documents", "resource":"elastos://content/publish", "reason":"Controlled proof", + "account_id":account, "address":format!("0x{}", "12".repeat(20)), "proof_type":"siwe", "chain_namespace":"eip155:20", + "connector_id":if case == "other-connector" { WALLET_METAMASK_CAPSULE_ID } else { WALLET_WALLETCONNECT_CAPSULE_ID }, + "principal_id":if case == "other-principal" { "other-principal" } else { &owner.principal_id }, + "payload_hash":payload_hash, "created_at":now_ts(), "expires_at":if case == "expired" { 0 } else { expiry }, + }); + let provider = MockWalletProvider { approvals: TokioMutex::new(vec![approval]), ..Default::default() }; + let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); + let input = json!({"schema":"elastos.home.wallet-connector.effect.request/v1", "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, "connector_token":connector}); + let (status, review) = call(&app, &owner.home_token, "review", input.clone()).await; + if case != "valid" { + assert_ne!(status, StatusCode::OK, "{case}"); + assert_ne!(call(&app, &owner.home_token, "handoff", input).await.0, StatusCode::OK, "{case}"); + continue; + } + assert_eq!(status, StatusCode::OK, "{review}"); + assert_eq!(review["account_id"], account); + for field in ["account_id", "requested_by_actor", "payload_hash"] { + let mut injected = input.clone(); injected[field] = json!("capsule-selected"); + assert_ne!(call(&app, &owner.home_token, "handoff", injected).await.0, StatusCode::OK); + } + let (status, result) = call(&app, &owner.home_token, "handoff", input).await; + assert_eq!(status, StatusCode::OK, "{result}"); + assert_eq!(result["binding"], json!({ + "principal_id":owner.principal_id, "requested_by_actor":"documents", "account_id":account, + "chain_namespace":"eip155:20", "payload_hash":payload_hash, "expires_at":expiry, + })); + assert_eq!(result["handoff"]["payload_hash"], payload_hash); + } +} + #[tokio::test] async fn test_wallet_connector_route_requires_connector_launch_token() { let dir = tempfile::tempdir().unwrap(); From f535c4dba427cea0f852a6abc1207703486e8310 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:13:07 -0500 Subject: [PATCH 013/139] fix(walletconnect): reject expired or resolved handoffs in Runtime --- .../crates/elastos-server/src/api/gateway_wallet_approvals.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index 660cd6fe9..994c31ffa 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -248,6 +248,10 @@ pub(in crate::api::gateway) async fn approve_external_wallet_request( capsule_id: &str, ) -> anyhow::Result { let request = pending_wallet_approval_request(state, authority, request_id).await?; + if capsule_id == WALLET_WALLETCONNECT_CAPSULE_ID { + anyhow::ensure!(request.status == "pending" && request.expires_at > now_ts(), + "WalletConnect request changed or expired"); + } if is_managed_wallet_proof_type(&request.proof_type) { anyhow::bail!("Use System to approve built-in wallet requests"); } From ba09f817efa94392cfd5f6576133fdf6a6bf9d00 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:14:37 -0500 Subject: [PATCH 014/139] test(walletconnect): bound the opt-in operator project file read --- .../src/api/gateway_tests/wallet/walletconnect_real_relay.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 004b48d43..57562b5bd 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -30,8 +30,9 @@ fn relay_auth() -> String { async fn walletconnect_real_project_opens_through_runtime_and_exit() { let file = std::env::var_os("ELASTOS_WALLETCONNECT_PROJECT_FILE") .expect("set ELASTOS_WALLETCONNECT_PROJECT_FILE"); - let project = std::fs::read_to_string(file).expect("read operator project file"); - let project = project.trim(); + let bytes = gateway_walletconnect::read_bytes(std::path::Path::new(&file), 129) + .expect("read bounded operator project file").expect("operator project file exists"); + let project = std::str::from_utf8(&bytes).expect("operator project file is UTF-8").trim(); assert!(project.len() >= 8 && project.len() <= 128); assert!(project .bytes() From b6624e642bf65ed2eeb040c2898da7a5a55c46ba Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:20:05 -0500 Subject: [PATCH 015/139] style(walletconnect): format review fixes and binding route tests --- .../src/api/gateway_home_wallet_connector.rs | 9 ++- .../api/gateway_tests/wallet/connectors.rs | 45 +++++++++--- .../api/gateway_tests/wallet/walletconnect.rs | 65 ++++++++++++++--- .../wallet/walletconnect_real_relay.rs | 7 +- .../src/api/gateway_wallet_approvals.rs | 6 +- .../src/api/gateway_walletconnect.rs | 70 +++++++++++++++---- 6 files changed, 161 insertions(+), 41 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index c9e09912d..77e595c34 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -480,7 +480,14 @@ pub(super) fn require_home_wallet_connector_authority( connector_token: &str, expected_connector_id: &str, ) -> anyhow::Result { - let authority = revalidate_home_wallet_connector_authority(state, headers, schema, connector_id, connector_token, expected_connector_id)?; + let authority = revalidate_home_wallet_connector_authority( + state, + headers, + schema, + connector_id, + connector_token, + expected_connector_id, + )?; ensure_wallet_connector_configured(&state.data_dir, connector_id)?; Ok(authority) } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 564f151ab..4d1814f95 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -8,14 +8,23 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { .header("x-elastos-home-token", home).header(CONTENT_TYPE, "application/json") .body(Body::from(input.to_string())).unwrap()).await.unwrap(); let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024).await.unwrap(); - (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .unwrap(); + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + ) } for case in ["valid", "other-principal", "other-connector", "expired"] { let dir = tempfile::tempdir().unwrap(); let owner = passkey_authority(dir.path()); seed_walletconnect_connector_config(dir.path()); - let connector = projection_launch_token_for_authority_context(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &owner); + let connector = projection_launch_token_for_authority_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &owner, + ); let expiry = now_ts() + 600; let payload_hash = format!("0x{}", "ab".repeat(32)); let account = format!("wallet:eip155:20:0x{}", "12".repeat(20)); @@ -27,27 +36,41 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { "principal_id":if case == "other-principal" { "other-principal" } else { &owner.principal_id }, "payload_hash":payload_hash, "created_at":now_ts(), "expires_at":if case == "expired" { 0 } else { expiry }, }); - let provider = MockWalletProvider { approvals: TokioMutex::new(vec![approval]), ..Default::default() }; + let provider = MockWalletProvider { + approvals: TokioMutex::new(vec![approval]), + ..Default::default() + }; let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); let input = json!({"schema":"elastos.home.wallet-connector.effect.request/v1", "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, "connector_token":connector}); let (status, review) = call(&app, &owner.home_token, "review", input.clone()).await; if case != "valid" { assert_ne!(status, StatusCode::OK, "{case}"); - assert_ne!(call(&app, &owner.home_token, "handoff", input).await.0, StatusCode::OK, "{case}"); + assert_ne!( + call(&app, &owner.home_token, "handoff", input).await.0, + StatusCode::OK, + "{case}" + ); continue; } assert_eq!(status, StatusCode::OK, "{review}"); assert_eq!(review["account_id"], account); for field in ["account_id", "requested_by_actor", "payload_hash"] { - let mut injected = input.clone(); injected[field] = json!("capsule-selected"); - assert_ne!(call(&app, &owner.home_token, "handoff", injected).await.0, StatusCode::OK); + let mut injected = input.clone(); + injected[field] = json!("capsule-selected"); + assert_ne!( + call(&app, &owner.home_token, "handoff", injected).await.0, + StatusCode::OK + ); } let (status, result) = call(&app, &owner.home_token, "handoff", input).await; assert_eq!(status, StatusCode::OK, "{result}"); - assert_eq!(result["binding"], json!({ - "principal_id":owner.principal_id, "requested_by_actor":"documents", "account_id":account, - "chain_namespace":"eip155:20", "payload_hash":payload_hash, "expires_at":expiry, - })); + assert_eq!( + result["binding"], + json!({ + "principal_id":owner.principal_id, "requested_by_actor":"documents", "account_id":account, + "chain_namespace":"eip155:20", "payload_hash":payload_hash, "expires_at":expiry, + }) + ); assert_eq!(result["handoff"]["payload_hash"], payload_hash); } } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index fdc2125ab..1a95d3835 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -334,10 +334,21 @@ impl Fixture { #[tokio::test] async fn walletconnect_home_and_connector_share_one_consent_request() { let f = Fixture::new().await; - let (status, host) = f.route(&f.connector, "/api/apps/wallet-walletconnect/host-config", Some(json!({}))).await; + let (status, host) = f + .route( + &f.connector, + "/api/apps/wallet-walletconnect/host-config", + Some(json!({})), + ) + .await; assert_eq!(status, StatusCode::OK); - let (_, connector) = f.route(&f.connector, INTERNET, Some(json!({"action":"request"}))).await; - assert_eq!(host["internet"]["request"]["id"], connector["request"]["id"]); + let (_, connector) = f + .route(&f.connector, INTERNET, Some(json!({"action":"request"}))) + .await; + assert_eq!( + host["internet"]["request"]["id"], + connector["request"]["id"] + ); assert_eq!(f.calls.load(Ordering::SeqCst), 0); } @@ -348,9 +359,21 @@ async fn walletconnect_admitted_frames_do_not_reread_sdk_but_new_admissions_veri let mut socket = f.ready().await; let sdk = f.data.path().join(WALLETCONNECT_SDK_PATH); std::fs::rename(&sdk, sdk.with_extension("held")).unwrap(); - socket.send(Message::Text("admitted-frame".into())).await.unwrap(); - assert_eq!(socket.next().await.unwrap().unwrap(), Message::Text("admitted-frame".into())); - let (status, _) = f.route(&f.connector, "/api/apps/wallet-walletconnect/relay-admission", Some(json!({}))).await; + socket + .send(Message::Text("admitted-frame".into())) + .await + .unwrap(); + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Text("admitted-frame".into()) + ); + let (status, _) = f + .route( + &f.connector, + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ) + .await; assert_ne!(status, StatusCode::OK); assert_eq!(f.calls.load(Ordering::SeqCst), 1); } @@ -361,12 +384,32 @@ async fn walletconnect_admission_quota_preserves_other_principals() { f.allow().await; let path = "/api/apps/wallet-walletconnect/relay-admission"; for _ in 0..8 { - assert_eq!(f.route(&f.connector, path, Some(json!({}))).await.0, StatusCode::OK); + assert_eq!( + f.route(&f.connector, path, Some(json!({}))).await.0, + StatusCode::OK + ); } - assert_ne!(f.route(&f.connector, path, Some(json!({}))).await.0, StatusCode::OK); - let other = passkey_authority_with_name_role_credential(f.data.path(), Some("quota-other"), crate::auth::RuntimePrincipalRole::Admin, "quota-other-credential"); - let connector = projection_launch_token_for_authority_context(f.data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &other); - assert_eq!(f.route_as(&other.home_token, &connector, path, Some(json!({}))).await.0, StatusCode::OK); + assert_ne!( + f.route(&f.connector, path, Some(json!({}))).await.0, + StatusCode::OK + ); + let other = passkey_authority_with_name_role_credential( + f.data.path(), + Some("quota-other"), + crate::auth::RuntimePrincipalRole::Admin, + "quota-other-credential", + ); + let connector = projection_launch_token_for_authority_context( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &other, + ); + assert_eq!( + f.route_as(&other.home_token, &connector, path, Some(json!({}))) + .await + .0, + StatusCode::OK + ); } #[tokio::test] diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 57562b5bd..ef602ab7d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -31,8 +31,11 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { let file = std::env::var_os("ELASTOS_WALLETCONNECT_PROJECT_FILE") .expect("set ELASTOS_WALLETCONNECT_PROJECT_FILE"); let bytes = gateway_walletconnect::read_bytes(std::path::Path::new(&file), 129) - .expect("read bounded operator project file").expect("operator project file exists"); - let project = std::str::from_utf8(&bytes).expect("operator project file is UTF-8").trim(); + .expect("read bounded operator project file") + .expect("operator project file exists"); + let project = std::str::from_utf8(&bytes) + .expect("operator project file is UTF-8") + .trim(); assert!(project.len() >= 8 && project.len() <= 128); assert!(project .bytes() diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index 994c31ffa..b868d3dfd 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -249,8 +249,10 @@ pub(in crate::api::gateway) async fn approve_external_wallet_request( ) -> anyhow::Result { let request = pending_wallet_approval_request(state, authority, request_id).await?; if capsule_id == WALLET_WALLETCONNECT_CAPSULE_ID { - anyhow::ensure!(request.status == "pending" && request.expires_at > now_ts(), - "WalletConnect request changed or expired"); + anyhow::ensure!( + request.status == "pending" && request.expires_at > now_ts(), + "WalletConnect request changed or expired" + ); } if is_managed_wallet_proof_type(&request.proof_type) { anyhow::bail!("Use System to approve built-in wallet requests"); diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index b2887fb33..e24cbda21 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -333,20 +333,41 @@ pub(super) async fn internet( } } -fn ensure_consent_request(state: &GatewayState, context: &HomeLaunchTokenContext, inner: &Inner) -> anyhow::Result<()> { +fn ensure_consent_request( + state: &GatewayState, + context: &HomeLaunchTokenContext, + inner: &Inner, +) -> anyhow::Result<()> { let current = load(&state.data_dir)?; - if current.as_ref().is_none_or(|c| c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts())) { + if current.as_ref().is_none_or(|c| { + c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts()) + }) { ensure_admin_context(&state.data_dir, context)?; - anyhow::ensure!(inner.sockets.values().all(|s| *s.done.borrow()), "Finish stopping WalletConnect first"); - save(&state.data_dir, &Consent { status: "requested".into(), id: gateway_home_token::uuid_like_token(), - at: now_ts(), principal: None, proof: None, capability: None })?; + anyhow::ensure!( + inner.sockets.values().all(|s| *s.done.borrow()), + "Finish stopping WalletConnect first" + ); + save( + &state.data_dir, + &Consent { + status: "requested".into(), + id: gateway_home_token::uuid_like_token(), + at: now_ts(), + principal: None, + proof: None, + capability: None, + }, + )?; } Ok(()) } async fn verify_sdk(state: &GatewayState) -> anyhow::Result<()> { let data = state.data_dir.clone(); - tokio::task::spawn_blocking(move || ensure_wallet_connector_configured(&data, WALLET_WALLETCONNECT_CAPSULE_ID)).await??; + tokio::task::spawn_blocking(move || { + ensure_wallet_connector_configured(&data, WALLET_WALLETCONNECT_CAPSULE_ID) + }) + .await??; Ok(()) } @@ -387,9 +408,17 @@ pub(super) async fn admission(State(state): State, headers: Header let principal = authority.home_launch_context().principal_id; let mut inner = state.walletconnect.inner.lock().await; check_owner(&state, true).await?; - inner.admissions.retain(|_, (expiry, _, _)| *expiry > now_ts()); + inner + .admissions + .retain(|_, (expiry, _, _)| *expiry > now_ts()); anyhow::ensure!( - inner.admissions.len() < 128 && inner.admissions.values().filter(|(_, _, owner)| owner == &principal).count() < 8, + inner.admissions.len() < 128 + && inner + .admissions + .values() + .filter(|(_, _, owner)| owner == &principal) + .count() + < 8, "WalletConnect admission quota exceeded" ); let token = gateway_home_token::uuid_like_token(); @@ -597,7 +626,9 @@ async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyho _ = cancelled.changed() => Ok(()), result = transport(state, &headers, socket, url) => result, }; - if result.is_err() { tracing::warn!("WalletConnect relay transport failed"); } + if result.is_err() { + tracing::warn!("WalletConnect relay transport failed"); + } let _ = tokio::time::timeout(Duration::from_secs(1), socket.send(Message::Close(None))).await; // Turn Off can hold the lock while it waits for done, so signal before removal. drop(completion); @@ -660,7 +691,13 @@ async fn transport( // Exit forwards TLS bytes and never holds WalletConnect session keys. let config = relay_tls_config(); #[cfg(test)] - let config = state.walletconnect.tls.lock().unwrap().clone().unwrap_or(config); + let config = state + .walletconnect + .tls + .lock() + .unwrap() + .clone() + .unwrap_or(config); let connector = Some(tokio_tungstenite::Connector::Rustls(config)); let mut request = url.as_str().into_client_request()?; request.headers_mut().insert( @@ -723,10 +760,15 @@ async fn transport( #[cfg(unix)] fn relay_tls_config() -> Arc { let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); - Arc::new(rustls::ClientConfig::builder_with_provider(Arc::new( - rustls::crypto::ring::default_provider(), - )).with_safe_default_protocol_versions().expect("ring TLS versions") - .with_root_certificates(roots).with_no_client_auth()) + Arc::new( + rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .expect("ring TLS versions") + .with_root_certificates(roots) + .with_no_client_auth(), + ) } #[cfg(not(unix))] async fn transport( From c7562691ddffe091ce269b9211b579344e8e7041 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:23:39 -0500 Subject: [PATCH 016/139] fix(walletconnect): keep TLS and WebSocket configurations distinct --- .../elastos-server/src/api/gateway_walletconnect.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index e24cbda21..c2c305c3d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -689,16 +689,16 @@ async fn transport( }; // Rustls authenticates the relay hostname using the release's root store; // Exit forwards TLS bytes and never holds WalletConnect session keys. - let config = relay_tls_config(); + let tls_config = relay_tls_config(); #[cfg(test)] - let config = state + let tls_config = state .walletconnect .tls .lock() .unwrap() .clone() - .unwrap_or(config); - let connector = Some(tokio_tungstenite::Connector::Rustls(config)); + .unwrap_or(tls_config); + let connector = Some(tokio_tungstenite::Connector::Rustls(tls_config)); let mut request = url.as_str().into_client_request()?; request.headers_mut().insert( "origin", From 0d1b5ab2d8728d72b075947edb31a86d81b721b9 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:38:30 -0500 Subject: [PATCH 017/139] fix(walletconnect): preserve returned transaction hashes across state changes --- .../browser/home-wallet-connector-host.js | 17 +++--- docs/WALLET_PROVIDER.md | 6 ++- scripts/walletconnect-home-host.test.mjs | 53 +++++++++++++++---- 3 files changed, 57 insertions(+), 19 deletions(-) diff --git a/capsules/home/browser/home-wallet-connector-host.js b/capsules/home/browser/home-wallet-connector-host.js index 93f0e6604..3797fa0ef 100644 --- a/capsules/home/browser/home-wallet-connector-host.js +++ b/capsules/home/browser/home-wallet-connector-host.js @@ -366,13 +366,16 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, method: "eth_sendTransaction", params: [handoff.transaction], }, expiry), 512, "Wallet returned an invalid transaction hash."); - await checkBinding(false); - const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { - payload_hash: handoff.payload_hash, - signer: currentSigner, - transaction_hash: transactionHash, - })); - requireApprovalCompletion(completed, connectorId, handoff.request_id); + try { + const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { + payload_hash: handoff.payload_hash, + signer: currentSigner, + transaction_hash: transactionHash, + })); + requireApprovalCompletion(completed, connectorId, handoff.request_id); + } catch { + throw new Error(`Wallet returned transaction hash ${transactionHash}. Runtime could not confirm it. Keep this hash and check it before sending again.`); + } return Object.freeze({ status: "completed", effect: "transaction" }); } const method = handoff.intent === "browser_typed_data_sign" diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 0b00ec61d..e55804d68 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -261,7 +261,11 @@ Home accepts link actions, approval IDs, and disconnect actions; Runtime and `wallet-provider` supply the exact proof or signing payload. Pairing carries connection state. Each signing request retains its principal, requesting actor, account, chain, payload hash, and expiry. Disconnect leaves linked accounts in -Wallet. Account or chain changes stop a request in progress. +Wallet. Account or chain changes stop a request before the wallet sends it. +Home passes each returned transaction hash to Runtime once, including after a +connection or account change. A completion error keeps that hash visible so the +person can check the transaction before sending again. Unused signatures and +ownership proofs still stop when the account, chain, or request expiry changes. Inbox owns internet consent through the owner's passkey. Runtime connects only to `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through diff --git a/scripts/walletconnect-home-host.test.mjs b/scripts/walletconnect-home-host.test.mjs index 0edf2c85a..e61a4f472 100644 --- a/scripts/walletconnect-home-host.test.mjs +++ b/scripts/walletconnect-home-host.test.mjs @@ -16,6 +16,13 @@ async function fixture(scenario) { const clock = Date.now; const events = new Map(); let changed = false; + const changeKind = scenario.replace(/^signature-/, ""); + const changeDuringReply = () => { + changed = true; + if (changeKind === "account-change-during-send") events.get("accountsChanged")?.([]); + if (changeKind === "chain-change-during-send") events.get("chainChanged")?.("0x1"); + if (changeKind === "expired-during-send") Date.now = () => clock() + 601000; + }; globalThis.document = { querySelector() { return null; } }; globalThis.location = { origin }; globalThis.window = { addEventListener() {}, dispatchEvent() {} }; @@ -28,14 +35,14 @@ async function fixture(scenario) { async request(input, expiry) { calls.push({ ...input, expiry }); if (input.method === "eth_requestAccounts") return [address]; - if (input.method === "personal_sign") return signature; - if (input.method === "eth_accounts") return [scenario === "wrong-account" || changed && scenario === "account-change-during-send" ? `0x${"ab".repeat(20)}` : address]; - if (input.method === "eth_chainId") return scenario === "wrong-chain" || changed && scenario === "chain-change-during-send" ? "0x1" : "0x14"; + if (input.method === "personal_sign") { + if (scenario.startsWith("signature-")) changeDuringReply(); + return signature; + } + if (input.method === "eth_accounts") return [scenario === "wrong-account" || changed && changeKind === "account-change-during-send" ? `0x${"ab".repeat(20)}` : address]; + if (input.method === "eth_chainId") return scenario === "wrong-chain" || changed && changeKind === "chain-change-during-send" ? "0x1" : "0x14"; if (input.method === "eth_sendTransaction") { - changed = true; - if (scenario === "account-change-during-send") events.get("accountsChanged")?.([]); - if (scenario === "chain-change-during-send") events.get("chainChanged")?.("0x1"); - if (scenario === "expired-during-send") Date.now = () => clock() + 601000; + changeDuringReply(); return transactionHash; } throw new Error(`Unexpected wallet call: ${input.method}`); @@ -60,7 +67,8 @@ async function fixture(scenario) { value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "evm_link_complete", connector_id: connector, status: "linked" }; } else if (path.endsWith("/review")) value = { address, chain_namespace: "eip155:20", expires_at: Math.floor(Date.now() / 1000) + 600 }; - else if (path.endsWith("/handoff")) value = { + else if (path.endsWith("/handoff")) { + value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_handoff", connector_id: connector, request_id: "approval:fixture", evm_chains: [], handoff: { schema: "elastos.wallet.webconnect_handoff/v1", request_id: "approval:fixture", intent: "transaction_intent", @@ -69,12 +77,18 @@ async function fixture(scenario) { }, binding: { principal_id: "principal-fixture", requested_by_actor: "documents", account_id: "account-fixture", chain_namespace: "eip155:20", payload_hash: payloadHash, expires_at: scenario === "expired" ? 1 : Math.floor(Date.now() / 1000) + 600 }, - }; + }; + if (scenario.startsWith("signature-")) { + delete value.handoff.transaction; + Object.assign(value.handoff, { intent: "browser_personal_sign", status: "awaiting_wallet_signature", message: "Runtime approval fixture", signature_type: "personal_sign" }); + } + } else if (path.endsWith("/complete")) { const body = JSON.parse(input.body); assert.equal(body.payload_hash, payloadHash); assert.equal(body.signer, address); assert.equal(body.transaction_hash, transactionHash); + if (scenario === "completion-refused") return { ok: false, status: 403, text: async () => "wallet approval request expired" }; value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_complete", connector_id: connector, request_id: "approval:fixture", status: "completed" }; } else throw new Error(`Unexpected Runtime route: ${path}`); @@ -111,10 +125,27 @@ for (const scenario of ["wrong-account", "wrong-chain", "wrong-capsule", "expire } for (const scenario of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { - test(`trusted Home refuses completion after ${scenario}`, async () => { + test(`trusted Home preserves a returned transaction hash after ${scenario}`, async () => { const result = await fixture(scenario); - assert.equal(typeof result.response.error, "string"); + assert.equal(result.response.error, undefined, result.response.error); assert.equal(result.calls.filter(call => call.method === "eth_sendTransaction").length, 1); + assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); + }); +} + +test("a refused transaction completion retains its hash and asks for checking before another send", async () => { + const result = await fixture("completion-refused"); + assert.ok(result.response.error.includes(transactionHash)); + assert.match(result.response.error, /Keep this hash and check it before sending again/); + assert.doesNotMatch(result.response.error, /new review/); + assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); +}); + +for (const change of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { + test(`trusted Home stops an unused signature after ${change}`, async () => { + const result = await fixture(`signature-${change}`); + assert.equal(typeof result.response.error, "string"); + assert.equal(result.calls.filter(call => call.method === "personal_sign").length, 1); assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 0); }); } From 67bdc0c21651a909fbf84c3e4e1d5098d5cb08c4 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:38:30 -0500 Subject: [PATCH 018/139] fix(walletconnect): compare handoff binding with Runtime principal and payload --- .../elastos-server/src/api/gateway_home_wallet_connector.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index 77e595c34..0baa723aa 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -410,6 +410,11 @@ pub(super) async fn home_wallet_connector_approval_handoff( "WalletConnect approval binding is missing" )); }; + if binding["principal_id"].as_str() != Some(authority.context.principal_id.as_str()) + || binding["payload_hash"] != response["handoff"]["payload_hash"] + { + return system_error_response(anyhow::anyhow!("WalletConnect approval binding mismatch")); + } response["binding"] = json!({ "principal_id":binding["principal_id"], "requested_by_actor":binding["requested_by_actor"], "account_id":binding["account_id"], "chain_namespace":binding["chain_namespace"], From 9827c4e2d1fe0db0fe80e382d45b4b4e273f1220 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:40:45 -0500 Subject: [PATCH 019/139] style(walletconnect): format the handoff binding refusal --- .../elastos-server/src/api/gateway_home_wallet_connector.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index 0baa723aa..a66e03d2f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -413,7 +413,9 @@ pub(super) async fn home_wallet_connector_approval_handoff( if binding["principal_id"].as_str() != Some(authority.context.principal_id.as_str()) || binding["payload_hash"] != response["handoff"]["payload_hash"] { - return system_error_response(anyhow::anyhow!("WalletConnect approval binding mismatch")); + return system_error_response(anyhow::anyhow!( + "WalletConnect approval binding mismatch" + )); } response["binding"] = json!({ "principal_id":binding["principal_id"], "requested_by_actor":binding["requested_by_actor"], From 51fcb7c788aa65ce37cf0bc8436a18f31bcb90bc Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:59:44 -0500 Subject: [PATCH 020/139] fix(walletconnect): validate transaction hashes before receipt reporting --- capsules/home/browser/home-wallet-connector-host.js | 5 ++++- scripts/walletconnect-home-host.test.mjs | 9 ++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/capsules/home/browser/home-wallet-connector-host.js b/capsules/home/browser/home-wallet-connector-host.js index 3797fa0ef..d4178fe02 100644 --- a/capsules/home/browser/home-wallet-connector-host.js +++ b/capsules/home/browser/home-wallet-connector-host.js @@ -365,7 +365,10 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, const transactionHash = requireProviderResult(await provider.request({ method: "eth_sendTransaction", params: [handoff.transaction], - }, expiry), 512, "Wallet returned an invalid transaction hash."); + }, expiry), 66, "Wallet returned an invalid transaction hash."); + if (!/^0x[0-9a-fA-F]{64}$/.test(transactionHash)) { + throw new Error("Wallet returned an invalid transaction hash."); + } try { const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { payload_hash: handoff.payload_hash, diff --git a/scripts/walletconnect-home-host.test.mjs b/scripts/walletconnect-home-host.test.mjs index e61a4f472..33d3a4af5 100644 --- a/scripts/walletconnect-home-host.test.mjs +++ b/scripts/walletconnect-home-host.test.mjs @@ -43,7 +43,7 @@ async function fixture(scenario) { if (input.method === "eth_chainId") return scenario === "wrong-chain" || changed && changeKind === "chain-change-during-send" ? "0x1" : "0x14"; if (input.method === "eth_sendTransaction") { changeDuringReply(); - return transactionHash; + return scenario === "invalid-hash" ? "Open the wallet's fake recovery website" : transactionHash; } throw new Error(`Unexpected wallet call: ${input.method}`); }, @@ -141,6 +141,13 @@ test("a refused transaction completion retains its hash and asks for checking be assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); }); +test("wallet-chosen text cannot appear as a returned transaction hash", async () => { + const result = await fixture("invalid-hash"); + assert.match(result.response.error, /invalid transaction hash/); + assert.doesNotMatch(result.response.error, /fake recovery website/); + assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 0); +}); + for (const change of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { test(`trusted Home stops an unused signature after ${change}`, async () => { const result = await fixture(`signature-${change}`); From 76969478655e2130133917ec9c57fdf170866cda Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 12:59:44 -0500 Subject: [PATCH 021/139] fix(walletconnect): keep the connector listening through the wallet approval window --- .../browser/wallet-walletconnect.js | 5 +- .../lib/walletconnect-connector-loader.mjs | 7 ++ ...walletconnect-connector-deadlines.test.mjs | 72 +++++++++++++++++++ 3 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 scripts/lib/walletconnect-connector-loader.mjs create mode 100644 scripts/walletconnect-connector-deadlines.test.mjs diff --git a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js index bc7013b45..97f49d186 100644 --- a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js +++ b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js @@ -7,7 +7,8 @@ const HOST_EFFECT_TYPE = "home:wallet-connector-effect"; const HOST_EFFECT_SCHEMA = "elastos.home.wallet-connector-effect/v1"; const HOST_RESULT_TYPE = "home:wallet-connector-effect-result"; const HOST_RESULT_SCHEMA = "elastos.home.wallet-connector-effect-result/v1"; -const HOST_EFFECT_TIMEOUT_MS = 180_000; +// Cover QR pairing (180 s), the Runtime approval window (600 s), and delivery. +const HOST_EFFECT_TIMEOUT_MS = 810_000; const connectButton = document.querySelector("#wallet-connect"); const statusNode = document.querySelector("#wallet-status"); const stateNode = document.querySelector("#wallet-state"); @@ -230,7 +231,7 @@ function requestHomeWalletEffect(action) { const timeout = window.setTimeout(() => { finish(); reject(new Error("Wallet request timed out.")); - }, action.kind === "status" ? 10000 : HOST_EFFECT_TIMEOUT_MS); + }, action.kind === "status" ? 10000 : ["approve", "link"].includes(action.kind) ? HOST_EFFECT_TIMEOUT_MS : 30000); const finish = () => { window.clearTimeout(timeout); window.removeEventListener("message", onMessage); diff --git a/scripts/lib/walletconnect-connector-loader.mjs b/scripts/lib/walletconnect-connector-loader.mjs new file mode 100644 index 000000000..5de26ebef --- /dev/null +++ b/scripts/lib/walletconnect-connector-loader.mjs @@ -0,0 +1,7 @@ +// Resolve the capsule's served asset import while importing its whole real module. +export function resolve(specifier, context, next) { + if (specifier.startsWith("/apps/home/home-clipboard-client.js?")) { + return next(new URL("../../capsules/home/browser/home-clipboard-client.js", import.meta.url).href, context); + } + return next(specifier, context); +} diff --git a/scripts/walletconnect-connector-deadlines.test.mjs b/scripts/walletconnect-connector-deadlines.test.mjs new file mode 100644 index 000000000..1d37651f2 --- /dev/null +++ b/scripts/walletconnect-connector-deadlines.test.mjs @@ -0,0 +1,72 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { register } from "node:module"; +register(new URL("./lib/walletconnect-connector-loader.mjs", import.meta.url)); + +class Element { + children = []; dataset = {}; listeners = new Map(); textContent = ""; + addEventListener(type, fn) { this.listeners.set(type, fn); } + append(...children) { this.children.push(...children); } + replaceChildren(...children) { this.children = children; } + closest() { return this; } +} +let sequence = 0; +const tick = () => new Promise(resolve => setImmediate(resolve)); +const transactionHash = `0x${"ab".repeat(32)}`; + +async function fixture(kind) { + const origin = "http://localhost:61183"; + const nodes = new Map(["wallet-connect", "wallet-disconnect", "wallet-connection", "wallet-status", "wallet-state", "wallet-accounts", "wallet-requests"].map(id => [`#${id}`, new Element()])); + globalThis.document = { querySelector: selector => nodes.get(selector), createElement: () => new Element() }; + const events = new Map(); const timers = new Map(); let now = 0, timerId = 0, effect; + const home = { postMessage(message) { if (message.type === "home:wallet-connector-effect") effect = message; } }; + globalThis.window = { + location: { search: `?home_origin=${encodeURIComponent(origin)}`, hash: "#home_token=deadline-fixture", origin: "null" }, + top: home, parent: home, crypto: { randomUUID: () => `deadline-${++sequence}` }, + addEventListener(type, callback) { if (!events.has(type)) events.set(type, new Set()); events.get(type).add(callback); }, + removeEventListener(type, callback) { events.get(type)?.delete(callback); }, + setTimeout(fn, ms) { timers.set(++timerId, { fn, at: now + ms }); return timerId; }, + clearTimeout(id) { timers.delete(id); }, + }; + globalThis.fetch = async path => ({ ok: true, json: async () => path.endsWith("/accounts") ? { accounts: [] } : { approval_requests: [{ + request_id: "approval:deadline", status: "pending", intent: "transaction_intent", capsule_id: "documents", chain_namespace: "eip155:20", + proof_type: "siwe", connector_id: "wallet-walletconnect", address: `0x${"12".repeat(20)}`, + }] } }); + await import(`../capsules/wallet-walletconnect/browser/wallet-walletconnect.js?deadline=${++sequence}`); + await tick(); + const root = nodes.get("#wallet-requests"); + const button = root.children[0].children.at(-1); + const pending = kind === "link" ? nodes.get("#wallet-connect").listeners.get("click")() + : root.listeners.get("click")({ target: button }); + assert.equal(effect.action.kind, kind); + return { + async advance(ms) { + now += ms; + for (const [id, timer] of [...timers]) if (timer.at <= now) { timers.delete(id); timer.fn(); } + await tick(); + }, + async reply() { + const data = { type: "home:wallet-connector-effect-result", schema: "elastos.home.wallet-connector-effect-result/v1", + requestId: effect.requestId, connectorId: "wallet-walletconnect", + ...(kind === "link" ? { result: { status: "linked" } } : { error: `Wallet returned transaction hash ${transactionHash}. Keep this hash and check it before sending again.` }), + }; + for (const fn of [...events.get("message")]) fn({ source: home, origin, data }); + await pending; + }, + pending, status: nodes.get("#wallet-status"), + }; +} + +for (const kind of ["approve", "link"]) { + test(`WalletConnect ${kind} still receives its Home reply after 180 seconds`, async () => { + const f = await fixture(kind); + await f.advance(181000); + await f.reply(); + assert.ok(kind === "link" ? f.status.textContent === "Approval method added." : f.status.textContent.includes(transactionHash), f.status.textContent); + }); +} +test("an unresponsive Home effect has a bounded screen deadline", async () => { + const f = await fixture("approve"); + await f.advance(811000); await f.pending; + assert.equal(f.status.textContent, "Wallet request timed out."); +}); From f0121051a18ecefa4a3c9ab6653be971c8c499d7 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 13:15:03 -0500 Subject: [PATCH 022/139] test(walletconnect): refuse provider handoff replies with mismatched principal or payload --- .../api/gateway_tests/wallet/connectors.rs | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 4d1814f95..e45a96035 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -2,6 +2,28 @@ use super::super::*; #[tokio::test] async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { + struct ReplyOverride { + inner: MockWalletProvider, + field: Option<&'static str>, + } + #[async_trait::async_trait] + impl Provider for ReplyOverride { + fn name(&self) -> &'static str { "walletconnect-binding-fixture" } + fn schemes(&self) -> Vec<&'static str> { vec!["wallet"] } + async fn handle(&self, request: ResourceRequest) -> Result { + self.inner.handle(request).await + } + async fn send_raw(&self, request: &Value) -> Result { + let mut reply = self.inner.send_raw(request).await?; + let data = &mut reply["data"]["result"]["data"]; + if let Some(field) = self.field.filter(|_| data.get("handoff").is_some()) { + data["approval_request"][field] = if field == "payload_hash" { + json!(format!("0x{}", "ff".repeat(32))) + } else { json!("other-principal") }; + } + Ok(reply) + } + } async fn call(app: &Router, home: &str, suffix: &str, input: Value) -> (StatusCode, Value) { let response = app.clone().oneshot(test_browser_request("localhost:61180", "http://localhost:61180") .method("POST").uri(format!("/api/apps/home/wallet-connector/approvals/wallet-approval%3Awc-reviewed/{suffix}")) @@ -13,10 +35,10 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { .unwrap(); ( status, - serde_json::from_slice(&bytes).unwrap_or(Value::Null), + serde_json::from_slice(&bytes).unwrap_or_else(|_| json!({"text":String::from_utf8_lossy(&bytes)})), ) } - for case in ["valid", "other-principal", "other-connector", "expired"] { + for case in ["valid", "other-principal", "other-connector", "expired", "response-principal_id", "response-payload_hash"] { let dir = tempfile::tempdir().unwrap(); let owner = passkey_authority(dir.path()); seed_walletconnect_connector_config(dir.path()); @@ -40,9 +62,17 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { approvals: TokioMutex::new(vec![approval]), ..Default::default() }; - let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); + let provider = ReplyOverride { inner: provider, field: case.strip_prefix("response-") }; + let app = gateway_router(wallet_test_state_with_shared_provider(dir.path(), Arc::new(provider)).await); let input = json!({"schema":"elastos.home.wallet-connector.effect.request/v1", "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, "connector_token":connector}); let (status, review) = call(&app, &owner.home_token, "review", input.clone()).await; + if case.starts_with("response-") { + assert_eq!(status, StatusCode::OK, "stored request remains bound to its owner"); + let (status, error) = call(&app, &owner.home_token, "handoff", input).await; + assert_ne!(status, StatusCode::OK); + assert_eq!(error["text"], "WalletConnect approval binding mismatch"); + continue; + } if case != "valid" { assert_ne!(status, StatusCode::OK, "{case}"); assert_ne!( From 46123f4cfc48e43cefc80002ae000d9677487cb3 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 13:15:49 -0500 Subject: [PATCH 023/139] style(walletconnect): format the provider reply mismatch fixture --- .../api/gateway_tests/wallet/connectors.rs | 44 +++++++++++++++---- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index e45a96035..3c97af135 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -8,9 +8,16 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { } #[async_trait::async_trait] impl Provider for ReplyOverride { - fn name(&self) -> &'static str { "walletconnect-binding-fixture" } - fn schemes(&self) -> Vec<&'static str> { vec!["wallet"] } - async fn handle(&self, request: ResourceRequest) -> Result { + fn name(&self) -> &'static str { + "walletconnect-binding-fixture" + } + fn schemes(&self) -> Vec<&'static str> { + vec!["wallet"] + } + async fn handle( + &self, + request: ResourceRequest, + ) -> Result { self.inner.handle(request).await } async fn send_raw(&self, request: &Value) -> Result { @@ -19,7 +26,9 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { if let Some(field) = self.field.filter(|_| data.get("handoff").is_some()) { data["approval_request"][field] = if field == "payload_hash" { json!(format!("0x{}", "ff".repeat(32))) - } else { json!("other-principal") }; + } else { + json!("other-principal") + }; } Ok(reply) } @@ -35,10 +44,18 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { .unwrap(); ( status, - serde_json::from_slice(&bytes).unwrap_or_else(|_| json!({"text":String::from_utf8_lossy(&bytes)})), + serde_json::from_slice(&bytes) + .unwrap_or_else(|_| json!({"text":String::from_utf8_lossy(&bytes)})), ) } - for case in ["valid", "other-principal", "other-connector", "expired", "response-principal_id", "response-payload_hash"] { + for case in [ + "valid", + "other-principal", + "other-connector", + "expired", + "response-principal_id", + "response-payload_hash", + ] { let dir = tempfile::tempdir().unwrap(); let owner = passkey_authority(dir.path()); seed_walletconnect_connector_config(dir.path()); @@ -62,12 +79,21 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { approvals: TokioMutex::new(vec![approval]), ..Default::default() }; - let provider = ReplyOverride { inner: provider, field: case.strip_prefix("response-") }; - let app = gateway_router(wallet_test_state_with_shared_provider(dir.path(), Arc::new(provider)).await); + let provider = ReplyOverride { + inner: provider, + field: case.strip_prefix("response-"), + }; + let app = gateway_router( + wallet_test_state_with_shared_provider(dir.path(), Arc::new(provider)).await, + ); let input = json!({"schema":"elastos.home.wallet-connector.effect.request/v1", "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, "connector_token":connector}); let (status, review) = call(&app, &owner.home_token, "review", input.clone()).await; if case.starts_with("response-") { - assert_eq!(status, StatusCode::OK, "stored request remains bound to its owner"); + assert_eq!( + status, + StatusCode::OK, + "stored request remains bound to its owner" + ); let (status, error) = call(&app, &owner.home_token, "handoff", input).await; assert_ne!(status, StatusCode::OK); assert_eq!(error["text"], "WalletConnect approval binding mismatch"); From 8f958d19f663dea67e83b0daa3eb03aa82bdda7c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 13:40:10 -0500 Subject: [PATCH 024/139] fix(walletconnect): preserve short signature approval lifetimes --- .../browser/home-wallet-connector-host.js | 15 ++++++++---- components.json | 14 +++++------ scripts/walletconnect-home-host.test.mjs | 23 ++++++++++++++++--- 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/capsules/home/browser/home-wallet-connector-host.js b/capsules/home/browser/home-wallet-connector-host.js index d4178fe02..ae6ba6707 100644 --- a/capsules/home/browser/home-wallet-connector-host.js +++ b/capsules/home/browser/home-wallet-connector-host.js @@ -316,7 +316,9 @@ async function completeApproval(connectorId, connectorToken, approvalRequestId) ensureSameAddress(await currentEvmAccount(provider), review.address, "Select the requested account in your phone wallet, then review again."); const chain = `eip155:${requireEvmChainId(await provider.request({ method: "eth_chainId" }))}`; if (chain !== review.chain_namespace) throw new Error("Select the request network in your phone wallet, then review again."); - if (!Number.isSafeInteger(review.expires_at) || review.expires_at - Math.ceil(Date.now() / 1000) < 300) { + const remaining = review.expires_at - Math.ceil(Date.now() / 1000); + if (!Number.isSafeInteger(review.expires_at) || remaining <= 0 + || review.intent === "transaction_intent" && remaining < 300) { throw new Error("Wallet request expires soon. Request a fresh review."); } } @@ -347,8 +349,10 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, throw new Error("Wallet request changed or expired. Request a new review."); } const ttl = binding.expires_at - Math.ceil(Date.now() / 1000); - if (startingRequest && ttl < 300) throw new Error("Wallet request expires soon. Request a fresh review."); - return ttl; + if (startingRequest && handoff.intent === "transaction_intent" && ttl < 300) { + throw new Error("Wallet request expires soon. Request a fresh review."); + } + return Math.min(600, Math.max(ttl, 300)); }; const signer = requireEvmAddress(await currentEvmAccount(provider)); ensureSameAddress(signer, handoff.signer, "Switch to the linked account before approving."); @@ -362,12 +366,13 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, "Switch to the linked account before approving.", ); const expiry = await checkBinding(); + const invalidHash = "Wallet returned an invalid transaction hash. The wallet may have sent it. Check your wallet before sending again."; const transactionHash = requireProviderResult(await provider.request({ method: "eth_sendTransaction", params: [handoff.transaction], - }, expiry), 66, "Wallet returned an invalid transaction hash."); + }, expiry), 66, invalidHash); if (!/^0x[0-9a-fA-F]{64}$/.test(transactionHash)) { - throw new Error("Wallet returned an invalid transaction hash."); + throw new Error(invalidHash); } try { const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { diff --git a/components.json b/components.json index 102d8da81..0153fec42 100644 --- a/components.json +++ b/components.json @@ -91,8 +91,8 @@ ], "install_path": "capsules/wallet-walletconnect", "entrypoint": "browser/index.html", - "entrypoint_sha256": "sha256:b5fc187eef3396671ff204cd0ba7291f8af6739b6fd6b964689f29160e082865", - "entrypoint_size": 1480, + "entrypoint_sha256": "sha256:f7e3c08e4e6b2a49fc153d18e4e0a1ffd17965e4d904314d387200e7115d706a", + "entrypoint_size": 1670, "runtime_abi": "elastos.runtime-projection/v1", "execution": "web-projection", "bus_contract": "elastos.runtime-projection/v1", @@ -106,8 +106,8 @@ "browser_assets": [ { "path": "browser/index.html", - "sha256": "sha256:b5fc187eef3396671ff204cd0ba7291f8af6739b6fd6b964689f29160e082865", - "size": 1480 + "sha256": "sha256:f7e3c08e4e6b2a49fc153d18e4e0a1ffd17965e4d904314d387200e7115d706a", + "size": 1670 }, { "path": "browser/style.css", @@ -116,8 +116,8 @@ }, { "path": "browser/wallet-walletconnect.js", - "sha256": "sha256:bb4efeaceacfcbb334123729e4108f2b06a264c004b58856801605ac980075ea", - "size": 17187 + "sha256": "sha256:c2a0c0e1c49d88cf64c7094ebf7cf77ed94d4c56a729eadbdb4fe3e30d43ccf3", + "size": 14583 } ] }, @@ -1285,7 +1285,7 @@ }, "gba-nonogram": { "install_path": "capsules/gba-nonogram", - "description": "Nonogram Advance — MIT homebrew cartridge for the browser GBA viewer", + "description": "Nonogram Advance \u2014 MIT homebrew cartridge for the browser GBA viewer", "platforms": { "*": { "cid": "", diff --git a/scripts/walletconnect-home-host.test.mjs b/scripts/walletconnect-home-host.test.mjs index 33d3a4af5..b19ef838c 100644 --- a/scripts/walletconnect-home-host.test.mjs +++ b/scripts/walletconnect-home-host.test.mjs @@ -13,6 +13,8 @@ const origin = "http://localhost:61180"; const connector = "wallet-walletconnect"; async function fixture(scenario) { + const signatureIntent = scenario.startsWith("signature-"); + const lifetime = scenario === "signature-short" ? 180 : scenario === "long-request" ? 1800 : 600; const clock = Date.now; const events = new Map(); let changed = false; @@ -66,7 +68,7 @@ async function fixture(scenario) { assert.equal(body.message, linkMessages[scenario] || linkMessage); assert.equal(body.signature, signature); value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "evm_link_complete", connector_id: connector, status: "linked" }; } - else if (path.endsWith("/review")) value = { address, chain_namespace: "eip155:20", expires_at: Math.floor(Date.now() / 1000) + 600 }; + else if (path.endsWith("/review")) value = { address, intent: signatureIntent ? "browser_personal_sign" : "transaction_intent", chain_namespace: "eip155:20", expires_at: Math.floor(Date.now() / 1000) + lifetime }; else if (path.endsWith("/handoff")) { value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_handoff", @@ -76,7 +78,7 @@ async function fixture(scenario) { transaction: { from: address, to: `0x${"78".repeat(20)}`, value: "0x1", data: "0x", gas: "0x5208", gasPrice: "0x1", nonce: "0x1", chainId: "0x14" }, }, binding: { principal_id: "principal-fixture", requested_by_actor: "documents", account_id: "account-fixture", chain_namespace: "eip155:20", - payload_hash: payloadHash, expires_at: scenario === "expired" ? 1 : Math.floor(Date.now() / 1000) + 600 }, + payload_hash: payloadHash, expires_at: scenario === "expired" ? 1 : Math.floor(Date.now() / 1000) + lifetime }, }; if (scenario.startsWith("signature-")) { delete value.handoff.transaction; @@ -87,7 +89,8 @@ async function fixture(scenario) { const body = JSON.parse(input.body); assert.equal(body.payload_hash, payloadHash); assert.equal(body.signer, address); - assert.equal(body.transaction_hash, transactionHash); + if (signatureIntent) assert.equal(body.signature, signature); + else assert.equal(body.transaction_hash, transactionHash); if (scenario === "completion-refused") return { ok: false, status: 403, text: async () => "wallet approval request expired" }; value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_complete", connector_id: connector, request_id: "approval:fixture", status: "completed" }; @@ -144,10 +147,24 @@ test("a refused transaction completion retains its hash and asks for checking be test("wallet-chosen text cannot appear as a returned transaction hash", async () => { const result = await fixture("invalid-hash"); assert.match(result.response.error, /invalid transaction hash/); + assert.match(result.response.error, /Check your wallet before sending again/); assert.doesNotMatch(result.response.error, /fake recovery website/); assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 0); }); +test("a 180-second Runtime signature keeps its expiry with a 300-second SDK timeout", async () => { + const result = await fixture("signature-short"); + assert.equal(result.response.error, undefined, result.response.error); + assert.equal(result.calls.find(call => call.method === "personal_sign").expiry, 300); + assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); +}); + +test("a longer Runtime request caps its SDK timeout at 600 seconds", async () => { + const result = await fixture("long-request"); + assert.equal(result.response.error, undefined, result.response.error); + assert.equal(result.calls.find(call => call.method === "eth_sendTransaction").expiry, 600); +}); + for (const change of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { test(`trusted Home stops an unused signature after ${change}`, async () => { const result = await fixture(`signature-${change}`); From 6ca0ff62f48e0d0b352d61bb765573ca069b951c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 13:52:59 -0500 Subject: [PATCH 025/139] test(walletconnect): use the selected consent and Apps launch journey --- scripts/browser-internet-consent.test.mjs | 2 +- scripts/home-wallet-connector-launch-headless-smoke.mjs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/browser-internet-consent.test.mjs b/scripts/browser-internet-consent.test.mjs index b1a8097ea..497638ce5 100644 --- a/scripts/browser-internet-consent.test.mjs +++ b/scripts/browser-internet-consent.test.mjs @@ -62,7 +62,7 @@ async function fixture(service = "browser") { } const app=url.searchParams.get("app") || "browser"; res.setHeader("content-type","text/html"); - res.end(``);return; + res.end(``);return; } if (url.pathname === internetPath) { state.reads++; diff --git a/scripts/home-wallet-connector-launch-headless-smoke.mjs b/scripts/home-wallet-connector-launch-headless-smoke.mjs index 36c43f124..8954e9058 100644 --- a/scripts/home-wallet-connector-launch-headless-smoke.mjs +++ b/scripts/home-wallet-connector-launch-headless-smoke.mjs @@ -497,7 +497,8 @@ try { ); await waitFor(() => frameFor(page, "home-gui"), 15_000, "real Home GUI frame"); const homeGui = frameFor(page, "home-gui"); - await homeGui.dblclick('#desktop-shortcut-wallet'); + await homeGui.locator('#launcher-toggle').click(); + await homeGui.locator('#launcher-grid [data-target="wallet"]').click(); await waitFor(() => frameFor(page, "wallet"), 15_000, "real Wallet frame"); const wallet = frameFor(page, "wallet"); await wallet.waitForSelector("#wallet-settings-open", { timeout: 15_000 }); From e99005bddff0f0792af0256a4e5403e03e028be9 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 13:53:37 -0500 Subject: [PATCH 026/139] test(walletconnect): exercise the SDK with the Home RPC URL --- scripts/walletconnect-sdk.test.mjs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs index 4e053cc04..158a44587 100644 --- a/scripts/walletconnect-sdk.test.mjs +++ b/scripts/walletconnect-sdk.test.mjs @@ -42,7 +42,7 @@ const api = async (path, input) => { window.pending = connectWalletConnectEvm({ contextKey:'principal-fixture', projectId:'fixture-project-id', chains:[1], api, relayUrl:location.origin.replace(/^http/, 'ws') + '/relay', - runtimeUrl:new URLSearchParams(location.search).has('relative') ? '/api/apps/wallet-walletconnect' : location.origin + '/api/apps/wallet-walletconnect', + runtimeUrl:location.origin + '/api/apps/wallet-walletconnect', metadata:{name:'Isolated Runtime fixture', description:'WalletConnect test', url:location.origin, icons:[]}, }).catch(error => { window.cancelled = error.message === 'Wallet connection cancelled.'; window.failed = !window.cancelled; }); `; @@ -59,20 +59,20 @@ test("the locked SDK reaches QR through Home, stores its keys through Runtime, a let browser; try { browser = await chromium.launch({ headless: true }); - const invalid = await browser.newContext(); - const invalidPage = await invalid.newPage(); - await invalid.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); - await invalidPage.goto(`${origin}/?relative`); - await invalidPage.waitForFunction(() => window.failed, null, { timeout: 20000 }); - assert.equal(await invalidPage.locator("dialog[open]").count(), 0, "a relative RPC URL cannot initialize the real SDK"); - await invalid.close(); for (const width of [1280, 390]) { const context = await browser.newContext({ viewport: { width, height: 800 } }); // CSP remains the same Home-only network boundary used by the product. await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); const page = await context.newPage(); + const pageErrors = []; + page.on("pageerror", error => pageErrors.push(error.message)); await page.goto(origin); - await page.locator("dialog[open] canvas").waitFor({ timeout: 20000 }); + try { + await page.locator("dialog[open] canvas").waitFor({ timeout: 20000 }); + } catch (cause) { + const state = await page.evaluate(() => ({ failed: window.failed, methods: window.methods, nativeUrls: window.nativeUrls })); + throw new Error(`SDK fixture did not reach QR: ${JSON.stringify({ pageErrors, state })}`, { cause }); + } const state = await page.evaluate(() => ({ homeOnly: window.nativeUrls.length > 0 && window.nativeUrls.every(url => url === location.origin.replace(/^http/, "ws") + "/relay"), subscribed: window.methods.some(method => method.endsWith("subscribe")), From de752128e7354de647adf78ca9d4569b064e94f9 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 14:12:31 -0500 Subject: [PATCH 027/139] test(walletconnect): await the SDK batch subscription and key storage --- scripts/walletconnect-sdk.test.mjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs index 158a44587..1d99a2e9d 100644 --- a/scripts/walletconnect-sdk.test.mjs +++ b/scripts/walletconnect-sdk.test.mjs @@ -73,9 +73,12 @@ test("the locked SDK reaches QR through Home, stores its keys through Runtime, a const state = await page.evaluate(() => ({ failed: window.failed, methods: window.methods, nativeUrls: window.nativeUrls })); throw new Error(`SDK fixture did not reach QR: ${JSON.stringify({ pageErrors, state })}`, { cause }); } + await page.waitForFunction(() => window.methods.some(method => + ["irn_subscribe", "irn_batchSubscribe"].includes(method)) + && Object.keys(window.keys).some(key => key.includes("keychain")), null, { timeout: 10000 }); const state = await page.evaluate(() => ({ homeOnly: window.nativeUrls.length > 0 && window.nativeUrls.every(url => url === location.origin.replace(/^http/, "ws") + "/relay"), - subscribed: window.methods.some(method => method.endsWith("subscribe")), + subscribed: window.methods.some(method => ["irn_subscribe", "irn_batchSubscribe"].includes(method)), runtimeKeys: Object.keys(window.keys).some(key => key.includes("keychain")), localKeys: localStorage.length, canvas: document.querySelector("canvas").width, From 9400b2a042e92091a5d768cabda14061a4363e68 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 15:30:50 -0500 Subject: [PATCH 028/139] test(walletconnect): report redacted relay and storage readiness on failure --- scripts/walletconnect-sdk.test.mjs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs index 1d99a2e9d..8a387c99f 100644 --- a/scripts/walletconnect-sdk.test.mjs +++ b/scripts/walletconnect-sdk.test.mjs @@ -70,12 +70,19 @@ test("the locked SDK reaches QR through Home, stores its keys through Runtime, a try { await page.locator("dialog[open] canvas").waitFor({ timeout: 20000 }); } catch (cause) { - const state = await page.evaluate(() => ({ failed: window.failed, methods: window.methods, nativeUrls: window.nativeUrls })); + const state = await page.evaluate(() => ({ failed: window.failed, methods: window.methods, + nativeOrigins: window.nativeUrls.map(url => new URL(url).origin) })); throw new Error(`SDK fixture did not reach QR: ${JSON.stringify({ pageErrors, state })}`, { cause }); } - await page.waitForFunction(() => window.methods.some(method => - ["irn_subscribe", "irn_batchSubscribe"].includes(method)) - && Object.keys(window.keys).some(key => key.includes("keychain")), null, { timeout: 10000 }); + try { + await page.waitForFunction(() => window.methods.some(method => + ["irn_subscribe", "irn_batchSubscribe"].includes(method)) + && Object.keys(window.keys).some(key => key.includes("keychain")), null, { timeout: 10000 }); + } catch (cause) { + const state = await page.evaluate(() => ({ methods: window.methods, keyNames: Object.keys(window.keys), + localKeyCount: localStorage.length, nativeOrigins: window.nativeUrls.map(url => new URL(url).origin) })); + throw new Error(`SDK relay/storage not ready: ${JSON.stringify(state)}`, { cause }); + } const state = await page.evaluate(() => ({ homeOnly: window.nativeUrls.length > 0 && window.nativeUrls.every(url => url === location.origin.replace(/^http/, "ws") + "/relay"), subscribed: window.methods.some(method => ["irn_subscribe", "irn_batchSubscribe"].includes(method)), From 238a8ce3c9082d8bb40a48ca7fa643f2e4f7ac15 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 15:35:37 -0500 Subject: [PATCH 029/139] test(walletconnect): verify the pinned SDK pairing proposal protocol --- scripts/walletconnect-sdk.test.mjs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs index 8a387c99f..fa02f5db7 100644 --- a/scripts/walletconnect-sdk.test.mjs +++ b/scripts/walletconnect-sdk.test.mjs @@ -9,7 +9,7 @@ const bundle = readFileSync(new URL("../capsules/wallet-walletconnect/vendor/reo const fixture = ` import { connectWalletConnectEvm } from '/sdk.js'; -window.methods = []; window.nativeUrls = []; +window.methods = []; window.nativeUrls = []; window.proposalReady = false; window.keys = Object.create(null); window.cancelled = false; window.failed = false; class RelaySocket { constructor(url) { @@ -23,6 +23,11 @@ class RelaySocket { } if (!message.method) return; window.methods.push(message.method); + if (message.method === 'wc_proposeSession') { + window.proposalReady = /^[a-f0-9]{64}$/.test(message.params?.pairingTopic) + && typeof message.params?.sessionProposal === 'string' + && message.params.sessionProposal.length > 0; + } const result = message.method.endsWith('batchSubscribe') ? message.params.topics.map((_, i) => 'sub-' + i) : message.method.endsWith('subscribe') ? 'fixture-subscription' : true; queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ jsonrpc:'2.0', id:message.id, result }) })); @@ -75,24 +80,23 @@ test("the locked SDK reaches QR through Home, stores its keys through Runtime, a throw new Error(`SDK fixture did not reach QR: ${JSON.stringify({ pageErrors, state })}`, { cause }); } try { - await page.waitForFunction(() => window.methods.some(method => - ["irn_subscribe", "irn_batchSubscribe"].includes(method)) + await page.waitForFunction(() => window.proposalReady && Object.keys(window.keys).some(key => key.includes("keychain")), null, { timeout: 10000 }); } catch (cause) { - const state = await page.evaluate(() => ({ methods: window.methods, keyNames: Object.keys(window.keys), + const state = await page.evaluate(() => ({ methods: window.methods, proposalReady: window.proposalReady, keyNames: Object.keys(window.keys), localKeyCount: localStorage.length, nativeOrigins: window.nativeUrls.map(url => new URL(url).origin) })); throw new Error(`SDK relay/storage not ready: ${JSON.stringify(state)}`, { cause }); } const state = await page.evaluate(() => ({ homeOnly: window.nativeUrls.length > 0 && window.nativeUrls.every(url => url === location.origin.replace(/^http/, "ws") + "/relay"), - subscribed: window.methods.some(method => ["irn_subscribe", "irn_batchSubscribe"].includes(method)), + proposed: window.proposalReady, runtimeKeys: Object.keys(window.keys).some(key => key.includes("keychain")), localKeys: localStorage.length, canvas: document.querySelector("canvas").width, fits: document.querySelector("dialog").getBoundingClientRect().width <= innerWidth, })); assert.equal(state.homeOnly, true, "SDK sockets terminate at Home"); - assert.equal(state.subscribed, true); + assert.equal(state.proposed, true, "the pinned SDK publishes its pairing proposal through Home"); assert.equal(state.runtimeKeys, true, "SDK keychain reaches the Runtime storage adapter"); assert.equal(state.localKeys, 0); assert.ok(state.canvas > 0); From 6f9f777c016f0f1a81554a3314887fc89544805e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 17:36:53 -0500 Subject: [PATCH 030/139] test(walletconnect): use a fresh timestamped relay request ID --- .../api/gateway_tests/wallet/walletconnect_real_relay.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index ef602ab7d..3e7e51355 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -103,8 +103,10 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { "Runtime did not confirm the authenticated upstream WebSocket upgrade" ); // A successful relay RPC also excludes a post-upgrade authentication close. + // Reown requires a fresh timestamp-based ID, as the pinned SDK supplies. + let request_id = now_ts() * 1_000_000; socket.send(Message::Text(json!({ - "id": 1, "jsonrpc": "2.0", "method": "irn_subscribe", + "id": request_id, "jsonrpc": "2.0", "method": "irn_subscribe", "params": { "topic": format!("{:x}", Sha256::digest(gateway_home_token::uuid_like_token())) }, }).to_string())).await.unwrap(); let response = tokio::time::timeout(Duration::from_secs(15), socket.next()).await; @@ -113,7 +115,7 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { }; let response: Value = serde_json::from_str(&response).expect("relay JSON response"); assert!( - response["id"] == 1 && response["result"].is_string(), + response["id"] == request_id && response["result"].is_string(), "real relay subscription failed" ); socket.close(None).await.unwrap(); From 8da20d86d45b4f4bda92e070c18d65732c0ea519 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 12 Nov 2026 21:08:05 -0500 Subject: [PATCH 031/139] fix(walletconnect): serve only the pinned SDK beyond browser assets (#575) --- .../src/api/browser_capsules.rs | 142 +++++++++++++++++- 1 file changed, 140 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/browser_capsules.rs b/elastos/crates/elastos-server/src/api/browser_capsules.rs index 2cb8618bc..073aa9026 100644 --- a/elastos/crates/elastos-server/src/api/browser_capsules.rs +++ b/elastos/crates/elastos-server/src/api/browser_capsules.rs @@ -248,8 +248,31 @@ async fn serve_browser_capsule_asset( return (StatusCode::NOT_FOUND, "File not found").into_response(); } - let asset_path = match tokio::fs::canonicalize(capsule_root.join(relative_path)).await { - Ok(path) if path.starts_with(&capsule_root) => path, + // The connector's locked SDK is a sibling of browser/. This one asset has + // a browser route; the rest of the executable capsule stays private. + let asset_root = if app == super::gateway::WALLET_WALLETCONNECT_CAPSULE_ID + && relative_path == "vendor/reown-appkit.js" + && capsule.root.ends_with("browser") + { + let Some(root) = capsule.root.parent() else { + return (StatusCode::NOT_FOUND, "File not found").into_response(); + }; + let root = match tokio::fs::canonicalize(root).await { + Ok(path) if path.starts_with(&installed_root) => path, + _ => return (StatusCode::NOT_FOUND, "File not found").into_response(), + }; + if strict_declared_content_icon_path(&root, relative_path) + .await + .is_err() + { + return (StatusCode::NOT_FOUND, "File not found").into_response(); + } + root + } else { + capsule_root.clone() + }; + let asset_path = match tokio::fs::canonicalize(asset_root.join(relative_path)).await { + Ok(path) if path.starts_with(&asset_root) => path, _ => return (StatusCode::NOT_FOUND, "File not found").into_response(), }; let Ok(bytes) = tokio::fs::read(&asset_path).await else { @@ -1454,6 +1477,121 @@ mod tests { assert_eq!(escape_file_response.status(), StatusCode::NOT_FOUND); } + #[tokio::test] + async fn walletconnect_serves_exact_pinned_sdk_without_exposing_capsule_root() { + use super::super::gateway::{ + WALLETCONNECT_CONFIG_PATH, WALLETCONNECT_CONFIG_SCHEMA, WALLETCONNECT_SDK_PACKAGE, + }; + let data_dir = tempfile::tempdir().unwrap(); + write_test_wasm_browser_capsule( + data_dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + "WalletConnect", + "app", + ); + let capsule = data_dir.path().join("capsules/wallet-walletconnect"); + let sdk = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../capsules/wallet-walletconnect/vendor/reown-appkit.js" + )); + let hash = hex::encode(Sha256::digest(sdk)); + assert_eq!( + hash, + "6cff318e63fa0b8c9cc7ee95ce92d5a5470df6cd742a8ad8c2033ce829bb1895" + ); + fs::create_dir_all(capsule.join("vendor")).unwrap(); + fs::write(capsule.join("vendor/reown-appkit.js"), sdk).unwrap(); + fs::write(capsule.join("vendor/adapter.json"), "private provenance").unwrap(); + fs::write(capsule.join("vendor/package-lock.json"), "private lock").unwrap(); + fs::write( + capsule.join("wallet-walletconnect.wasm"), + "private executable", + ) + .unwrap(); + let config = data_dir.path().join(WALLETCONNECT_CONFIG_PATH); + fs::create_dir_all(config.parent().unwrap()).unwrap(); + fs::write( + config, + serde_json::to_vec(&serde_json::json!({ + "schema": WALLETCONNECT_CONFIG_SCHEMA, + "project_id": "fixture-project", + "sdk_package": WALLETCONNECT_SDK_PACKAGE, + "sdk_version": "2.23.9", + "sdk_sha256": hash, + })) + .unwrap(), + ) + .unwrap(); + + let response = serve_browser_capsule_path( + data_dir.path(), + &test_request_headers(), + WALLET_WALLETCONNECT_CAPSULE_ID, + Some("vendor/reown-appkit.js"), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["access-control-allow-origin"], "null"); + assert_eq!(response.headers()["content-type"], "application/javascript"); + let bytes = axum::body::to_bytes(response.into_body(), sdk.len()) + .await + .unwrap(); + assert_eq!(hex::encode(Sha256::digest(&bytes)), hash); + assert_eq!(bytes.as_ref(), sdk); + for path in [ + "capsule.json", + "wallet-walletconnect.wasm", + "vendor/adapter.json", + "vendor/package-lock.json", + "vendor/../capsule.json", + "../wallet/wallet.wasm", + ] { + let response = serve_browser_capsule_path( + data_dir.path(), + &test_request_headers(), + WALLET_WALLETCONNECT_CAPSULE_ID, + Some(path), + ) + .await; + assert!( + matches!( + response.status(), + StatusCode::NOT_FOUND | StatusCode::BAD_REQUEST + ), + "capsule path was exposed: {path}" + ); + } + + write_test_wasm_browser_capsule(data_dir.path(), "other-app", "Other app", "app"); + let other = data_dir.path().join("capsules/other-app/vendor"); + fs::create_dir_all(&other).unwrap(); + fs::write(other.join("reown-appkit.js"), sdk).unwrap(); + let response = serve_browser_capsule_path( + data_dir.path(), + &test_request_headers(), + "other-app", + Some("vendor/reown-appkit.js"), + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); + + #[cfg(unix)] + { + // A directory link must be refused even when its bytes match the pin. + fs::rename(capsule.join("vendor"), capsule.join("private-vendor")).unwrap(); + std::os::unix::fs::symlink(capsule.join("private-vendor"), capsule.join("vendor")) + .unwrap(); + let response = serve_browser_capsule_path( + data_dir.path(), + &test_request_headers(), + WALLET_WALLETCONNECT_CAPSULE_ID, + Some("vendor/reown-appkit.js"), + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + } + #[tokio::test] async fn walletconnect_browser_capsule_requires_pinned_runtime_config() { let data_dir = tempfile::tempdir().unwrap(); From bef2c7780858c3d5ebaf653dab7d049893a40772 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:06:13 -0500 Subject: [PATCH 032/139] test(walletconnect): keep relay-auth encoding dependency after develop merge --- elastos/crates/elastos-server/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index c22251053..045861d18 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -117,6 +117,7 @@ data-encoding = "2.6" custody-provider = { path = "../../../capsules/custody-provider" } [dev-dependencies] +bs58 = "0.5" rcgen = "0.13" tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } tokio = { version = "1.0", features = ["full", "test-util"] } From a8e099b8e1eda6d5fee81aaac12f6fe7c03b6932 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:08:10 -0500 Subject: [PATCH 033/139] test(walletconnect): reproduce capsule Storage parity against both engines --- .../browser/walletconnect-storage.mjs | 78 +++++++++++++ elastos/Cargo.lock | 1 + .../src/api/gateway_tests/content_sandbox.rs | 85 +++++++++++++++ scripts/lib/walletconnect-browser-fixture.mjs | 44 ++++++++ scripts/lib/walletconnect-storage-probe.mjs | 20 ++++ scripts/walletconnect-sandbox-smoke.mjs | 103 ++++++++++++++++++ scripts/walletconnect-sdk.test.mjs | 47 +------- scripts/walletconnect-storage-smoke.mjs | 51 +++++++++ 8 files changed, 384 insertions(+), 45 deletions(-) create mode 100644 capsules/wallet-walletconnect/browser/walletconnect-storage.mjs create mode 100644 scripts/lib/walletconnect-browser-fixture.mjs create mode 100644 scripts/lib/walletconnect-storage-probe.mjs create mode 100644 scripts/walletconnect-sandbox-smoke.mjs create mode 100644 scripts/walletconnect-storage-smoke.mjs diff --git a/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs b/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs new file mode 100644 index 000000000..74adea63a --- /dev/null +++ b/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs @@ -0,0 +1,78 @@ +// Capsule-local compatibility for SDK imports. Runtime owns protocol storage. +export function installWalletConnectStorage(window, trace = () => {}) { + const stores = new WeakMap(); + const data = receiver => { + const value = stores.get(receiver); + if (!value) throw new TypeError("Illegal invocation"); + return value; + }; + const text = value => { + if (typeof value === "symbol") throw new TypeError("Cannot convert a Symbol to a string"); + return String(value); + }; + const requireArguments = (count, actual) => { + if (actual < count) throw new TypeError(`${count} arguments required`); + }; + const prototype = Object.create(window.Storage.prototype); + Object.defineProperties(prototype, { + length: { configurable: true, enumerable: true, get() { return data(this).values.size; } }, + key: { configurable: true, enumerable: true, writable: true, value: function key(index) { + const state = data(this); requireArguments(1, arguments.length); + return [...state.values.keys()][+index >>> 0] ?? null; + } }, + getItem: { configurable: true, enumerable: true, writable: true, value: function getItem(key) { + const state = data(this); requireArguments(1, arguments.length); key = text(key); + return state.values.has(key) ? state.values.get(key) : null; + } }, + setItem: { configurable: true, enumerable: true, writable: true, value: function setItem(key, value) { + const state = data(this); requireArguments(2, arguments.length); + key = text(key); value = text(value); + const refused = /wc@2:|keychain/i.test(key); + trace({ store: state.name, operation: "setItem", key, refused }); + if (refused) throw new window.DOMException("WalletConnect protocol state requires Runtime storage.", "SecurityError"); + state.values.set(key, value); + } }, + removeItem: { configurable: true, enumerable: true, writable: true, value: function removeItem(key) { + const state = data(this); requireArguments(1, arguments.length); key = text(key); + trace({ store: state.name, operation: "removeItem", key }); state.values.delete(key); + } }, + clear: { configurable: true, enumerable: true, writable: true, value: function clear() { + const state = data(this); trace({ store: state.name, operation: "clear" }); state.values.clear(); + } }, + }); + const memory = name => { + const values = new Map(); + const target = Object.create(prototype); + const visible = key => typeof key === "string" && values.has(key) && !Reflect.has(target, key); + const storage = new Proxy(target, { + get(target, key, receiver) { return visible(key) ? values.get(key) : Reflect.get(target, key, receiver); }, + has(target, key) { return values.has(key) || Reflect.has(target, key); }, + set(target, key, value) { + if (typeof key === "symbol") return Reflect.set(target, key, value); + prototype.setItem.call(storage, key, value); return true; + }, + deleteProperty(target, key) { + if (typeof key === "symbol") return Reflect.deleteProperty(target, key); + prototype.removeItem.call(storage, key); return true; + }, + ownKeys(target) { return [...Reflect.ownKeys(target), ...[...values.keys()].filter(visible)]; }, + getOwnPropertyDescriptor(target, key) { + return visible(key) ? { value: values.get(key), configurable: true, enumerable: true, writable: true } + : Reflect.getOwnPropertyDescriptor(target, key); + }, + defineProperty(target, key, descriptor) { + if (typeof key === "symbol") return Reflect.defineProperty(target, key, descriptor); + if ("get" in descriptor || "set" in descriptor || descriptor.configurable === false + || descriptor.enumerable === false || descriptor.writable === false) return false; + prototype.setItem.call(storage, key, descriptor.value); return true; + }, + }); + stores.set(storage, { name, values }); + return storage; + }; + const local = memory("localStorage"), session = memory("sessionStorage"); + for (const [name, storage] of [["localStorage", local], ["sessionStorage", session]]) { + Object.defineProperty(window, name, { get: () => storage, configurable: false, enumerable: true }); + } + return () => { prototype.clear.call(local); prototype.clear.call(session); }; +} diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index 0282a0196..9b8cfe4b1 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -1664,6 +1664,7 @@ dependencies = [ "axum", "axum-server", "base64", + "bs58", "cid", "clap", "custody-provider", diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index f925a8172..1c026fe36 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -656,3 +656,88 @@ async fn content_sandbox_browser_capsule_scripts() { String::from_utf8_lossy(&output.stderr) ); } + +#[tokio::test] +#[ignore = "requires Playwright Chromium and WebKit; focused WalletConnect sandbox gate"] +async fn content_sandbox_browser_walletconnect_sdk() { + let dir = tempfile::tempdir().unwrap(); + let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); + for name in ["home", "wallet-walletconnect"] { + let destination = dir.path().join("capsules").join(name); + activate_test_capsule(dir.path(), name); + std::fs::create_dir_all(&destination).unwrap(); + std::fs::copy( + repo.join("capsules").join(name).join("capsule.json"), + destination.join("capsule.json"), + ) + .unwrap(); + copy_operator_site( + &repo.join("capsules").join(name).join("browser"), + &destination.join("browser"), + ); + write_test_wasm_entrypoint(dir.path(), name); + } + let capsule = dir.path().join("capsules/wallet-walletconnect"); + std::fs::create_dir_all(capsule.join("vendor")).unwrap(); + let sdk = repo.join("capsules/wallet-walletconnect/vendor/reown-appkit.js"); + std::fs::copy(&sdk, capsule.join("vendor/reown-appkit.js")).unwrap(); + // The browser-local name keeps the same locked fixture import in the + // sandbox and unsandboxed SDK tests. The canonical vendor route is also + // hash-checked by the browser test. + std::fs::copy(sdk, capsule.join("browser/wc-sdk.js")).unwrap(); + std::fs::copy( + repo.join("scripts/lib/walletconnect-browser-fixture.mjs"), + capsule.join("browser/wc-fixture.js"), + ) + .unwrap(); + std::fs::write(capsule.join("browser/wc-bootstrap.js"), + "import { installWalletConnectStorage } from './walletconnect-storage.mjs';\nwindow.storageTrace = [];\ninstallWalletConnectStorage(window, entry => window.storageTrace.push(entry));\nawait import('./wc-fixture.js');", + ).unwrap(); + std::fs::write( + capsule.join("browser/wc-frame.html"), + "", + ) + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let app = gateway_router_with_api_url(test_state(dir.path()), format!("http://{addr}")); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let mut server = tokio::spawn(async move { + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(async { + let _ = shutdown_rx.await; + }) + .await + }); + let mut command = tokio::process::Command::new("node"); + command + .arg(repo.join("scripts/walletconnect-sandbox-smoke.mjs")) + .env( + "ELASTOS_WALLETCONNECT_SANDBOX_URL", + format!("http://{addr}"), + ) + .kill_on_drop(true); + let result = tokio::time::timeout(std::time::Duration::from_secs(180), command.output()).await; + let _ = shutdown_tx.send(()); + if tokio::time::timeout(std::time::Duration::from_secs(5), &mut server) + .await + .is_err() + { + server.abort(); + let _ = server.await; + panic!("WalletConnect source Home did not stop"); + } + let output = result + .expect("WalletConnect browser timeout") + .expect("start WalletConnect browser gate"); + println!("{}", String::from_utf8_lossy(&output.stdout)); + assert!( + output.status.success(), + "WalletConnect sandbox failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} diff --git a/scripts/lib/walletconnect-browser-fixture.mjs b/scripts/lib/walletconnect-browser-fixture.mjs new file mode 100644 index 000000000..76645d057 --- /dev/null +++ b/scripts/lib/walletconnect-browser-fixture.mjs @@ -0,0 +1,44 @@ +import { connectWalletConnectEvm } from './wc-sdk.js'; +window.methods = []; window.nativeUrls = []; window.proposalReady = false; +window.runtimeTrace = []; +window.keys = Object.create(null); window.cancelled = false; window.failed = false; +class RelaySocket { + constructor(url) { + window.nativeUrls.push(url); this.readyState = 0; + queueMicrotask(() => { this.readyState = 1; this.onopen?.(); }); + } + send(raw) { + const message = JSON.parse(raw); + if (message.token) { + queueMicrotask(() => this.onmessage?.({ data: '{"ready":true}' })); return; + } + if (!message.method) return; + window.methods.push(message.method); + if (message.method === 'wc_proposeSession') { + window.proposalReady = /^[a-f0-9]{64}$/.test(message.params?.pairingTopic) + && typeof message.params?.sessionProposal === 'string' + && message.params.sessionProposal.length > 0; + } + const result = message.method.endsWith('batchSubscribe') ? message.params.topics.map((_, i) => 'sub-' + i) + : message.method.endsWith('subscribe') ? 'fixture-subscription' : true; + queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ jsonrpc:'2.0', id:message.id, result }) })); + } + close() { this.readyState = 3; this.onclose?.(); } +} +globalThis.WebSocket = RelaySocket; +const api = async (path, input) => { + if (path === 'relay-admission') return { token:'fixture-admission' }; + if (path !== 'storage') throw new Error('unexpected Runtime resource'); + if (input) { + const { key, value } = JSON.parse(input.body); + window.runtimeTrace.push({ key, operation: value === null ? "removeItem" : "setItem" }); + if (value === null) delete window.keys[key]; else window.keys[key] = value; + } + return structuredClone(window.keys); +}; +window.pending = connectWalletConnectEvm({ + contextKey:'principal-fixture', projectId:'fixture-project-id', chains:[1], api, + relayUrl:location.origin.replace(/^http/, 'ws') + '/relay', + runtimeUrl:location.origin + '/api/apps/wallet-walletconnect', + metadata:{name:'Isolated Runtime fixture', description:'WalletConnect test', url:location.origin, icons:[]}, +}).catch(error => { window.cancelled = error.message === 'Wallet connection cancelled.'; window.failed = !window.cancelled; }); diff --git a/scripts/lib/walletconnect-storage-probe.mjs b/scripts/lib/walletconnect-storage-probe.mjs new file mode 100644 index 000000000..35d2e7ac2 --- /dev/null +++ b/scripts/lib/walletconnect-storage-probe.mjs @@ -0,0 +1,20 @@ +export function exerciseStorage() { + const s=localStorage;const set=s.setItem,get=s.getItem,clear=s.clear,key=s.key;const error=fn=>{try{fn();return null;}catch(e){return e.name;}}; + clear.call(s); + set.call(s,null,undefined);set.call(s,'choice',42);set.call(s,'choice',43); + s.named=false; + Object.defineProperty(s,'defined',{value:7,enumerable:true,writable:true,configurable:true}); + const symbol=Symbol('fixture');s[symbol]='symbol-value'; + const out={length:s.length,missing:get.call(s,'absent'),missingProperty:s.absent??null,nullKey:get.call(s,null),named:s.named,defined:s.defined, + keys:Object.keys(s).sort(),keyNames:Array.from({length:s.length},(_,i)=>key.call(s,i)).sort(),negative:key.call(s,-1),overflow:key.call(s,2**32)===key.call(s,0), + protoIdentity:Object.getPrototypeOf(s)===Storage.prototype, + prototypeGet:error(()=>Storage.prototype.getItem.call(s,'choice')), + tag:Object.prototype.toString.call(s),instance:s instanceof Storage,symbol:s[symbol], + missingArgument:error(()=>get.call(s)),missingValue:error(()=>set.call(s,'only')),symbolValue:error(()=>set.call(s,'sym',Symbol())), + bigintIndex:error(()=>key.call(s,1n)),badReceiver:error(()=>get.call({},'a'))}; + delete s.named;delete s[symbol]; + set.call(s,'getItem','reserved');set.call(s,'length','reserved');set.call(s,'__proto__','reserved'); + out.reserved={method:typeof s.getItem,length:s.length,proto:typeof s.__proto__,own:Object.keys(s).sort(),value:get.call(s,'getItem')}; + clear.call(s);out.empty=s.length; + return out; +} diff --git a/scripts/walletconnect-sandbox-smoke.mjs b/scripts/walletconnect-sandbox-smoke.mjs new file mode 100644 index 000000000..b5c078a44 --- /dev/null +++ b/scripts/walletconnect-sandbox-smoke.mjs @@ -0,0 +1,103 @@ +// The source gateway test supplies the documents, headers and pinned SDK. +import assert from "node:assert/strict"; +import { mkdir, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { importProductSmokePlaywright } from "./product-smoke-browser.mjs"; +import { exerciseStorage } from "./lib/walletconnect-storage-probe.mjs"; + +const origin = process.env.ELASTOS_WALLETCONNECT_SANDBOX_URL; +assert.ok(origin, "the source Runtime supplies the Home URL"); +const evidence = process.env.WALLETCONNECT_SCREENSHOTS; +if (evidence) await mkdir(evidence, { recursive: true }); +const expectedHash = "6cff318e63fa0b8c9cc7ee95ce92d5a5470df6cd742a8ad8c2033ce829bb1895"; +const sdk = await fetch(`${origin}/apps/wallet-walletconnect/vendor/reown-appkit.js`); +assert.equal(sdk.status, 200); +assert.equal(createHash("sha256").update(Buffer.from(await sdk.arrayBuffer())).digest("hex"), expectedHash); +for (const path of ["capsule.json", "main.wasm", "vendor/package-lock.json", "vendor/other.js"]) { + assert.equal((await fetch(`${origin}/apps/wallet-walletconnect/${path}`)).status, 404, path); +} +const result = { sdkSha256: expectedHash, runs: [] }; +const failures = []; +const playwright = await importProductSmokePlaywright(); +for (const engine of ["chromium", "webkit"]) { + const browser = await playwright[engine].launch({ headless: true }); + try { + for (const width of [1280, 390]) { + const context = await browser.newContext({ viewport: { width, height: 850 } }); + const page = await context.newPage(); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + // Block foreign traffic. Product CSP remains untouched. + await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); + const run = { engine, version: browser.version(), width, errors }; + try { + const home = await page.goto(`${origin}/apps/home/`); + assert.equal(home.status(), 200); + const doc = await fetch(`${origin}/apps/wallet-walletconnect/wc-frame.html`); + run.headers = Object.fromEntries(doc.headers); + assert.equal(run.headers["content-security-policy"], `sandbox allow-scripts allow-forms allow-downloads; default-src ${origin}; script-src 'self' 'wasm-unsafe-eval' ${origin}; style-src ${origin} 'unsafe-inline'; img-src ${origin} blob: data:; connect-src ${origin} ${origin.replace(/^http/, "ws")}; frame-src ${origin}; object-src 'none'; base-uri 'none'; form-action ${origin}`); + await page.evaluate(url => { + const frame = document.createElement("iframe"); + frame.setAttribute("sandbox", "allow-downloads allow-forms allow-modals allow-pointer-lock allow-scripts"); + frame.src = url; + frame.style = "position:fixed;inset:0;width:100%;height:100%;z-index:999999"; + document.body.append(frame); + }, `${origin}/apps/wallet-walletconnect/wc-frame.html`); + const frame = page.frameLocator('iframe[src$="/wc-frame.html"]'); + await frame.locator("dialog[open] canvas").waitFor({ timeout: 20000 }); + const actualFrame = page.frames().find(f => f.url().endsWith("/wc-frame.html")); + await actualFrame.waitForFunction(() => window.proposalReady && Object.keys(window.keys).some(key => key.includes("keychain"))); + run.state = await actualFrame.evaluate(() => { + const canvas = document.querySelector("canvas"); + const pixels = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data; + let black = 0, white = 0; + for (let i = 0; i < pixels.length; i += 4) { + if (pixels[i + 3] === 255) { if (pixels[i] < 10) black++; if (pixels[i] > 240) white++; } + } + return { origin: self.origin, crypto: !!crypto.subtle, failed: window.failed, + runtimeTrace: window.runtimeTrace, storageTrace: window.storageTrace, + proposal: window.proposalReady, canvas: canvas.width, black, white, + fits: document.querySelector("dialog").getBoundingClientRect().width <= innerWidth }; + }); + assert.equal(run.state.origin, "null"); + assert.equal(run.state.crypto, true); + assert.equal(run.state.failed, false); + assert.ok(run.state.black && run.state.white); + assert.equal(run.state.fits, true); + assert.ok(run.state.runtimeTrace.some(t => t.key.includes("keychain"))); + assert.ok(run.state.storageTrace.every(t => !t.refused)); + run.native = await page.evaluate(exerciseStorage); + run.memory = await actualFrame.evaluate(exerciseStorage); + assert.deepEqual(run.memory, run.native); + run.refusals = await actualFrame.evaluate(() => { + const results = []; + for (const name of ["localStorage", "sessionStorage"]) for (const write of [ + s => s.setItem("wc@2:core:0.3//keychain", "fixture"), + s => { s["wc@2:client:0.3//session"] = "fixture"; }, + s => Object.defineProperty(s, "wc@2:core:0.3//pairing", { value: "fixture" }), + ]) { + try { write(window[name]); results.push("accepted"); } + catch (error) { results.push(error.name); } + } + return results; + }); + assert.deepEqual(run.refusals, Array(6).fill("SecurityError")); + if (evidence) await page.screenshot({ path: `${evidence}/${engine}-${width}.png` }); + await frame.getByRole("button", { name: "Cancel", exact: true }).click(); + await actualFrame.waitForFunction(() => window.cancelled); + assert.equal(await frame.locator("dialog").count(), 0); + run.cancelled = true; + console.log(`PASS ${engine} ${width}: opaque SDK, QR, Runtime writes, native Storage parity, protocol refusal, Cancel`); + } catch (error) { + run.failure = error.message; + failures.push(`${engine} ${width}: ${error.message}`); + } finally { + result.runs.push(run); + await context.close(); + } + } + } finally { await browser.close(); } +} +if (evidence) await writeFile(`${evidence}/step0b.json`, JSON.stringify(result, null, 2)); +console.log(JSON.stringify(result)); +assert.deepEqual(failures, []); diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs index fa02f5db7..466f8f640 100644 --- a/scripts/walletconnect-sdk.test.mjs +++ b/scripts/walletconnect-sdk.test.mjs @@ -7,55 +7,12 @@ const require = createRequire(new URL("../elastos/tools/browser-playwright-engin const { chromium } = require("playwright"); const bundle = readFileSync(new URL("../capsules/wallet-walletconnect/vendor/reown-appkit.js", import.meta.url)); -const fixture = ` -import { connectWalletConnectEvm } from '/sdk.js'; -window.methods = []; window.nativeUrls = []; window.proposalReady = false; -window.keys = Object.create(null); window.cancelled = false; window.failed = false; -class RelaySocket { - constructor(url) { - window.nativeUrls.push(url); this.readyState = 0; - queueMicrotask(() => { this.readyState = 1; this.onopen?.(); }); - } - send(raw) { - const message = JSON.parse(raw); - if (message.token) { - queueMicrotask(() => this.onmessage?.({ data: '{"ready":true}' })); return; - } - if (!message.method) return; - window.methods.push(message.method); - if (message.method === 'wc_proposeSession') { - window.proposalReady = /^[a-f0-9]{64}$/.test(message.params?.pairingTopic) - && typeof message.params?.sessionProposal === 'string' - && message.params.sessionProposal.length > 0; - } - const result = message.method.endsWith('batchSubscribe') ? message.params.topics.map((_, i) => 'sub-' + i) - : message.method.endsWith('subscribe') ? 'fixture-subscription' : true; - queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ jsonrpc:'2.0', id:message.id, result }) })); - } - close() { this.readyState = 3; this.onclose?.(); } -} -globalThis.WebSocket = RelaySocket; -const api = async (path, input) => { - if (path === 'relay-admission') return { token:'fixture-admission' }; - if (path !== 'storage') throw new Error('unexpected Runtime resource'); - if (input) { - const { key, value } = JSON.parse(input.body); - if (value === null) delete window.keys[key]; else window.keys[key] = value; - } - return structuredClone(window.keys); -}; -window.pending = connectWalletConnectEvm({ - contextKey:'principal-fixture', projectId:'fixture-project-id', chains:[1], api, - relayUrl:location.origin.replace(/^http/, 'ws') + '/relay', - runtimeUrl:location.origin + '/api/apps/wallet-walletconnect', - metadata:{name:'Isolated Runtime fixture', description:'WalletConnect test', url:location.origin, icons:[]}, -}).catch(error => { window.cancelled = error.message === 'Wallet connection cancelled.'; window.failed = !window.cancelled; }); -`; +const fixture = readFileSync(new URL("./lib/walletconnect-browser-fixture.mjs", import.meta.url)); test("the locked SDK reaches QR through Home, stores its keys through Runtime, and cancels", { timeout: 45000 }, async () => { const server = http.createServer((req, res) => { res.setHeader("content-security-policy", "default-src 'self'; script-src 'self'; connect-src 'self'; frame-src 'self'; style-src 'self'"); - if (req.url === "/sdk.js") { res.setHeader("content-type", "text/javascript"); res.end(bundle); } + if (req.url === "/wc-sdk.js") { res.setHeader("content-type", "text/javascript"); res.end(bundle); } else if (req.url === "/fixture.js") { res.setHeader("content-type", "text/javascript"); res.end(fixture); } else { res.setHeader("content-type", "text/html"); res.end(''); } }); diff --git a/scripts/walletconnect-storage-smoke.mjs b/scripts/walletconnect-storage-smoke.mjs new file mode 100644 index 000000000..4f920192b --- /dev/null +++ b/scripts/walletconnect-storage-smoke.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import http from "node:http"; +import { readFileSync } from "node:fs"; +import { requireProductSmokePlaywright } from "./product-smoke-browser.mjs"; +import { exerciseStorage } from "./lib/walletconnect-storage-probe.mjs"; + +const shim = readFileSync(new URL("../capsules/wallet-walletconnect/browser/walletconnect-storage.mjs", import.meta.url)); + +for (const engine of ["chromium", "webkit"]) { + test(`capsule memory Storage matches native ${engine} Storage`, { timeout: 45000 }, async () => { + const server = http.createServer((req, res) => { + res.setHeader("content-type", req.url === "/shim.mjs" ? "text/javascript" : "text/html"); + res.end(req.url === "/shim.mjs" ? shim : "Storage comparison"); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + let browser; + try { + browser = await requireProductSmokePlaywright()[engine].launch({ headless: true }); + const page = await browser.newPage(); + await page.goto(`http://127.0.0.1:${server.address().port}`); + const native = await page.evaluate(exerciseStorage); + await page.evaluate(async () => { + const { installWalletConnectStorage } = await import("/shim.mjs"); + window.clearMemoryStorage = installWalletConnectStorage(window); + }); + const memory = await page.evaluate(exerciseStorage); + assert.deepEqual(memory, native); + assert.deepEqual(await page.evaluate(() => { + const errors = []; + for (const name of ["localStorage", "sessionStorage"]) { + for (const write of [ + s => s.setItem("wc@2:core:0.3//keychain", "fixture"), + s => { s["wc@2:client:0.3//session"] = "fixture"; }, + s => Object.defineProperty(s, "wc@2:core:0.3//pairing", { value: "fixture" }), + ]) { + try { write(window[name]); errors.push("accepted"); } + catch (error) { errors.push(error.name); } + } + window[name].setItem("wallet-choice", "fixture"); + } + window.clearMemoryStorage(); + return { errors, lengths: [localStorage.length, sessionStorage.length] }; + }), { errors: Array(6).fill("SecurityError"), lengths: [0, 0] }); + } finally { + await browser?.close(); + server.closeAllConnections(); + await new Promise(resolve => server.close(resolve)); + } + }); +} From 10992f04b9b311fe88d48546f7628de595f55ba3 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:12:14 -0500 Subject: [PATCH 034/139] fix(walletconnect): match native Storage prototype and reserved names --- .../browser/walletconnect-storage.mjs | 23 ++++++++++++---- docs/WALLET_PROVIDER.md | 11 ++++++++ .../src/api/gateway_tests/content_sandbox.rs | 4 --- scripts/lib/walletconnect-browser-fixture.mjs | 2 +- scripts/walletconnect-sandbox-smoke.mjs | 2 +- scripts/walletconnect-sdk.test.mjs | 2 +- scripts/walletconnect-storage-smoke.mjs | 27 ++++++++++++++----- 7 files changed, 53 insertions(+), 18 deletions(-) diff --git a/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs b/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs index 74adea63a..fc2e0068a 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-storage.mjs @@ -1,5 +1,7 @@ // Capsule-local compatibility for SDK imports. Runtime owns protocol storage. -export function installWalletConnectStorage(window, trace = () => {}) { +export function installWalletConnectStorage(window, trace = () => {}, + engine = /AppleWebKit/.test(window.navigator.userAgent) && !/Chrome|Chromium|Edg/.test(window.navigator.userAgent) + ? "webkit" : "chromium") { const stores = new WeakMap(); const data = receiver => { const value = stores.get(receiver); @@ -13,18 +15,22 @@ export function installWalletConnectStorage(window, trace = () => {}) { const requireArguments = (count, actual) => { if (actual < count) throw new TypeError(`${count} arguments required`); }; - const prototype = Object.create(window.Storage.prototype); + const prototype = window.Storage.prototype; + const native = Object.getOwnPropertyDescriptors(prototype); Object.defineProperties(prototype, { - length: { configurable: true, enumerable: true, get() { return data(this).values.size; } }, + length: { configurable: true, enumerable: true, get() { return stores.has(this) ? data(this).values.size : native.length.get.call(this); } }, key: { configurable: true, enumerable: true, writable: true, value: function key(index) { + if (!stores.has(this)) return native.key.value.apply(this, arguments); const state = data(this); requireArguments(1, arguments.length); return [...state.values.keys()][+index >>> 0] ?? null; } }, getItem: { configurable: true, enumerable: true, writable: true, value: function getItem(key) { + if (!stores.has(this)) return native.getItem.value.apply(this, arguments); const state = data(this); requireArguments(1, arguments.length); key = text(key); return state.values.has(key) ? state.values.get(key) : null; } }, setItem: { configurable: true, enumerable: true, writable: true, value: function setItem(key, value) { + if (!stores.has(this)) return native.setItem.value.apply(this, arguments); const state = data(this); requireArguments(2, arguments.length); key = text(key); value = text(value); const refused = /wc@2:|keychain/i.test(key); @@ -33,10 +39,12 @@ export function installWalletConnectStorage(window, trace = () => {}) { state.values.set(key, value); } }, removeItem: { configurable: true, enumerable: true, writable: true, value: function removeItem(key) { + if (!stores.has(this)) return native.removeItem.value.apply(this, arguments); const state = data(this); requireArguments(1, arguments.length); key = text(key); trace({ store: state.name, operation: "removeItem", key }); state.values.delete(key); } }, clear: { configurable: true, enumerable: true, writable: true, value: function clear() { + if (!stores.has(this)) return native.clear.value.apply(this, arguments); const state = data(this); trace({ store: state.name, operation: "clear" }); state.values.clear(); } }, }); @@ -55,13 +63,18 @@ export function installWalletConnectStorage(window, trace = () => {}) { if (typeof key === "symbol") return Reflect.deleteProperty(target, key); prototype.removeItem.call(storage, key); return true; }, - ownKeys(target) { return [...Reflect.ownKeys(target), ...[...values.keys()].filter(visible)]; }, + // Native engines enumerate stored method names even though reads use the + // prototype method. Chromium omits the readonly length name; WebKit + // includes it. The engine is explicit for native-comparison tests. + ownKeys(target) { return [...Reflect.ownKeys(target), ...[...values.keys()] + .filter(key => key !== "length" || engine === "webkit")]; }, getOwnPropertyDescriptor(target, key) { - return visible(key) ? { value: values.get(key), configurable: true, enumerable: true, writable: true } + return values.has(key) ? { value: values.get(key), configurable: true, enumerable: true, writable: true } : Reflect.getOwnPropertyDescriptor(target, key); }, defineProperty(target, key, descriptor) { if (typeof key === "symbol") return Reflect.defineProperty(target, key, descriptor); + if (/wc@2:|keychain/i.test(key)) prototype.setItem.call(storage, key, descriptor.value); if ("get" in descriptor || "set" in descriptor || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) return false; prototype.setItem.call(storage, key, descriptor.value); return true; diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index e55804d68..7c03c9fe4 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -267,6 +267,17 @@ connection or account change. A completion error keeps that hash visible so the person can check the transaction before sending again. Unused signatures and ownership proofs still stop when the account, chain, or request expiry changes. +The opaque-frame SDK qualification test uses capsule-local +`walletconnect-storage.mjs` for browser Storage compatibility. Its memory holds +only UI preferences, such as wallet and network choice, and resets on reload. +The Runtime adapter owns sessions, pairings and cryptographic keys. The memory +store raises `SecurityError` for WalletConnect protocol and keychain names. +The focused native-Storage comparison runs in Chromium and WebKit with +`node --test scripts/walletconnect-storage-smoke.mjs`; the source gateway test +`content_sandbox_browser_walletconnect_sdk` checks the same SDK under capsule +CSP and sandbox headers. This test uses a deterministic relay and key/value +adapter; a paired reconnect requires the separate real-relay journey. + Inbox owns internet consent through the owner's passkey. Runtime connects only to `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through the existing local Exit. Runtime authenticates relay TLS, limits frame size and diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index 1c026fe36..0bc0f8918 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -681,10 +681,6 @@ async fn content_sandbox_browser_walletconnect_sdk() { std::fs::create_dir_all(capsule.join("vendor")).unwrap(); let sdk = repo.join("capsules/wallet-walletconnect/vendor/reown-appkit.js"); std::fs::copy(&sdk, capsule.join("vendor/reown-appkit.js")).unwrap(); - // The browser-local name keeps the same locked fixture import in the - // sandbox and unsandboxed SDK tests. The canonical vendor route is also - // hash-checked by the browser test. - std::fs::copy(sdk, capsule.join("browser/wc-sdk.js")).unwrap(); std::fs::copy( repo.join("scripts/lib/walletconnect-browser-fixture.mjs"), capsule.join("browser/wc-fixture.js"), diff --git a/scripts/lib/walletconnect-browser-fixture.mjs b/scripts/lib/walletconnect-browser-fixture.mjs index 76645d057..00f27859e 100644 --- a/scripts/lib/walletconnect-browser-fixture.mjs +++ b/scripts/lib/walletconnect-browser-fixture.mjs @@ -1,4 +1,4 @@ -import { connectWalletConnectEvm } from './wc-sdk.js'; +import { connectWalletConnectEvm } from './vendor/reown-appkit.js'; window.methods = []; window.nativeUrls = []; window.proposalReady = false; window.runtimeTrace = []; window.keys = Object.create(null); window.cancelled = false; window.failed = false; diff --git a/scripts/walletconnect-sandbox-smoke.mjs b/scripts/walletconnect-sandbox-smoke.mjs index b5c078a44..f3007d51c 100644 --- a/scripts/walletconnect-sandbox-smoke.mjs +++ b/scripts/walletconnect-sandbox-smoke.mjs @@ -66,6 +66,7 @@ for (const engine of ["chromium", "webkit"]) { assert.equal(run.state.fits, true); assert.ok(run.state.runtimeTrace.some(t => t.key.includes("keychain"))); assert.ok(run.state.storageTrace.every(t => !t.refused)); + if (evidence) await page.screenshot({ path: `${evidence}/${engine}-${width}.png` }); run.native = await page.evaluate(exerciseStorage); run.memory = await actualFrame.evaluate(exerciseStorage); assert.deepEqual(run.memory, run.native); @@ -82,7 +83,6 @@ for (const engine of ["chromium", "webkit"]) { return results; }); assert.deepEqual(run.refusals, Array(6).fill("SecurityError")); - if (evidence) await page.screenshot({ path: `${evidence}/${engine}-${width}.png` }); await frame.getByRole("button", { name: "Cancel", exact: true }).click(); await actualFrame.waitForFunction(() => window.cancelled); assert.equal(await frame.locator("dialog").count(), 0); diff --git a/scripts/walletconnect-sdk.test.mjs b/scripts/walletconnect-sdk.test.mjs index 466f8f640..1be246053 100644 --- a/scripts/walletconnect-sdk.test.mjs +++ b/scripts/walletconnect-sdk.test.mjs @@ -12,7 +12,7 @@ const fixture = readFileSync(new URL("./lib/walletconnect-browser-fixture.mjs", test("the locked SDK reaches QR through Home, stores its keys through Runtime, and cancels", { timeout: 45000 }, async () => { const server = http.createServer((req, res) => { res.setHeader("content-security-policy", "default-src 'self'; script-src 'self'; connect-src 'self'; frame-src 'self'; style-src 'self'"); - if (req.url === "/wc-sdk.js") { res.setHeader("content-type", "text/javascript"); res.end(bundle); } + if (req.url === "/vendor/reown-appkit.js") { res.setHeader("content-type", "text/javascript"); res.end(bundle); } else if (req.url === "/fixture.js") { res.setHeader("content-type", "text/javascript"); res.end(fixture); } else { res.setHeader("content-type", "text/html"); res.end(''); } }); diff --git a/scripts/walletconnect-storage-smoke.mjs b/scripts/walletconnect-storage-smoke.mjs index 4f920192b..7158844eb 100644 --- a/scripts/walletconnect-storage-smoke.mjs +++ b/scripts/walletconnect-storage-smoke.mjs @@ -5,7 +5,7 @@ import { readFileSync } from "node:fs"; import { requireProductSmokePlaywright } from "./product-smoke-browser.mjs"; import { exerciseStorage } from "./lib/walletconnect-storage-probe.mjs"; -const shim = readFileSync(new URL("../capsules/wallet-walletconnect/browser/walletconnect-storage.mjs", import.meta.url)); +const shim = readFileSync(process.env.WALLETCONNECT_STORAGE_MODULE || new URL("../capsules/wallet-walletconnect/browser/walletconnect-storage.mjs", import.meta.url)); for (const engine of ["chromium", "webkit"]) { test(`capsule memory Storage matches native ${engine} Storage`, { timeout: 45000 }, async () => { @@ -20,10 +20,11 @@ for (const engine of ["chromium", "webkit"]) { const page = await browser.newPage(); await page.goto(`http://127.0.0.1:${server.address().port}`); const native = await page.evaluate(exerciseStorage); - await page.evaluate(async () => { + await page.evaluate(async engine => { + window.nativeStorage = localStorage; const { installWalletConnectStorage } = await import("/shim.mjs"); - window.clearMemoryStorage = installWalletConnectStorage(window); - }); + window.clearMemoryStorage = installWalletConnectStorage(window, undefined, engine); + }, engine); const memory = await page.evaluate(exerciseStorage); assert.deepEqual(memory, native); assert.deepEqual(await page.evaluate(() => { @@ -33,6 +34,7 @@ for (const engine of ["chromium", "webkit"]) { s => s.setItem("wc@2:core:0.3//keychain", "fixture"), s => { s["wc@2:client:0.3//session"] = "fixture"; }, s => Object.defineProperty(s, "wc@2:core:0.3//pairing", { value: "fixture" }), + s => Storage.prototype.setItem.call(s, "wc@2:core:0.3//keychain", "fixture"), ]) { try { write(window[name]); errors.push("accepted"); } catch (error) { errors.push(error.name); } @@ -40,8 +42,21 @@ for (const engine of ["chromium", "webkit"]) { window[name].setItem("wallet-choice", "fixture"); } window.clearMemoryStorage(); - return { errors, lengths: [localStorage.length, sessionStorage.length] }; - }), { errors: Array(6).fill("SecurityError"), lengths: [0, 0] }); + nativeStorage.setItem("native-control", "works"); + const nativeControl = nativeStorage.getItem("native-control"); + nativeStorage.removeItem("native-control"); + return { errors, lengths: [localStorage.length, sessionStorage.length], nativeControl }; + }), { errors: Array(8).fill("SecurityError"), lengths: [0, 0], nativeControl: "works" }); + await page.evaluate(() => { + localStorage.setItem("wallet-choice", "fixture"); + sessionStorage.setItem("network-choice", "fixture"); + }); + await page.reload(); + assert.deepEqual(await page.evaluate(async engine => { + const { installWalletConnectStorage } = await import("/shim.mjs"); + installWalletConnectStorage(window, undefined, engine); + return [localStorage.length, sessionStorage.length]; + }, engine), [0, 0], "preferences reset on reload"); } finally { await browser?.close(); server.closeAllConnections(); From df68a3855c87c1ef8bad0320bda9b3068a3e7e01 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:14:02 -0500 Subject: [PATCH 035/139] test(walletconnect): configure isolated source gateway SDK fixture --- .../src/api/gateway_tests/content_sandbox.rs | 20 +++++++++++++++++++ scripts/walletconnect-sandbox-smoke.mjs | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index 0bc0f8918..f339665ff 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -660,6 +660,9 @@ async fn content_sandbox_browser_capsule_scripts() { #[tokio::test] #[ignore = "requires Playwright Chromium and WebKit; focused WalletConnect sandbox gate"] async fn content_sandbox_browser_walletconnect_sdk() { + use super::super::gateway::{ + WALLETCONNECT_CONFIG_PATH, WALLETCONNECT_CONFIG_SCHEMA, WALLETCONNECT_SDK_PACKAGE, + }; let dir = tempfile::tempdir().unwrap(); let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); for name in ["home", "wallet-walletconnect"] { @@ -681,6 +684,23 @@ async fn content_sandbox_browser_walletconnect_sdk() { std::fs::create_dir_all(capsule.join("vendor")).unwrap(); let sdk = repo.join("capsules/wallet-walletconnect/vendor/reown-appkit.js"); std::fs::copy(&sdk, capsule.join("vendor/reown-appkit.js")).unwrap(); + for path in ["vendor/package-lock.json", "vendor/other.js"] { + std::fs::write(capsule.join(path), "private fixture").unwrap(); + } + let config = dir.path().join(WALLETCONNECT_CONFIG_PATH); + std::fs::create_dir_all(config.parent().unwrap()).unwrap(); + std::fs::write( + config, + serde_json::to_vec(&json!({ + "schema": WALLETCONNECT_CONFIG_SCHEMA, + "project_id": "fixture-project", + "sdk_package": WALLETCONNECT_SDK_PACKAGE, + "sdk_version": "2.23.9", + "sdk_sha256": "6cff318e63fa0b8c9cc7ee95ce92d5a5470df6cd742a8ad8c2033ce829bb1895", + })) + .unwrap(), + ) + .unwrap(); std::fs::copy( repo.join("scripts/lib/walletconnect-browser-fixture.mjs"), capsule.join("browser/wc-fixture.js"), diff --git a/scripts/walletconnect-sandbox-smoke.mjs b/scripts/walletconnect-sandbox-smoke.mjs index f3007d51c..3925b10b0 100644 --- a/scripts/walletconnect-sandbox-smoke.mjs +++ b/scripts/walletconnect-sandbox-smoke.mjs @@ -13,7 +13,7 @@ const expectedHash = "6cff318e63fa0b8c9cc7ee95ce92d5a5470df6cd742a8ad8c2033ce829 const sdk = await fetch(`${origin}/apps/wallet-walletconnect/vendor/reown-appkit.js`); assert.equal(sdk.status, 200); assert.equal(createHash("sha256").update(Buffer.from(await sdk.arrayBuffer())).digest("hex"), expectedHash); -for (const path of ["capsule.json", "main.wasm", "vendor/package-lock.json", "vendor/other.js"]) { +for (const path of ["capsule.json", "wallet-walletconnect.wasm", "vendor/package-lock.json", "vendor/other.js"]) { assert.equal((await fetch(`${origin}/apps/wallet-walletconnect/${path}`)).status, 404, path); } const result = { sdkSha256: expectedHash, runs: [] }; From ab06406097e844eb0c6e5267bd422d549f66e711 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:19:01 -0500 Subject: [PATCH 036/139] test(walletconnect): prove preferences leave native storage empty --- docs/WALLET_PROVIDER.md | 5 +++-- scripts/walletconnect-sandbox-smoke.mjs | 5 +++-- scripts/walletconnect-storage-smoke.mjs | 2 ++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 7c03c9fe4..2d7757765 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -268,8 +268,9 @@ person can check the transaction before sending again. Unused signatures and ownership proofs still stop when the account, chain, or request expiry changes. The opaque-frame SDK qualification test uses capsule-local -`walletconnect-storage.mjs` for browser Storage compatibility. Its memory holds -only UI preferences, such as wallet and network choice, and resets on reload. +`walletconnect-storage.mjs` for browser Storage compatibility. Its non-protocol +memory supports UI preferences, such as wallet and network choice, and resets +on reload. The Runtime adapter owns sessions, pairings and cryptographic keys. The memory store raises `SecurityError` for WalletConnect protocol and keychain names. The focused native-Storage comparison runs in Chromium and WebKit with diff --git a/scripts/walletconnect-sandbox-smoke.mjs b/scripts/walletconnect-sandbox-smoke.mjs index 3925b10b0..edab807a8 100644 --- a/scripts/walletconnect-sandbox-smoke.mjs +++ b/scripts/walletconnect-sandbox-smoke.mjs @@ -76,18 +76,19 @@ for (const engine of ["chromium", "webkit"]) { s => s.setItem("wc@2:core:0.3//keychain", "fixture"), s => { s["wc@2:client:0.3//session"] = "fixture"; }, s => Object.defineProperty(s, "wc@2:core:0.3//pairing", { value: "fixture" }), + s => Storage.prototype.setItem.call(s, "wc@2:core:0.3//keychain", "fixture"), ]) { try { write(window[name]); results.push("accepted"); } catch (error) { results.push(error.name); } } return results; }); - assert.deepEqual(run.refusals, Array(6).fill("SecurityError")); + assert.deepEqual(run.refusals, Array(8).fill("SecurityError")); await frame.getByRole("button", { name: "Cancel", exact: true }).click(); await actualFrame.waitForFunction(() => window.cancelled); assert.equal(await frame.locator("dialog").count(), 0); run.cancelled = true; - console.log(`PASS ${engine} ${width}: opaque SDK, QR, Runtime writes, native Storage parity, protocol refusal, Cancel`); + console.log(`PASS ${engine} ${width}: opaque SDK, QR, Runtime-adapter fixture writes, covered native Storage operations, protocol refusal, Cancel`); } catch (error) { run.failure = error.message; failures.push(`${engine} ${width}: ${error.message}`); diff --git a/scripts/walletconnect-storage-smoke.mjs b/scripts/walletconnect-storage-smoke.mjs index 7158844eb..8fd917b53 100644 --- a/scripts/walletconnect-storage-smoke.mjs +++ b/scripts/walletconnect-storage-smoke.mjs @@ -52,6 +52,8 @@ for (const engine of ["chromium", "webkit"]) { sessionStorage.setItem("network-choice", "fixture"); }); await page.reload(); + assert.deepEqual(await page.evaluate(() => [localStorage.length, sessionStorage.length]), + [0, 0], "preference writes leave native persistent storage empty"); assert.deepEqual(await page.evaluate(async engine => { const { installWalletConnectStorage } = await import("/shim.mjs"); installWalletConnectStorage(window, undefined, engine); From 30d13115a2a30df754495ebbb8a665aa9fcc2464 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:21:14 -0500 Subject: [PATCH 037/139] test(walletconnect): use enclosing gateway fixture constants --- .../elastos-server/src/api/gateway_tests/content_sandbox.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index f339665ff..08a629244 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -660,9 +660,6 @@ async fn content_sandbox_browser_capsule_scripts() { #[tokio::test] #[ignore = "requires Playwright Chromium and WebKit; focused WalletConnect sandbox gate"] async fn content_sandbox_browser_walletconnect_sdk() { - use super::super::gateway::{ - WALLETCONNECT_CONFIG_PATH, WALLETCONNECT_CONFIG_SCHEMA, WALLETCONNECT_SDK_PACKAGE, - }; let dir = tempfile::tempdir().unwrap(); let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); for name in ["home", "wallet-walletconnect"] { From c58831cd624893f8a2a51f33dc1e23a2412a7996 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:40:06 -0500 Subject: [PATCH 038/139] test(walletconnect): exercise opaque-frame real relay preflight --- .../wallet/walletconnect_real_relay.rs | 148 ++++++++++++++---- .../walletconnect-real-browser-fixture.mjs | 33 ++++ .../walletconnect-real-preflight-smoke.mjs | 97 ++++++++++++ 3 files changed, 249 insertions(+), 29 deletions(-) create mode 100644 scripts/lib/walletconnect-real-browser-fixture.mjs create mode 100644 scripts/walletconnect-real-preflight-smoke.mjs diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 3e7e51355..125fbb687 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -2,37 +2,21 @@ use super::*; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use ed25519_dalek::{Signer, SigningKey}; +use std::io::Read; use tokio::net::TcpStream; -// Matches @walletconnect/relay-auth's locked signJWT/encodeIss implementation. -fn relay_auth() -> String { - let key = SigningKey::generate(&mut rand::rngs::OsRng); - let mut public = vec![0xed, 0x01]; - public.extend_from_slice(key.verifying_key().as_bytes()); - let issuer = format!("did:key:z{}", bs58::encode(public).into_string()); - let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","typ":"JWT"}"#); - let payload = URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&json!({ - "iss": issuer, "sub": gateway_home_token::uuid_like_token(), - "aud": "wss://relay.walletconnect.org", "iat": now_ts(), "exp": now_ts() + 300, - })) - .unwrap(), - ); - let data = format!("{header}.{payload}"); - format!( - "{data}.{}", - URL_SAFE_NO_PAD.encode(key.sign(data.as_bytes()).to_bytes()) - ) -} - -#[tokio::test] -#[ignore = "operator acceptance: needs ELASTOS_WALLETCONNECT_PROJECT_FILE and the real relay"] -async fn walletconnect_real_project_opens_through_runtime_and_exit() { +fn operator_project() -> String { let file = std::env::var_os("ELASTOS_WALLETCONNECT_PROJECT_FILE") .expect("set ELASTOS_WALLETCONNECT_PROJECT_FILE"); - let bytes = gateway_walletconnect::read_bytes(std::path::Path::new(&file), 129) - .expect("read bounded operator project file") - .expect("operator project file exists"); + // The trusted operator input may be a pipe on a rented test machine. Read + // at most 130 bytes; the driver owns the pipe and the test time limit. + let mut bytes = Vec::new(); + std::io::Read::take( + std::fs::File::open(file).expect("open operator project file"), + 130, + ) + .read_to_end(&mut bytes) + .expect("read bounded operator project file"); let project = std::str::from_utf8(&bytes) .expect("operator project file is UTF-8") .trim(); @@ -40,6 +24,10 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { assert!(project .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')); + project.to_owned() +} + +async fn real_fixture(project: &str) -> Fixture { let mut f = Fixture::new().await; assert!(!f.addr.ends_with(":8090")); let config_path = f.data.path().join(WALLETCONNECT_CONFIG_PATH); @@ -91,10 +79,39 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { ) .await .unwrap(); + f +} + +// Matches @walletconnect/relay-auth's locked signJWT/encodeIss implementation. +fn relay_auth() -> String { + let key = SigningKey::generate(&mut rand::rngs::OsRng); + let mut public = vec![0xed, 0x01]; + public.extend_from_slice(key.verifying_key().as_bytes()); + let issuer = format!("did:key:z{}", bs58::encode(public).into_string()); + let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","typ":"JWT"}"#); + let payload = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&json!({ + "iss": issuer, "sub": gateway_home_token::uuid_like_token(), + "aud": "wss://relay.walletconnect.org", "iat": now_ts(), "exp": now_ts() + 300, + })) + .unwrap(), + ); + let data = format!("{header}.{payload}"); + format!( + "{data}.{}", + URL_SAFE_NO_PAD.encode(key.sign(data.as_bytes()).to_bytes()) + ) +} + +#[tokio::test] +#[ignore = "operator acceptance: needs ELASTOS_WALLETCONNECT_PROJECT_FILE and the real relay"] +async fn walletconnect_real_project_opens_through_runtime_and_exit() { + let project = operator_project(); + let f = real_fixture(&project).await; f.allow().await; let mut url = url::Url::parse("wss://relay.walletconnect.org/").unwrap(); url.query_pairs_mut() - .append_pair("projectId", project) + .append_pair("projectId", &project) .append_pair("auth", &relay_auth()); let mut socket = f.connect(&f.connector, url.as_str()).await; let first = tokio::time::timeout(Duration::from_secs(30), socket.next()).await; @@ -119,5 +136,78 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { "real relay subscription failed" ); socket.close(None).await.unwrap(); - println!("PASS: Runtime -> Exit harness -> authenticated Reown WSS upgrade and subscription; project ; ephemeral localhost port; no 401/403"); + println!("PASS: Runtime -> Exit harness -> authenticated Reown WSS upgrade and subscription; project file set; ephemeral localhost port; no 401/403"); +} + +#[tokio::test] +#[ignore = "operator acceptance: real relay, pinned SDK, Playwright Chromium and WebKit"] +async fn walletconnect_real_project_opaque_preflight() { + use tokio::io::AsyncWriteExt; + let project = operator_project(); + let f = real_fixture(&project).await; + let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); + for name in ["home", "wallet-walletconnect"] { + let destination = f.data.path().join("capsules").join(name); + activate_test_capsule(f.data.path(), name); + std::fs::create_dir_all(&destination).unwrap(); + std::fs::copy( + repo.join("capsules").join(name).join("capsule.json"), + destination.join("capsule.json"), + ) + .unwrap(); + copy_operator_site( + &repo.join("capsules").join(name).join("browser"), + &destination.join("browser"), + ); + write_test_wasm_entrypoint(f.data.path(), name); + } + let capsule = f.data.path().join("capsules/wallet-walletconnect"); + let sdk = + std::fs::read(repo.join("capsules/wallet-walletconnect/vendor/reown-appkit.js")).unwrap(); + std::fs::write(capsule.join("vendor/reown-appkit.js"), &sdk).unwrap(); + crate::auth::atomic_write( + &f.data.path().join(WALLETCONNECT_CONFIG_PATH), + &serde_json::to_vec(&json!({ + "schema": WALLETCONNECT_CONFIG_SCHEMA, "project_id": project, + "sdk_package": WALLETCONNECT_SDK_PACKAGE, "sdk_version": "2.23.9", + "sdk_sha256": format!("{:x}", Sha256::digest(&sdk)), + })) + .unwrap(), + ) + .unwrap(); + std::fs::copy( + repo.join("scripts/lib/walletconnect-real-browser-fixture.mjs"), + capsule.join("browser/wc-real-fixture.js"), + ) + .unwrap(); + std::fs::write( + capsule.join("browser/wc-real.html"), + "", + ) + .unwrap(); + f.allow().await; + let input = serde_json::to_vec(&json!({ + "origin": format!("http://{}", f.addr), "connector": f.connector, "projectId": project, + })) + .unwrap(); + let mut child = tokio::process::Command::new("node") + .arg(repo.join("scripts/walletconnect-real-preflight-smoke.mjs")) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(&input).await.unwrap(); + let output = tokio::time::timeout(Duration::from_secs(150), child.wait_with_output()) + .await + .expect("real relay browser gate timeout") + .unwrap(); + println!("{}", String::from_utf8_lossy(&output.stdout)); + // The Node driver emits only bounded, value-free evidence. SDK diagnostics + // can contain relay credentials, so stderr remains private to this process. + assert!( + output.status.success(), + "real relay opaque preflight failed; see structured evidence (project file set)" + ); } diff --git a/scripts/lib/walletconnect-real-browser-fixture.mjs b/scripts/lib/walletconnect-real-browser-fixture.mjs new file mode 100644 index 000000000..2c95741a2 --- /dev/null +++ b/scripts/lib/walletconnect-real-browser-fixture.mjs @@ -0,0 +1,33 @@ +// This fixture uses the production routes with this frame's own launch token. +import { installWalletConnectStorage } from './walletconnect-storage.mjs'; +window.storageTrace = []; +installWalletConnectStorage(window, entry => window.storageTrace.push(entry)); +window.runtimeTrace = []; +window.phase = 'options'; +const options = await window.walletConnectTestOptions(); +const origin = new URL(import.meta.url).origin; +const api = async (resource, input = {}) => { + const response = await fetch(`${origin}/api/apps/wallet-walletconnect/${resource}`, { + ...input, headers: { 'content-type':'application/json', 'x-elastos-home-token':options.connector }, + }); + window.runtimeTrace.push({ resource, status:response.status }); + if (!response.ok) { + window.refusal = { resource, status:response.status }; + throw new Error('Runtime refused the connector resource'); + } + return response.json(); +}; +try { + window.phase = 'import'; + const { connectWalletConnectEvm } = await import('./vendor/reown-appkit.js'); + window.phase = 'connect'; + window.provider = await connectWalletConnectEvm({ + contextKey:'wallet-walletconnect', projectId:options.projectId, chains:[1], api, + runtimeUrl:`${origin}/api/apps/wallet-walletconnect`, + relayUrl:`${origin.replace(/^http/, 'ws')}/api/apps/wallet-walletconnect/relay`, + metadata:{name:'Isolated recovery test', description:'Throwaway test wallet', url:origin, icons:[]}, + }); + window.phase = 'connected'; +} catch { + window.failed = true; +} diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs new file mode 100644 index 000000000..1d71f776e --- /dev/null +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -0,0 +1,97 @@ +// Opt-in preflight before paired recovery: use real Runtime resources and relay. +// The Rust source gateway supplies private options through stdin. +// SDK logs stay in process memory. Evidence contains resource names and status. +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { importProductSmokePlaywright } from './product-smoke-browser.mjs'; +const require = createRequire(new URL('./walletconnect/package.json', import.meta.url)); +const { SignClient } = require('@walletconnect/sign-client'); +const { privateKeyToAccount, generatePrivateKey } = require('viem/accounts'); +let input = ''; +for await (const chunk of process.stdin) { input += chunk; assert.ok(input.length < 16384); } +const options = JSON.parse(input); +const result = { project: 'project file set', runs: [] }; +const evidence = process.env.WALLETCONNECT_SCREENSHOTS; +let rejections = 0; +const logger = Object.fromEntries(['trace','debug','info','warn','error','fatal'].map(level => [level, () => {}])); +logger.child = () => logger; logger.level = 'silent'; +process.on('unhandledRejection', () => rejections++); +// Prevent third-party diagnostic output from exposing URLs or credentials. +const emit = console.log.bind(console); +console.log = console.warn = console.error = () => {}; +let exitCode = 1; +try { + const playwright = await importProductSmokePlaywright(); + for (const engine of ['chromium', 'webkit']) { + const run = { engine, walletReady:false, paired:false }; + result.runs.push(run); + let browser, wallet; + try { + const signer = privateKeyToAccount(generatePrivateKey()); + wallet = await SignClient.init({ projectId:options.projectId, logger, telemetryEnabled:false, + metadata:{name:'Disposable test wallet', description:'Isolated recovery fixture', url:'http://localhost', icons:[]} }); + run.walletReady = true; + wallet.on('session_proposal', async proposal => { + const approval = await wallet.approve({ id:proposal.id, namespaces:{eip155:{ + chains:['eip155:1'], accounts:[`eip155:1:${signer.address}`], + methods:['personal_sign','eth_sendTransaction'], events:['accountsChanged','chainChanged'], + }} }); + await approval.acknowledged(); + run.paired = true; + }); + wallet.on('session_request', async event => { + const request = event.params.request; + assert.equal(request.method, 'personal_sign'); + const signature = await signer.signMessage({message:{raw:request.params[0]}}); + await wallet.respond({ topic:event.topic, response:{id:event.id,jsonrpc:'2.0',result:signature} }); + }); + browser = await playwright[engine].launch({headless:true}); + run.version = browser.version(); + const context = await browser.newContext(); + await context.exposeBinding('walletConnectTestOptions', () => options); + await context.route('**/*', route => new URL(route.request().url()).origin === options.origin ? route.continue() : route.abort()); + const page = await context.newPage(); + const home = await page.goto(`${options.origin}/apps/home/`); + assert.equal(home.status(), 200); + const response = await fetch(`${options.origin}/apps/wallet-walletconnect/wc-real.html`); + run.csp = response.headers.get('content-security-policy'); + assert.ok(run.csp.startsWith('sandbox allow-scripts allow-forms allow-downloads;')); + await page.evaluate(origin => { + const frame = document.createElement('iframe'); + frame.sandbox = 'allow-downloads allow-forms allow-modals allow-pointer-lock allow-scripts'; + frame.src = `${origin}/apps/wallet-walletconnect/wc-real.html`; + document.body.append(frame); + }, options.origin); + await page.waitForFunction(() => document.querySelector('iframe')?.contentWindow != null); + let frame; + for (let i=0; i<100 && !frame; i++) { frame=page.frames().find(f => f.url().endsWith('/wc-real.html')); if (!frame) await new Promise(resolve => setTimeout(resolve,50)); } + assert.ok(frame); + // The initial Runtime-backed keychain read precedes any pairing proposal. + await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width > 0, null, {timeout:30000}); + run.state = await frame.evaluate(() => ({origin:self.origin,phase:window.phase, + refusal:window.refusal, runtimeTrace:window.runtimeTrace, storageTrace:window.storageTrace})); + assert.equal(run.state.origin, 'null'); + assert.equal(run.state.refusal, undefined, 'connector launch token must admit the Runtime SDK store'); + assert.ok(await frame.locator('dialog[open] canvas').count()); + run.status = 'PASS'; + } catch { + run.status = 'FAIL'; + } finally { + await browser?.close(); + if (wallet) { + for (const session of wallet.session.getAll()) await wallet.disconnect({topic:session.topic,reason:{code:6000,message:'Test ended'}}).catch(() => {}); + await wallet.core.relayer.transportClose().catch(() => {}); + } + } + // The brief requires an immediate stop at the first Chromium blocker. + if (engine === 'chromium' && run.status !== 'PASS') break; + } +} catch { result.setup = 'FAIL'; } +exitCode = result.runs.length === 2 && result.runs.every(run => run.status === 'PASS') ? 0 : 1; +if (evidence) { + await mkdir(evidence, {recursive:true}); + await writeFile(`${evidence}/real-preflight.json`, JSON.stringify(result,null,2)); +} +emit(JSON.stringify(result)); +process.exit(exitCode); From a6550680bfd7d88fcd22160c542172388936ad67 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:43:31 -0500 Subject: [PATCH 039/139] test(walletconnect): share capsule fixture helper and keep peer storage in memory --- .../src/api/gateway_tests/content_sandbox.rs | 2 +- .../wallet/walletconnect_real_relay.rs | 6 +++++- scripts/walletconnect-real-preflight-smoke.mjs | 14 +++++++++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index 08a629244..d13847292 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -438,7 +438,7 @@ async fn content_sandbox_opaque_cookie_requests_require_explicit_launch_authorit } } -fn copy_operator_site(source: &std::path::Path, destination: &std::path::Path) { +pub(super) fn copy_operator_site(source: &std::path::Path, destination: &std::path::Path) { std::fs::create_dir_all(destination).unwrap(); for entry in std::fs::read_dir(source).unwrap() { let entry = entry.unwrap(); diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 125fbb687..bebdf05e2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -17,6 +17,10 @@ fn operator_project() -> String { ) .read_to_end(&mut bytes) .expect("read bounded operator project file"); + assert!( + bytes.len() <= 129, + "operator project input exceeds its limit" + ); let project = std::str::from_utf8(&bytes) .expect("operator project file is UTF-8") .trim(); @@ -155,7 +159,7 @@ async fn walletconnect_real_project_opaque_preflight() { destination.join("capsule.json"), ) .unwrap(); - copy_operator_site( + super::super::super::content_sandbox::copy_operator_site( &repo.join("capsules").join(name).join("browser"), &destination.join("browser"), ); diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index 1d71f776e..e48928d34 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -4,6 +4,7 @@ import assert from 'node:assert/strict'; import { createRequire } from 'node:module'; import { mkdir, writeFile } from 'node:fs/promises'; +import { runtimeStorage } from './walletconnect/runtime-storage.mjs'; import { importProductSmokePlaywright } from './product-smoke-browser.mjs'; const require = createRequire(new URL('./walletconnect/package.json', import.meta.url)); const { SignClient } = require('@walletconnect/sign-client'); @@ -29,9 +30,17 @@ try { let browser, wallet; try { const signer = privateKeyToAccount(generatePrivateKey()); - wallet = await SignClient.init({ projectId:options.projectId, logger, telemetryEnabled:false, + run.phase = 'wallet-init'; + const values = Object.create(null); + const storage = runtimeStorage(async (_, input) => { + if (input) { const {key,value} = JSON.parse(input.body); if (value === null) delete values[key]; else values[key] = value; } + return structuredClone(values); + }); + wallet = await SignClient.init({ projectId:options.projectId, logger, telemetryEnabled:false, storage, metadata:{name:'Disposable test wallet', description:'Isolated recovery fixture', url:'http://localhost', icons:[]} }); + await wallet.core.relayer.transportOpen(); run.walletReady = true; + run.phase = 'browser'; wallet.on('session_proposal', async proposal => { const approval = await wallet.approve({ id:proposal.id, namespaces:{eip155:{ chains:['eip155:1'], accounts:[`eip155:1:${signer.address}`], @@ -52,11 +61,13 @@ try { await context.exposeBinding('walletConnectTestOptions', () => options); await context.route('**/*', route => new URL(route.request().url()).origin === options.origin ? route.continue() : route.abort()); const page = await context.newPage(); + run.phase = 'home'; const home = await page.goto(`${options.origin}/apps/home/`); assert.equal(home.status(), 200); const response = await fetch(`${options.origin}/apps/wallet-walletconnect/wc-real.html`); run.csp = response.headers.get('content-security-policy'); assert.ok(run.csp.startsWith('sandbox allow-scripts allow-forms allow-downloads;')); + run.phase = 'capsule'; await page.evaluate(origin => { const frame = document.createElement('iframe'); frame.sandbox = 'allow-downloads allow-forms allow-modals allow-pointer-lock allow-scripts'; @@ -67,6 +78,7 @@ try { let frame; for (let i=0; i<100 && !frame; i++) { frame=page.frames().find(f => f.url().endsWith('/wc-real.html')); if (!frame) await new Promise(resolve => setTimeout(resolve,50)); } assert.ok(frame); + run.phase = 'runtime-store'; // The initial Runtime-backed keychain read precedes any pairing proposal. await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width > 0, null, {timeout:30000}); run.state = await frame.evaluate(() => ({origin:self.origin,phase:window.phase, From 78bc8b860dfa3f11284633bf0541a16838246cca Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 12:52:32 -0500 Subject: [PATCH 040/139] test(walletconnect): preserve the first capsule admission failure --- .../walletconnect-real-browser-fixture.mjs | 19 ++- .../walletconnect-real-preflight-smoke.mjs | 111 +++++++----------- 2 files changed, 57 insertions(+), 73 deletions(-) diff --git a/scripts/lib/walletconnect-real-browser-fixture.mjs b/scripts/lib/walletconnect-real-browser-fixture.mjs index 2c95741a2..ec7f55547 100644 --- a/scripts/lib/walletconnect-real-browser-fixture.mjs +++ b/scripts/lib/walletconnect-real-browser-fixture.mjs @@ -1,18 +1,26 @@ -// This fixture uses the production routes with this frame's own launch token. +// Playwright provisions private options; production routes receive only this +// capsule's launch token. This preflight stops at the first resource refusal. import { installWalletConnectStorage } from './walletconnect-storage.mjs'; window.storageTrace = []; -installWalletConnectStorage(window, entry => window.storageTrace.push(entry)); +installWalletConnectStorage(window, entry => { + if (window.storageTrace.length < 128) window.storageTrace.push({ + store:entry.store, operation:entry.operation, refused:!!entry.refused, + protocol:/wc@2:|keychain/i.test(entry.key || ''), + }); +}); window.runtimeTrace = []; window.phase = 'options'; const options = await window.walletConnectTestOptions(); const origin = new URL(import.meta.url).origin; const api = async (resource, input = {}) => { + const trace = {resource, status:'request'}; + if (window.runtimeTrace.length < 128) window.runtimeTrace.push(trace); const response = await fetch(`${origin}/api/apps/wallet-walletconnect/${resource}`, { ...input, headers: { 'content-type':'application/json', 'x-elastos-home-token':options.connector }, }); - window.runtimeTrace.push({ resource, status:response.status }); + trace.status = response.status; if (!response.ok) { - window.refusal = { resource, status:response.status }; + window.refusal ??= { resource, status:response.status }; throw new Error('Runtime refused the connector resource'); } return response.json(); @@ -28,6 +36,7 @@ try { metadata:{name:'Isolated recovery test', description:'Throwaway test wallet', url:origin, icons:[]}, }); window.phase = 'connected'; -} catch { +} catch (error) { + window.errorName = ['Error','TypeError','SecurityError'].includes(error.name) ? error.name : 'Error'; window.failed = true; } diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index e48928d34..c2ad858de 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -1,109 +1,84 @@ -// Opt-in preflight before paired recovery: use real Runtime resources and relay. -// The Rust source gateway supplies private options through stdin. -// SDK logs stay in process memory. Evidence contains resource names and status. +// Opt-in admission preflight before paired recovery. Private fixture options +// enter through stdin; browser evidence contains resource names and status. import assert from 'node:assert/strict'; -import { createRequire } from 'node:module'; import { mkdir, writeFile } from 'node:fs/promises'; -import { runtimeStorage } from './walletconnect/runtime-storage.mjs'; import { importProductSmokePlaywright } from './product-smoke-browser.mjs'; -const require = createRequire(new URL('./walletconnect/package.json', import.meta.url)); -const { SignClient } = require('@walletconnect/sign-client'); -const { privateKeyToAccount, generatePrivateKey } = require('viem/accounts'); let input = ''; for await (const chunk of process.stdin) { input += chunk; assert.ok(input.length < 16384); } const options = JSON.parse(input); -const result = { project: 'project file set', runs: [] }; +const result = { project:'project file set', runs:[] }; const evidence = process.env.WALLETCONNECT_SCREENSHOTS; -let rejections = 0; -const logger = Object.fromEntries(['trace','debug','info','warn','error','fatal'].map(level => [level, () => {}])); -logger.child = () => logger; logger.level = 'silent'; -process.on('unhandledRejection', () => rejections++); -// Prevent third-party diagnostic output from exposing URLs or credentials. const emit = console.log.bind(console); console.log = console.warn = console.error = () => {}; -let exitCode = 1; +const deadline = setTimeout(() => { result.timeout = true; emit(JSON.stringify(result)); process.exit(1); }, 120000); +const expectedCsp = `sandbox allow-scripts allow-forms allow-downloads; default-src ${options.origin}; script-src 'self' 'wasm-unsafe-eval' ${options.origin}; style-src ${options.origin} 'unsafe-inline'; img-src ${options.origin} blob: data:; connect-src ${options.origin} ${options.origin.replace(/^http/, 'ws')}; frame-src ${options.origin}; object-src 'none'; base-uri 'none'; form-action ${options.origin}`; try { const playwright = await importProductSmokePlaywright(); for (const engine of ['chromium', 'webkit']) { - const run = { engine, walletReady:false, paired:false }; + const run = { engine, paired:false, network:[] }; result.runs.push(run); - let browser, wallet; + let browser, frame; try { - const signer = privateKeyToAccount(generatePrivateKey()); - run.phase = 'wallet-init'; - const values = Object.create(null); - const storage = runtimeStorage(async (_, input) => { - if (input) { const {key,value} = JSON.parse(input.body); if (value === null) delete values[key]; else values[key] = value; } - return structuredClone(values); - }); - wallet = await SignClient.init({ projectId:options.projectId, logger, telemetryEnabled:false, storage, - metadata:{name:'Disposable test wallet', description:'Isolated recovery fixture', url:'http://localhost', icons:[]} }); - await wallet.core.relayer.transportOpen(); - run.walletReady = true; run.phase = 'browser'; - wallet.on('session_proposal', async proposal => { - const approval = await wallet.approve({ id:proposal.id, namespaces:{eip155:{ - chains:['eip155:1'], accounts:[`eip155:1:${signer.address}`], - methods:['personal_sign','eth_sendTransaction'], events:['accountsChanged','chainChanged'], - }} }); - await approval.acknowledged(); - run.paired = true; - }); - wallet.on('session_request', async event => { - const request = event.params.request; - assert.equal(request.method, 'personal_sign'); - const signature = await signer.signMessage({message:{raw:request.params[0]}}); - await wallet.respond({ topic:event.topic, response:{id:event.id,jsonrpc:'2.0',result:signature} }); - }); - browser = await playwright[engine].launch({headless:true}); + browser = await playwright[engine].launch({headless:true, timeout:15000}); run.version = browser.version(); const context = await browser.newContext(); - await context.exposeBinding('walletConnectTestOptions', () => options); + // Fixture provisioning only; Runtime APIs still receive the capsule token. + await context.exposeBinding('walletConnectTestOptions', source => { + assert.equal(source.frame.url(), `${options.origin}/apps/wallet-walletconnect/wc-real.html`); + return options; + }); await context.route('**/*', route => new URL(route.request().url()).origin === options.origin ? route.continue() : route.abort()); + context.on('response', response => { + const path = new URL(response.url()).pathname; + if (path.startsWith('/api/apps/wallet-walletconnect/') && run.network.length < 128) { + run.network.push({resource:path.split('/').at(-1), status:response.status()}); + } + }); const page = await context.newPage(); run.phase = 'home'; - const home = await page.goto(`${options.origin}/apps/home/`); - assert.equal(home.status(), 200); - const response = await fetch(`${options.origin}/apps/wallet-walletconnect/wc-real.html`); - run.csp = response.headers.get('content-security-policy'); - assert.ok(run.csp.startsWith('sandbox allow-scripts allow-forms allow-downloads;')); + assert.equal((await page.goto(`${options.origin}/apps/home/`, {timeout:10000})).status(), 200); run.phase = 'capsule'; + const document = page.waitForResponse(response => response.url() === `${options.origin}/apps/wallet-walletconnect/wc-real.html`, {timeout:10000}); await page.evaluate(origin => { - const frame = document.createElement('iframe'); + const frame = window.document.createElement('iframe'); + frame.id = 'wc-real-preflight'; frame.sandbox = 'allow-downloads allow-forms allow-modals allow-pointer-lock allow-scripts'; frame.src = `${origin}/apps/wallet-walletconnect/wc-real.html`; - document.body.append(frame); + window.document.body.append(frame); }, options.origin); - await page.waitForFunction(() => document.querySelector('iframe')?.contentWindow != null); - let frame; - for (let i=0; i<100 && !frame; i++) { frame=page.frames().find(f => f.url().endsWith('/wc-real.html')); if (!frame) await new Promise(resolve => setTimeout(resolve,50)); } + run.csp = (await (await document).allHeaders())['content-security-policy']; + assert.equal(run.csp, expectedCsp); + frame = await (await page.waitForSelector('#wc-real-preflight', {timeout:10000})).contentFrame(); assert.ok(frame); run.phase = 'runtime-store'; - // The initial Runtime-backed keychain read precedes any pairing proposal. - await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width > 0, null, {timeout:30000}); - run.state = await frame.evaluate(() => ({origin:self.origin,phase:window.phase, - refusal:window.refusal, runtimeTrace:window.runtimeTrace, storageTrace:window.storageTrace})); - assert.equal(run.state.origin, 'null'); - assert.equal(run.state.refusal, undefined, 'connector launch token must admit the Runtime SDK store'); - assert.ok(await frame.locator('dialog[open] canvas').count()); + await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width > 0, null, {timeout:20000}); + assert.equal(await frame.evaluate(() => window.failed), undefined); + assert.equal(await frame.evaluate(() => self.origin), 'null'); + assert.equal(await frame.locator('dialog[open] canvas').count(), 1); run.status = 'PASS'; } catch { run.status = 'FAIL'; } finally { - await browser?.close(); - if (wallet) { - for (const session of wallet.session.getAll()) await wallet.disconnect({topic:session.topic,reason:{code:6000,message:'Test ended'}}).catch(() => {}); - await wallet.core.relayer.transportClose().catch(() => {}); + if (frame) { + try { + run.state = await Promise.race([ + frame.evaluate(() => ({origin:self.origin, phase:window.phase, refusal:window.refusal, + errorName:window.errorName, runtimeTrace:window.runtimeTrace, storageTrace:window.storageTrace})), + new Promise((_, reject) => setTimeout(() => reject(new Error('state timeout')), 3000)), + ]); + } catch { run.stateUnavailable = true; } } + await browser?.close(); } - // The brief requires an immediate stop at the first Chromium blocker. + // Stop at the first Chromium blocker, as required by the round's brief. if (engine === 'chromium' && run.status !== 'PASS') break; } } catch { result.setup = 'FAIL'; } -exitCode = result.runs.length === 2 && result.runs.every(run => run.status === 'PASS') ? 0 : 1; if (evidence) { await mkdir(evidence, {recursive:true}); await writeFile(`${evidence}/real-preflight.json`, JSON.stringify(result,null,2)); } +clearTimeout(deadline); emit(JSON.stringify(result)); -process.exit(exitCode); +process.exit(result.runs.length === 2 && result.runs.every(run => run.status === 'PASS') ? 0 : 1); From e638f113c8f26a78c837ae2d6a8f3ead5d34fe69 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:20:27 -0500 Subject: [PATCH 041/139] test(walletconnect): require capsule-owned storage and opaque relay authority --- .../api/gateway_tests/wallet/walletconnect.rs | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 1a95d3835..46d6bc2ba 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -812,3 +812,138 @@ async fn walletconnect_revoked_owner_cannot_send_another_relay_frame() { Some(Ok(Message::Close(_))) | None )); } + +// Real frontdoor and app routes, carrying only the capsule launch token. +async fn capsule_route(f: &Fixture, token: &str, path: &str, body: Option) -> StatusCode { + f.app + .clone() + .oneshot( + Request::builder() + .header(HOST, &f.addr) + .header("origin", "null") + .header("x-elastos-home-token", token) + .header(CONTENT_TYPE, "application/json") + .uri(path) + .method(if body.is_some() { "POST" } else { "GET" }) + .body(body.map_or_else(Body::empty, |v| Body::from(v.to_string()))) + .unwrap(), + ) + .await + .unwrap() + .status() +} + +#[tokio::test] +async fn walletconnect_capsule_owns_storage_and_admission() { + let f = Fixture::new().await; + f.allow().await; + let context = runtime_wallet_authority_for_app_token( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &f.connector, + ) + .home_launch_context(); + let expired = gateway_home_token::issue_expired_home_launch_token_with_context( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &context, + ) + .unwrap(); + for (path, body) in [ + (STORAGE, None), + (STORAGE, Some(json!({"key":"positive","value":true}))), + ( + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ), + ] { + for token in [&f.home, &f.inbox, &expired] { + assert_ne!( + capsule_route(&f, token, path, body.clone()).await, + StatusCode::OK, + "{path}: invalid caller" + ); + } + assert_eq!( + capsule_route(&f, &f.connector, path, body).await, + StatusCode::OK, + "{path}: capsule owns its resource" + ); + } + crate::auth::revoke_session_grant(f.data.path(), &context.session_id, now_ts()).unwrap(); + for (path, body) in [ + (STORAGE, None), + (STORAGE, Some(json!({"key":"replay","value":true}))), + ( + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ), + ] { + assert_ne!( + capsule_route(&f, &f.connector, path, body).await, + StatusCode::OK, + "{path}: replay after session revocation" + ); + } + assert_eq!(f.calls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn walletconnect_opaque_relay_redeems_once_and_rechecks_launch() { + let f = Fixture::new().await; + f.allow().await; + let response = f + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, &f.addr) + .header("origin", "null") + .header("x-elastos-home-token", &f.connector) + .uri("/api/apps/wallet-walletconnect/relay-admission") + .method("POST") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 8192) + .await + .unwrap(); + let ticket: Value = serde_json::from_slice(&bytes).unwrap(); + let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", "null".parse().unwrap()); + let (mut socket, _) = connect_async(request.clone()).await.unwrap(); + let hello = json!({"token":ticket["token"], "relay":RELAY}).to_string(); + socket.send(Message::Text(hello.clone())).await.unwrap(); + assert_eq!( + socket.next().await.unwrap().unwrap(), + Message::Text("{\"ready\":true}".into()) + ); + let (mut replay, _) = connect_async(request).await.unwrap(); + replay.send(Message::Text(hello)).await.unwrap(); + assert!(matches!( + replay.next().await, + Some(Ok(Message::Close(_))) | None + )); + let context = runtime_wallet_authority_for_app_token( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &f.connector, + ) + .home_launch_context(); + crate::auth::revoke_session_grant(f.data.path(), &context.session_id, now_ts()).unwrap(); + // The heartbeat must close an idle socket whose launch lost its live session. + assert!(matches!( + tokio::time::timeout(Duration::from_secs(20), socket.next()) + .await + .unwrap(), + Some(Ok(Message::Close(_))) | None + )); + assert_eq!(f.calls.load(Ordering::SeqCst), 1); +} From 19cbd4a2a0d47e232b3f1da4f37abef5c494f93f Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:24:09 -0500 Subject: [PATCH 042/139] fix(walletconnect): bind capsule storage relay and signing to its live launch --- .../elastos-server/src/api/auth_gateway.rs | 9 +- .../src/api/gateway_frontdoor.rs | 8 +- .../src/api/gateway_home_wallet_connector.rs | 7 +- .../api/gateway_tests/wallet/connectors.rs | 111 +++++++++++----- .../api/gateway_tests/wallet/walletconnect.rs | 96 ++++++++------ .../src/api/gateway_wallet_connectors.rs | 124 +++++++++++++++++- .../src/api/gateway_walletconnect.rs | 99 +++++++++----- 7 files changed, 334 insertions(+), 120 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index a43d8a6a8..6cde0099f 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -3614,8 +3614,13 @@ fn require_wallet_link_context( state: &GatewayState, headers: &HeaderMap, ) -> anyhow::Result { - let _ = (state, headers); - Err(WalletConnectorBridgeRequired.into()) + let authority = super::gateway::require_runtime_wallet_authority( + &state.data_dir, + headers, + &[WALLET_WALLETCONNECT_CAPSULE_ID], + ) + .map_err(|_| anyhow::Error::new(WalletConnectorBridgeRequired))?; + verified_wallet_link_context(state, WALLET_WALLETCONNECT_CAPSULE_ID, authority) } pub(in crate::api) fn verified_wallet_link_context( diff --git a/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs b/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs index 056e2da78..ed90239f1 100644 --- a/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs +++ b/elastos/crates/elastos-server/src/api/gateway_frontdoor.rs @@ -253,13 +253,11 @@ pub(super) async fn gateway_admission( let sign_in = sign_in_route(path, method) && same_gateway_origin(headers); let ticket = read && gateway_home_terminal::admitted_terminal_ticket(path, request.uri().query()).await; - // The browser WebSocket API cannot send a launch-token header. Trusted Home - // may upgrade this one transport; its first frame must redeem the short-lived - // admission issued through the separately authenticated Home route. + // An opaque connector cannot send a launch-token header on a WebSocket. + // Its first bounded frame redeems capsule-scoped, single-use admission. let walletconnect_transport = method == Method::GET && path == "/api/apps/wallet-walletconnect/relay" - && origin.is_some_and(|origin| origin != "null") - && same_gateway_origin(headers); + && origin == Some("null"); let runtime_session = runtime_operator_route(path, method) && headers.contains_key("authorization") && !headers.contains_key("origin") diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index a66e03d2f..fd7728949 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -5,11 +5,8 @@ use serde_json::json; const HOME_WALLET_CONNECTOR_REQUEST_SCHEMA: &str = "elastos.home.wallet-connector.effect.request/v1"; const HOME_WALLET_CONNECTOR_RESULT_SCHEMA: &str = "elastos.home.wallet-connector.effect.result/v1"; -const HOSTED_WALLET_CONNECTOR_IDS: &[&str] = &[ - WALLET_METAMASK_CAPSULE_ID, - WALLET_UNISAT_CAPSULE_ID, - WALLET_WALLETCONNECT_CAPSULE_ID, -]; +const HOSTED_WALLET_CONNECTOR_IDS: &[&str] = + &[WALLET_METAMASK_CAPSULE_ID, WALLET_UNISAT_CAPSULE_ID]; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 3c97af135..26411d5bf 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1,7 +1,7 @@ use super::super::*; #[tokio::test] -async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { +async fn test_walletconnect_capsule_handoff_keeps_runtime_binding() { struct ReplyOverride { inner: MockWalletProvider, field: Option<&'static str>, @@ -33,10 +33,10 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { Ok(reply) } } - async fn call(app: &Router, home: &str, suffix: &str, input: Value) -> (StatusCode, Value) { - let response = app.clone().oneshot(test_browser_request("localhost:61180", "http://localhost:61180") - .method("POST").uri(format!("/api/apps/home/wallet-connector/approvals/wallet-approval%3Awc-reviewed/{suffix}")) - .header("x-elastos-home-token", home).header(CONTENT_TYPE, "application/json") + async fn call(app: &Router, token: &str, suffix: &str, input: Value) -> (StatusCode, Value) { + let response = app.clone().oneshot(test_browser_request("localhost:61180", "null") + .method("POST").uri(format!("/api/apps/wallet-walletconnect/wallet/approvals/wallet-approval%3Awc-reviewed/{suffix}")) + .header("x-elastos-home-token", token).header(CONTENT_TYPE, "application/json") .body(Body::from(input.to_string())).unwrap()).await.unwrap(); let status = response.status(); let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) @@ -53,6 +53,7 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { "other-principal", "other-connector", "expired", + "already-approved", "response-principal_id", "response-payload_hash", ] { @@ -68,7 +69,7 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { let payload_hash = format!("0x{}", "ab".repeat(32)); let account = format!("wallet:eip155:20:0x{}", "12".repeat(20)); let approval = json!({ - "request_id":"wallet-approval:wc-reviewed", "status":"pending", "intent":"publish_envelope", + "request_id":"wallet-approval:wc-reviewed", "status":if case == "already-approved" { "approved" } else { "pending" }, "intent":"publish_envelope", "requested_by_actor":"documents", "resource":"elastos://content/publish", "reason":"Controlled proof", "account_id":account, "address":format!("0x{}", "12".repeat(20)), "proof_type":"siwe", "chain_namespace":"eip155:20", "connector_id":if case == "other-connector" { WALLET_METAMASK_CAPSULE_ID } else { WALLET_WALLETCONNECT_CAPSULE_ID }, @@ -86,47 +87,27 @@ async fn test_walletconnect_home_review_and_handoff_keep_runtime_binding() { let app = gateway_router( wallet_test_state_with_shared_provider(dir.path(), Arc::new(provider)).await, ); - let input = json!({"schema":"elastos.home.wallet-connector.effect.request/v1", "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, "connector_token":connector}); - let (status, review) = call(&app, &owner.home_token, "review", input.clone()).await; - if case.starts_with("response-") { - assert_eq!( - status, - StatusCode::OK, - "stored request remains bound to its owner" - ); - let (status, error) = call(&app, &owner.home_token, "handoff", input).await; - assert_ne!(status, StatusCode::OK); - assert_eq!(error["text"], "WalletConnect approval binding mismatch"); - continue; - } + let input = json!({}); if case != "valid" { - assert_ne!(status, StatusCode::OK, "{case}"); assert_ne!( - call(&app, &owner.home_token, "handoff", input).await.0, + call(&app, &connector, "approve", input).await.0, StatusCode::OK, "{case}" ); continue; } - assert_eq!(status, StatusCode::OK, "{review}"); - assert_eq!(review["account_id"], account); for field in ["account_id", "requested_by_actor", "payload_hash"] { let mut injected = input.clone(); injected[field] = json!("capsule-selected"); assert_ne!( - call(&app, &owner.home_token, "handoff", injected).await.0, + call(&app, &connector, "approve", injected).await.0, StatusCode::OK ); } - let (status, result) = call(&app, &owner.home_token, "handoff", input).await; + let (status, result) = call(&app, &connector, "approve", input).await; assert_eq!(status, StatusCode::OK, "{result}"); - assert_eq!( - result["binding"], - json!({ - "principal_id":owner.principal_id, "requested_by_actor":"documents", "account_id":account, - "chain_namespace":"eip155:20", "payload_hash":payload_hash, "expires_at":expiry, - }) - ); + assert_eq!(result["binding"]["principal_id"], owner.principal_id); + assert_eq!(result["binding"]["payload_hash"], payload_hash); assert_eq!(result["handoff"]["payload_hash"], payload_hash); } } @@ -1322,3 +1303,69 @@ async fn test_metamask_connector_completes_external_wallet_handoff() { .unwrap_or_default() .starts_with("did:key:")); } + +#[tokio::test] +async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding() { + for case in [ + "valid", + "hash-text", + "hash-short", + "hash-nonhex", + "hash-uppercase-prefix", + "payload", + "signer", + "pending", + "expired", + "principal", + "connector", + ] { + let dir = tempfile::tempdir().unwrap(); + let owner = passkey_authority(dir.path()); + seed_walletconnect_connector_config(dir.path()); + let connector = projection_launch_token_for_authority_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &owner, + ); + let address = format!("0x{}", "12".repeat(20)); + let payload = format!("0x{}", "ab".repeat(32)); + let provider = Arc::new(RecordingWalletProvider::new(MockWalletProvider { + approvals: TokioMutex::new(vec![json!({ + "request_id":"wallet-approval:wc-complete", "status":if case == "pending" { "pending" } else { "approved" }, + "intent":"transaction_intent", "requested_by_actor":"documents", "resource":"elastos://transaction", "reason":"Fixture", + "account_id":"fixture-account", "address":address, "proof_type":"siwe", "chain_namespace":"eip155:20", + "connector_id":if case == "connector" { WALLET_METAMASK_CAPSULE_ID } else { WALLET_WALLETCONNECT_CAPSULE_ID }, + "principal_id":if case == "principal" { "other-principal" } else { &owner.principal_id }, + "payload_hash":payload, "created_at":now_ts(), "expires_at":if case == "expired" { 0 } else { now_ts() + 600 }, + })]), + ..Default::default() + })); + let app = gateway_router( + wallet_test_state_with_shared_provider(dir.path(), provider.clone()).await, + ); + let hash = match case { + "hash-text" => "Check a fake recovery site".into(), + "hash-short" => "0x12".into(), + "hash-nonhex" => format!("0x{}", "zz".repeat(32)), + "hash-uppercase-prefix" => format!("0X{}", "ab".repeat(32)), + _ => format!("0x{}", "34".repeat(32)), + }; + let body = json!({"payload_hash":if case == "payload" { format!("0x{}", "cd".repeat(32)) } else { payload }, + "signer":if case == "signer" { "another-account" } else { &address }, "transaction_hash":hash}); + let response = app.oneshot(test_browser_request("localhost:61180", "null") + .method("POST").uri("/api/apps/wallet-walletconnect/wallet/approvals/wallet-approval%3Awc-complete/complete") + .header("x-elastos-home-token", &connector).header(CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())).unwrap()).await.unwrap(); + let operations = provider.recorded_v2_operation_kinds().await; + if case == "valid" { + assert_eq!(response.status(), StatusCode::OK); + assert!(operations.contains(&WalletOperationKind::CompleteConnectorHandoff)); + } else { + assert_ne!(response.status(), StatusCode::OK, "{case}"); + assert!( + !operations.contains(&WalletOperationKind::CompleteConnectorHandoff), + "{case}: refused before provider effect" + ); + } + } +} diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 46d6bc2ba..6a2d3fb09 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -211,28 +211,22 @@ impl Fixture { } async fn route_as( &self, - home: &str, + _home: &str, token: &str, path: &str, body: Option, ) -> (StatusCode, Value) { - let hosted = - path == STORAGE || path.ends_with("relay-admission") || path.ends_with("host-config"); - let origin = if hosted { - format!("http://{}", self.addr) - } else { - "null".into() - }; + let origin = "null"; let response = self .app .clone() .oneshot( Request::builder() .header(HOST, self.addr.as_str()) - .header("origin", origin.as_str()) + .header("origin", origin) .uri(path) .method(if body.is_some() { "POST" } else { "GET" }) - .header("x-elastos-home-token", if hosted { home } else { token }) + .header("x-elastos-home-token", token) .header("x-elastos-walletconnect-connector", token) .header(CONTENT_TYPE, "application/json") .body(body.map_or_else(Body::empty, |v| Body::from(v.to_string()))) @@ -304,7 +298,7 @@ impl Fixture { .unwrap(); request .headers_mut() - .insert("origin", format!("http://{}", self.addr).parse().unwrap()); + .insert("origin", "null".parse().unwrap()); let (mut socket, _) = connect_async(request).await.unwrap(); socket .send(Message::Text( @@ -413,9 +407,13 @@ async fn walletconnect_admission_quota_preserves_other_principals() { } #[tokio::test] -async fn walletconnect_websocket_upgrade_requires_same_home_origin_and_first_frame_admission() { +async fn walletconnect_websocket_upgrade_requires_opaque_origin_and_first_frame_admission() { let f = Fixture::new().await; - for origin in [None, Some("null"), Some("https://other.example")] { + for origin in [ + None, + Some("http://localhost"), + Some("https://other.example"), + ] { let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) .into_client_request() .unwrap(); @@ -429,7 +427,7 @@ async fn walletconnect_websocket_upgrade_requires_same_home_origin_and_first_fra matches!(result, Err(tokio_tungstenite::tungstenite::Error::Http(ref response)) if response.status() == StatusCode::FORBIDDEN) ); } - // This matches the browser API: same-Home Origin, no custom auth header, + // This matches the opaque browser API: null Origin, no custom auth header, // and a refused first-frame ticket. Upgrading grants no Exit access. let mut socket = f.connect_ticket("refused", RELAY).await; assert!(matches!( @@ -679,7 +677,7 @@ async fn walletconnect_reconnects_after_runtime_service_restart_with_saved_princ } #[tokio::test] -async fn walletconnect_refuses_malformed_writes_and_cross_principal_host_authority() { +async fn walletconnect_refuses_malformed_writes_and_home_authority() { let f = Fixture::new().await; for body in [ json!({"key":"session","value":"x","unknown":true}), @@ -690,40 +688,21 @@ async fn walletconnect_refuses_malformed_writes_and_cross_principal_host_authori } let (_, stored) = f.route(&f.connector, STORAGE, None).await; assert_eq!(stored, json!({})); - let other = passkey_authority_with_name_role_credential( - f.data.path(), - Some("different-host"), - crate::auth::RuntimePrincipalRole::Admin, - "different-host-credential", - ); for path in [ STORAGE, "/api/apps/wallet-walletconnect/relay-admission", "/api/apps/wallet-walletconnect/host-config", ] { - let (status, _) = f - .route_as(&other.home_token, &f.connector, path, Some(json!({}))) - .await; - assert_ne!(status, StatusCode::OK); + let (status, _) = f.route(&f.home, path, None).await; + assert_ne!( + status, + StatusCode::OK, + "Home owns no WalletConnect authority" + ); } - let response = f - .app - .clone() - .oneshot( - Request::builder() - .header(HOST, f.addr.as_str()) - .header("origin", "null") - .uri(STORAGE) - .header("x-elastos-home-token", &f.connector) - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_ne!( - response.status(), - StatusCode::OK, - "capsule authority cannot read SDK keys" + assert_eq!( + capsule_route(&f, &f.connector, STORAGE, None).await, + StatusCode::OK ); assert_eq!(f.calls.load(Ordering::SeqCst), 0); } @@ -947,3 +926,34 @@ async fn walletconnect_opaque_relay_redeems_once_and_rechecks_launch() { )); assert_eq!(f.calls.load(Ordering::SeqCst), 1); } + +#[tokio::test] +async fn walletconnect_caps_unadmitted_opaque_sockets_and_recovers() { + let f = Fixture::new().await; + let mut sockets = Vec::new(); + for _ in 0..16 { + let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", "null".parse().unwrap()); + sockets.push(connect_async(request).await.unwrap().0); + } + let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", "null".parse().unwrap()); + assert!( + matches!(connect_async(request.clone()).await, Err(tokio_tungstenite::tungstenite::Error::Http(ref r)) if r.status() == StatusCode::TOO_MANY_REQUESTS) + ); + for socket in &mut sockets { + socket.close(None).await.unwrap(); + } + tokio::time::sleep(Duration::from_millis(100)).await; + let (mut recovered, _) = connect_async(request).await.unwrap(); + recovered.close(None).await.unwrap(); + assert_eq!(f.calls.load(Ordering::SeqCst), 0); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index d85b2de3b..c89931c1a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -101,6 +101,14 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_approve( Err(err) => return system_error_response(err), }; let context = authority.home_launch_context(); + let binding = if wallet_connector == WALLET_WALLETCONNECT_CAPSULE_ID { + match walletconnect_request_binding(&state, &authority, &request_id, "pending").await { + Ok(binding) => Some(binding), + Err(err) => return system_error_response(err), + } + } else { + None + }; let connector_label = wallet_connector_label(wallet_connector.as_str()); let reason = input .reason @@ -120,7 +128,19 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_approve( let mut summary = system_wallet_approvals_summary(&state, &authority, false).await; summary.note = Some(format!("Approved. Continue in {connector_label}.")); summary.handoff = outcome.handoff; - Json(summary).into_response() + let mut response = serde_json::to_value(summary).expect("wallet summary serialization"); + if let Some(binding) = binding { + if let Err(err) = validate_walletconnect_handoff( + &request_id, + &binding, + &outcome.approval_request, + &response["handoff"], + ) { + return system_error_response(err); + } + response["binding"] = binding; + } + Json(response).into_response() } Err(err) => system_error_response(err), } @@ -144,6 +164,34 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_complete( Err(err) => return system_error_response(err), }; let context = authority.home_launch_context(); + if wallet_connector == WALLET_WALLETCONNECT_CAPSULE_ID { + let binding = match walletconnect_request_binding( + &state, + &authority, + &request_id, + "approved", + ) + .await + { + Ok(binding) => binding, + Err(err) => return system_error_response(err), + }; + if binding["payload_hash"].as_str() != Some(input.payload_hash.as_str()) + || !binding["address"] + .as_str() + .is_some_and(|address| address.eq_ignore_ascii_case(&input.signer)) + || input + .transaction_hash + .as_deref() + .is_some_and(|hash| !walletconnect_hash(hash)) + || (binding["intent"] == "transaction_intent" + && (input.transaction_hash.is_none() || input.signature.is_some())) + { + return system_error_response(anyhow::anyhow!( + "WalletConnect completion binding or transaction hash is invalid" + )); + } + } let connector_label = wallet_connector_label(wallet_connector.as_str()); match complete_external_wallet_approval( &state, @@ -165,6 +213,9 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_complete( } fn require_capsule_owned_connector_effects(connector_id: &str) -> anyhow::Result<()> { + if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + return Ok(()); + } if is_wallet_connector_capsule_id(connector_id) { anyhow::bail!( "wallet connector injected-wallet effects require the trusted Home host bridge" @@ -276,3 +327,74 @@ pub(in crate::api::gateway) fn validate_walletconnect_connector_config( } Ok(()) } + +fn walletconnect_hash(value: &str) -> bool { + value.len() == 66 + && value.starts_with("0x") + && value[2..].bytes().all(|b| b.is_ascii_hexdigit()) +} + +async fn walletconnect_request_binding( + state: &GatewayState, + authority: &RuntimeWalletAuthority, + request_id: &str, + status: &str, +) -> anyhow::Result { + let data = runtime_wallet_data( + state, + authority, + elastos_wallet_contract::WalletProviderOperationV2::ListApprovals { + include_resolved: true, + }, + ) + .await?; + let request = data["approval_requests"] + .as_array() + .and_then(|requests| requests.iter().find(|r| r["request_id"] == request_id)) + .ok_or_else(|| anyhow::anyhow!("WalletConnect approval request not found"))?; + anyhow::ensure!( + request["principal_id"].as_str() == Some(authority.verified_context().principal_id()) + && request["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID + && request["status"] == status + && request["expires_at"] + .as_u64() + .is_some_and(|expiry| expiry > now_ts()) + && request["payload_hash"] + .as_str() + .is_some_and(walletconnect_hash), + "WalletConnect request binding changed or expired" + ); + Ok(request.clone()) +} + +fn validate_walletconnect_handoff( + request_id: &str, + binding: &serde_json::Value, + approved: &Option, + handoff: &serde_json::Value, +) -> anyhow::Result<()> { + let approved = approved + .as_ref() + .ok_or_else(|| anyhow::anyhow!("WalletConnect approval binding is missing"))?; + for field in [ + "principal_id", + "requested_by_actor", + "account_id", + "chain_namespace", + "payload_hash", + "expires_at", + ] { + anyhow::ensure!( + !binding[field].is_null() && approved[field] == binding[field], + "WalletConnect approval binding mismatch" + ); + } + anyhow::ensure!( + handoff["request_id"] == request_id + && handoff["payload_hash"] == binding["payload_hash"] + && handoff["intent"] == binding["intent"] + && handoff["signer"] == binding["address"], + "WalletConnect handoff binding mismatch" + ); + Ok(()) +} diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index c2c305c3d..a5db21a6b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -15,14 +15,26 @@ const MAX_BYTES: usize = 1024 * 1024; const MAX_SOCKETS: usize = 2; const RESOURCE: &str = "elastos://walletconnect/internet"; -#[derive(Default)] pub(crate) struct WalletConnectService { + unadmitted: Arc, inner: Mutex, #[cfg(test)] pub(in crate::api::gateway) pongs: std::sync::atomic::AtomicUsize, #[cfg(test)] pub(in crate::api::gateway) tls: std::sync::Mutex>>, } +impl Default for WalletConnectService { + fn default() -> Self { + Self { + unadmitted: Arc::new(tokio::sync::Semaphore::new(16)), + inner: Mutex::default(), + #[cfg(test)] + pongs: std::sync::atomic::AtomicUsize::new(0), + #[cfg(test)] + tls: std::sync::Mutex::new(None), + } + } +} #[derive(Default)] struct Inner { sockets: BTreeMap, @@ -371,22 +383,23 @@ async fn verify_sdk(state: &GatewayState) -> anyhow::Result<()> { Ok(()) } -fn hosted(state: &GatewayState, headers: &HeaderMap) -> anyhow::Result { - let connector = headers - .get("x-elastos-walletconnect-connector") - .and_then(|h| h.to_str().ok()) - .ok_or_else(|| anyhow::anyhow!("Home wallet connector authority is required"))?; - Ok( - gateway_home_wallet_connector::revalidate_home_wallet_connector_authority( - state, - headers, - "elastos.home.wallet-connector.effect.request/v1", - WALLET_WALLETCONNECT_CAPSULE_ID, - connector, - WALLET_WALLETCONNECT_CAPSULE_ID, - )? - .wallet, - ) +fn connector_authority( + state: &GatewayState, + headers: &HeaderMap, +) -> anyhow::Result { + let launch = require_home_launch_token_binding( + &state.data_dir, + headers, + &[WALLET_WALLETCONNECT_CAPSULE_ID], + )?; + anyhow::ensure!( + launch.launch_context.selected_resource == WALLET_WALLETCONNECT_CAPSULE_ID + && launch.context.proof_binding_id.is_some(), + "WalletConnect requires its own proof-bound capsule launch" + ); + // The signed launch carries principal, live session and exact launch instance. + // Retaining these headers binds relay tickets and recurring checks to that launch. + runtime_wallet_authority(&launch) } #[cfg(test)] pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayState) { @@ -403,7 +416,7 @@ pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayS } pub(super) async fn admission(State(state): State, headers: HeaderMap) -> Response { let result = async { - let authority = hosted(&state, &headers)?; + let authority = connector_authority(&state, &headers)?; verify_sdk(&state).await?; let principal = authority.home_launch_context().principal_id; let mut inner = state.walletconnect.inner.lock().await; @@ -436,7 +449,7 @@ pub(super) async fn host_config( headers: HeaderMap, ) -> Response { let result = async { - let authority = hosted(&state, &headers)?; + let authority = connector_authority(&state, &headers)?; if method == axum::http::Method::POST { verify_sdk(&state).await?; } let inner = state.walletconnect.inner.lock().await; if method == axum::http::Method::POST { @@ -481,7 +494,7 @@ pub(super) async fn storage( input: Result, axum::extract::rejection::JsonRejection>, ) -> Response { let result = async { - let authority = hosted(&state, &headers)?; + let authority = connector_authority(&state, &headers)?; let _guard = state.walletconnect.inner.lock().await; let path = storage_path( &state.data_dir, @@ -560,17 +573,39 @@ struct RelayHello { token: String, relay: String, } -pub(super) async fn relay(State(state): State, ws: WebSocketUpgrade) -> Response { +pub(super) async fn relay( + State(state): State, + headers: HeaderMap, + ws: WebSocketUpgrade, +) -> Response { + if headers.get("origin").and_then(|v| v.to_str().ok()) != Some("null") { + return ( + StatusCode::FORBIDDEN, + "WalletConnect requires its opaque capsule origin", + ) + .into_response(); + } + let Ok(permit) = state.walletconnect.unadmitted.clone().try_acquire_owned() else { + return ( + StatusCode::TOO_MANY_REQUESTS, + "WalletConnect admission connections are busy", + ) + .into_response(); + }; // Authority travels in the first bounded frame, never in a URL or log. ws.max_message_size(64 * 1024) .max_frame_size(64 * 1024) .on_upgrade(move |mut socket| async move { - let _ = relay_connection(&state, &mut socket).await; + let _ = relay_connection(&state, &mut socket, permit).await; // Error messages can contain upstream auth URLs. Keep them private. let _ = socket.close().await; }) } -async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyhow::Result<()> { +async fn relay_connection( + state: &GatewayState, + socket: &mut WebSocket, + permit: tokio::sync::OwnedSemaphorePermit, +) -> anyhow::Result<()> { let hello = tokio::time::timeout(Duration::from_secs(5), socket.recv()) .await? .ok_or_else(|| anyhow::anyhow!("WalletConnect transport closed"))??; @@ -585,11 +620,12 @@ async fn relay_connection(state: &GatewayState, socket: &mut WebSocket) -> anyho let (expiry, headers, _) = inner .admissions .remove(&hello.token) - .ok_or_else(|| anyhow::anyhow!("Home transport admission required"))?; + .ok_or_else(|| anyhow::anyhow!("Live WalletConnect capsule admission required"))?; anyhow::ensure!(expiry > now_ts(), "WalletConnect admission expired"); headers }; - let authority = hosted(state, &headers)?; + let authority = connector_authority(state, &headers)?; + drop(permit); let config = load_walletconnect_connector_config(&state.data_dir)?; let url = relay_url(&hello.relay, &config.project_id)?; let principal = authority.home_launch_context().principal_id.clone(); @@ -649,7 +685,7 @@ async fn transport( client::IntoClientRequest, protocol::WebSocketConfig, Message as Upstream, }; let host = url.host_str().unwrap(); - let authority = hosted(state, headers)?; + let authority = connector_authority(state, headers)?; let principal = authority.home_launch_context().principal_id; let registry = state .provider_registry @@ -700,10 +736,9 @@ async fn transport( .unwrap_or(tls_config); let connector = Some(tokio_tungstenite::Connector::Rustls(tls_config)); let mut request = url.as_str().into_client_request()?; - request.headers_mut().insert( - "origin", - gateway_home_token::home_browser_origin(headers)?.parse()?, - ); + request + .headers_mut() + .insert("origin", HeaderValue::from_static("null")); let (upstream, _) = tokio_tungstenite::client_async_tls_with_config( request, stream, @@ -723,7 +758,7 @@ async fn transport( loop { tokio::select! { _ = heartbeat.tick() => { - hosted(state, headers)?; + connector_authority(state, headers)?; check_owner(state, false).await?; check_liveness(pong.elapsed(), activity.elapsed())?; tokio::time::timeout(Duration::from_secs(5), upstream.send(Upstream::Ping(Vec::new()))).await??; @@ -744,7 +779,7 @@ async fn transport( }, frame = socket.recv() => match frame.transpose()? { Some(Message::Text(text)) => { - hosted(state, headers)?; + connector_authority(state, headers)?; check_owner(state, false).await?; activity = Instant::now(); tokio::time::timeout(Duration::from_secs(5), upstream.send(Upstream::Text(text))).await??; From 7eb93acffd56514c69ace7eae96a5da31922676c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:27:26 -0500 Subject: [PATCH 043/139] fix(walletconnect): import the connector actor in the auth gateway --- elastos/crates/elastos-server/src/api/auth_gateway.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 6cde0099f..c7e58c453 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -41,6 +41,7 @@ use super::gateway::{ is_wallet_connector_capsule_id, issue_home_launch_token_for_auth_grant, require_home_launch_token_binding, require_runtime_wallet_authority, runtime_wallet_authority, GatewayState, RuntimeWalletAdapter, RuntimeWalletAuthority, HOME_CAPSULE_ID, HOME_ROUTE, + WALLET_WALLETCONNECT_CAPSULE_ID, }; use crate::auth::AUTH_SESSION_TTL_SECS; From f49b9da42dc5d8e2ac95ec4a8e8bb5bd6e48dd80 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:27:26 -0500 Subject: [PATCH 044/139] test(walletconnect): exercise paired recovery through real capsule routes --- .../wallet/walletconnect_real_relay.rs | 38 +++++++++++-- .../walletconnect-real-browser-fixture.mjs | 17 +++++- .../walletconnect-real-preflight-smoke.mjs | 56 ++++++++++++++++++- 3 files changed, 102 insertions(+), 9 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index bebdf05e2..dbba24131 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -148,7 +148,7 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { async fn walletconnect_real_project_opaque_preflight() { use tokio::io::AsyncWriteExt; let project = operator_project(); - let f = real_fixture(&project).await; + let mut f = real_fixture(&project).await; let repo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); for name in ["home", "wallet-walletconnect"] { let destination = f.data.path().join("capsules").join(name); @@ -190,8 +190,10 @@ async fn walletconnect_real_project_opaque_preflight() { ) .unwrap(); f.allow().await; + let restart_path = f.data.path().join("restart.sock"); + let restart = UnixListener::bind(&restart_path).unwrap(); let input = serde_json::to_vec(&json!({ - "origin": format!("http://{}", f.addr), "connector": f.connector, "projectId": project, + "origin": format!("http://{}", f.addr), "connector": f.connector, "projectId": project, "restart":restart_path, })) .unwrap(); let mut child = tokio::process::Command::new("node") @@ -203,10 +205,34 @@ async fn walletconnect_real_project_opaque_preflight() { .spawn() .unwrap(); child.stdin.take().unwrap().write_all(&input).await.unwrap(); - let output = tokio::time::timeout(Duration::from_secs(150), child.wait_with_output()) - .await - .expect("real relay browser gate timeout") - .unwrap(); + let mut waiting = tokio::spawn(async move { child.wait_with_output().await }); + let result = tokio::time::timeout(Duration::from_secs(270), async { + loop { + tokio::select! { + output = &mut waiting => break output.unwrap().unwrap(), + connection = restart.accept() => { + let (mut connection, _) = connection.unwrap(); + let mut command = [0u8; 7]; + tokio::time::timeout(Duration::from_secs(3), connection.read_exact(&mut command)).await.unwrap().unwrap(); + assert_eq!(&command, b"restart"); + f.gateway.abort(); let _ = (&mut f.gateway).await; + let registry = f.state.provider_registry.clone(); + f.state = test_state(f.data.path()); + f.state.provider_registry = registry; + f.state.browser_internet = persistent_internet(f.data.path()).await; + let listener = TcpListener::bind(&f.addr).await.unwrap(); + f.app = gateway_router_with_api_url(f.state.clone(), format!("http://{}", f.addr)); + let app = f.app.clone(); + f.gateway = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); + connection.write_all(b"ready").await.unwrap(); + } + } + } + }).await; + if result.is_err() { + waiting.abort(); + } + let output = result.expect("real relay paired recovery timeout"); println!("{}", String::from_utf8_lossy(&output.stdout)); // The Node driver emits only bounded, value-free evidence. SDK diagnostics // can contain relay credentials, so stderr remains private to this process. diff --git a/scripts/lib/walletconnect-real-browser-fixture.mjs b/scripts/lib/walletconnect-real-browser-fixture.mjs index ec7f55547..db1ce73ec 100644 --- a/scripts/lib/walletconnect-real-browser-fixture.mjs +++ b/scripts/lib/walletconnect-real-browser-fixture.mjs @@ -23,7 +23,22 @@ const api = async (resource, input = {}) => { window.refusal ??= { resource, status:response.status }; throw new Error('Runtime refused the connector resource'); } - return response.json(); + const values = await response.json(); + if (resource === 'storage') { + // Private test-wallet handoff: the URI is reconstructed from the exact + // Runtime-persisted pairing and keychain, and stays in process memory. + const pairings = Object.entries(values).find(([key]) => key.endsWith('//pairing'))?.[1]; + const keys = Object.entries(values).find(([key]) => key.endsWith('//keychain'))?.[1]; + const pairing = Array.isArray(pairings) ? pairings.find(value => !value.active) : undefined; + const keychain = typeof keys === 'string' ? JSON.parse(keys) : keys; + const symKey = pairing && (Array.isArray(keychain) ? new Map(keychain).get(pairing.topic) : keychain?.[pairing.topic]); + if (pairing && typeof symKey === 'string') { + const params = new URLSearchParams({symKey, 'relay-protocol':pairing.relay.protocol, + expiryTimestamp:String(pairing.expiry), methods:'[wc_sessionPropose]'}); + window.pairingUri = `wc:${pairing.topic}@2?${params}`; + } + } + return values; }; try { window.phase = 'import'; diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index c2ad858de..1997e9d92 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -2,6 +2,8 @@ // enter through stdin; browser evidence contains resource names and status. import assert from 'node:assert/strict'; import { mkdir, writeFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { connect } from 'node:net'; import { importProductSmokePlaywright } from './product-smoke-browser.mjs'; let input = ''; for await (const chunk of process.stdin) { input += chunk; assert.ok(input.length < 16384); } @@ -10,15 +12,34 @@ const result = { project:'project file set', runs:[] }; const evidence = process.env.WALLETCONNECT_SCREENSHOTS; const emit = console.log.bind(console); console.log = console.warn = console.error = () => {}; -const deadline = setTimeout(() => { result.timeout = true; emit(JSON.stringify(result)); process.exit(1); }, 120000); +const deadline = setTimeout(() => { result.timeout = true; emit(JSON.stringify(result)); process.exit(1); }, 240000); +const bounded = (promise, ms = 20000) => Promise.race([promise, new Promise((_, reject) => { const timer = setTimeout(() => reject(new Error('step timeout')), ms); timer.unref(); })]); +const restart = () => bounded(new Promise((resolve, reject) => { const socket = connect(options.restart); socket.setTimeout(10000, () => socket.destroy(new Error('restart timeout'))); socket.on('error', reject); socket.on('connect', () => socket.end('restart')); socket.on('data', data => data.toString() === 'ready' ? resolve() : reject(new Error('restart refused'))); })); const expectedCsp = `sandbox allow-scripts allow-forms allow-downloads; default-src ${options.origin}; script-src 'self' 'wasm-unsafe-eval' ${options.origin}; style-src ${options.origin} 'unsafe-inline'; img-src ${options.origin} blob: data:; connect-src ${options.origin} ${options.origin.replace(/^http/, 'ws')}; frame-src ${options.origin}; object-src 'none'; base-uri 'none'; form-action ${options.origin}`; try { const playwright = await importProductSmokePlaywright(); + const { SignClient } = createRequire(new URL('./walletconnect/package.json', import.meta.url))('@walletconnect/sign-client'); for (const engine of ['chromium', 'webkit']) { const run = { engine, paired:false, network:[] }; result.runs.push(run); - let browser, frame; + let browser, frame, wallet; try { + run.phase = 'test-wallet'; + wallet = await bounded(SignClient.init({projectId:options.projectId, logger:'silent', + customStoragePrefix:`wc-recovery-${engine}-${Date.now()}`, storageOptions:{database:':memory:'}, + metadata:{name:'Disposable scripted wallet', description:'Pairing recovery only', url:'https://localhost', icons:[]}})); + let proposals = 0; + let approve; + const approved = new Promise((resolve, reject) => { approve = {resolve, reject}; }); + wallet.on('session_proposal', async proposal => { + proposals++; + try { + const session = await wallet.approve({id:proposal.id, namespaces:{eip155:{ + accounts:[`eip155:1:0x${'12'.repeat(20)}`], methods:['personal_sign','eth_sendTransaction'], + events:['accountsChanged','chainChanged']}}}); + approve.resolve(await session.acknowledged()); + } catch { approve.reject(new Error('scripted wallet approval failed')); } + }); run.phase = 'browser'; browser = await playwright[engine].launch({headless:true, timeout:15000}); run.version = browser.version(); @@ -56,6 +77,33 @@ try { assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => self.origin), 'null'); assert.equal(await frame.locator('dialog[open] canvas').count(), 1); + run.qr = 'PASS'; + run.phase = 'pairing'; + await frame.waitForFunction(() => typeof window.pairingUri === 'string', null, {timeout:10000}); + const uri = await frame.evaluate(() => window.pairingUri); + await bounded(wallet.core.pairing.pair({uri})); + const session = await bounded(approved, 30000); + await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:20000}); + assert.equal(await frame.evaluate(() => window.failed), undefined); + assert.equal(await frame.evaluate(() => window.provider.session.topic), session.topic); + await bounded(wallet.ping({topic:session.topic})); + run.paired = true; + run.pairing = 'PASS'; + for (const phase of ['reload', 'homeRestart']) { + run.phase = phase; + if (phase === 'homeRestart') await restart(); + await frame.evaluate(() => location.reload()); + await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:30000}); + assert.equal(await frame.evaluate(() => window.failed), undefined); + assert.equal(await frame.evaluate(() => window.provider.session.topic), session.topic); + assert.equal(await frame.locator('dialog[open] canvas').count(), 0); + await bounded(wallet.ping({topic:session.topic})); + assert.equal(proposals, 1); + run[phase] = 'PASS'; + } + const trace = await frame.evaluate(() => window.storageTrace); + assert.ok(trace.every(entry => !entry.protocol)); + run.protocolInShim = false; run.status = 'PASS'; } catch { run.status = 'FAIL'; @@ -69,6 +117,10 @@ try { ]); } catch { run.stateUnavailable = true; } } + try { + for (const session of wallet?.session.getAll() || []) await bounded(wallet.disconnect({topic:session.topic, reason:{code:6000, message:'Test complete'}}), 5000); + await wallet?.core.relayer.transportClose(); + } catch { run.walletCleanup = 'transport closed at process exit'; } await browser?.close(); } // Stop at the first Chromium blocker, as required by the round's brief. From ec2148f12a1654c7db4e170a06bc1980a10cecc3 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:29:50 -0500 Subject: [PATCH 045/139] test(walletconnect): refuse Home authority at its valid browser origin --- .../src/api/gateway_tests/wallet/walletconnect.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 6a2d3fb09..2ac5a7f69 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -794,12 +794,17 @@ async fn walletconnect_revoked_owner_cannot_send_another_relay_frame() { // Real frontdoor and app routes, carrying only the capsule launch token. async fn capsule_route(f: &Fixture, token: &str, path: &str, body: Option) -> StatusCode { + let origin = if token == f.home { + format!("http://{}", f.addr) + } else { + "null".into() + }; f.app .clone() .oneshot( Request::builder() .header(HOST, &f.addr) - .header("origin", "null") + .header("origin", origin) .header("x-elastos-home-token", token) .header(CONTENT_TYPE, "application/json") .uri(path) From 752daf0c4a711cf60b4ed80c78db8a08ea464ec1 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:30:56 -0500 Subject: [PATCH 046/139] test(walletconnect): preserve the pinned pairing URI parameters --- scripts/lib/walletconnect-real-browser-fixture.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/lib/walletconnect-real-browser-fixture.mjs b/scripts/lib/walletconnect-real-browser-fixture.mjs index db1ce73ec..4448352dd 100644 --- a/scripts/lib/walletconnect-real-browser-fixture.mjs +++ b/scripts/lib/walletconnect-real-browser-fixture.mjs @@ -34,7 +34,9 @@ const api = async (resource, input = {}) => { const symKey = pairing && (Array.isArray(keychain) ? new Map(keychain).get(pairing.topic) : keychain?.[pairing.topic]); if (pairing && typeof symKey === 'string') { const params = new URLSearchParams({symKey, 'relay-protocol':pairing.relay.protocol, - expiryTimestamp:String(pairing.expiry), methods:'[wc_sessionPropose]'}); + expiryTimestamp:String(pairing.expiry)}); + if (pairing.methods) params.set('methods', pairing.methods.join(',')); + if (pairing.relay.data) params.set('relay-data', pairing.relay.data); window.pairingUri = `wc:${pairing.topic}@2?${params}`; } } From dc4993f9bd55bffc7a435e0312f704daaa686ab2 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:32:41 -0500 Subject: [PATCH 047/139] test(walletconnect): cover all capsule authority routes and close sockets at restart --- .../api/gateway_tests/wallet/connectors.rs | 138 +++++++++++++++++- .../wallet/walletconnect_real_relay.rs | 1 + .../src/api/gateway_wallet_connectors.rs | 2 + .../src/api/gateway_walletconnect.rs | 15 ++ 4 files changed, 155 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 26411d5bf..0df2ec83a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1348,7 +1348,7 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding "hash-short" => "0x12".into(), "hash-nonhex" => format!("0x{}", "zz".repeat(32)), "hash-uppercase-prefix" => format!("0X{}", "ab".repeat(32)), - _ => format!("0x{}", "34".repeat(32)), + _ => format!("0x{}", "aB".repeat(32)), }; let body = json!({"payload_hash":if case == "payload" { format!("0x{}", "cd".repeat(32)) } else { payload }, "signer":if case == "signer" { "another-account" } else { &address }, "transaction_hash":hash}); @@ -1360,6 +1360,22 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding if case == "valid" { assert_eq!(response.status(), StatusCode::OK); assert!(operations.contains(&WalletOperationKind::CompleteConnectorHandoff)); + let requests = provider.requests.lock().await; + let forwarded = requests + .iter() + .filter_map(|request| { + let bytes = serde_json::to_vec(&request["request"]).ok()?; + let request = WalletProviderRequestV2::decode_at(&bytes, now_ts()).ok()?; + match request.operation { + WalletProviderOperationV2::CompleteConnectorHandoff { + transaction_hash, + .. + } => transaction_hash, + _ => None, + } + }) + .collect::>(); + assert_eq!(forwarded, vec![format!("0x{}", "aB".repeat(32))]); } else { assert_ne!(response.status(), StatusCode::OK, "{case}"); assert!( @@ -1369,3 +1385,123 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding } } } + +#[tokio::test] +async fn test_walletconnect_capsule_config_link_and_effect_authority_matrix() { + let dir = tempfile::tempdir().unwrap(); + let owner = passkey_authority(dir.path()); + seed_walletconnect_connector_config(dir.path()); + let token = projection_launch_token_for_authority_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &owner, + ); + let inbox = app_token_for_authority(dir.path(), INBOX_CAPSULE_ID, &owner); + let context = + runtime_wallet_authority_for_app_token(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &token) + .home_launch_context(); + let expired = gateway_home_token::issue_expired_home_launch_token_with_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &context, + ) + .unwrap(); + let signing_key = EvmSigningKey::from_bytes((&[9u8; 32]).into()).unwrap(); + let address = evm_test_address(&signing_key); + let payload = format!("0x{}", "ab".repeat(32)); + let provider = MockWalletProvider { + approvals: TokioMutex::new(vec![json!({ + "request_id":"wallet-approval:wc-authority", "status":"pending", "intent":"transaction_intent", + "requested_by_actor":"documents", "resource":"elastos://transaction", "reason":"Fixture", + "account_id":"fixture-account", "address":address, "proof_type":"siwe", "chain_namespace":"eip155:1", + "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, "principal_id":owner.principal_id, + "payload_hash":payload, "created_at":now_ts(), "expires_at":now_ts()+600, + })]), + ..Default::default() + }; + let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); + async fn call( + app: &Router, + home: &str, + token: &str, + path: &str, + body: Option, + ) -> (StatusCode, Value) { + let response = app + .clone() + .oneshot( + test_browser_request( + "localhost:61180", + if token == home { + "http://localhost:61180" + } else { + "null" + }, + ) + .method(if body.is_some() { "POST" } else { "GET" }) + .uri(path) + .header("x-elastos-home-token", token) + .header(CONTENT_TYPE, "application/json") + .body(body.map_or_else(Body::empty, |v| Body::from(v.to_string()))) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 128 * 1024) + .await + .unwrap(); + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + ) + } + let mut calls = vec![ + ("/api/apps/wallet-walletconnect/wallet/config", None), + ( + "/api/auth/evm/challenge", + Some(json!({"address":address,"chain_id":1})), + ), + ]; + let mut index = 0; + while index < calls.len() { + let (path, body) = calls[index].clone(); + for invalid in [&owner.home_token, &inbox, &expired] { + assert_ne!( + call(&app, &owner.home_token, invalid, path, body.clone()) + .await + .0, + StatusCode::OK, + "{path}: invalid caller" + ); + } + let (status, value) = call(&app, &owner.home_token, &token, path, body).await; + assert_eq!(status, StatusCode::OK, "{path}: {value}"); + if path.ends_with("challenge") { + let message = value["message"].as_str().unwrap(); + calls.push(( + "/api/auth/evm/verify", + Some(json!({"message":message,"signature":evm_sign_message(&signing_key,message)})), + )); + calls.push(("/api/apps/wallet-walletconnect/wallet/approvals/wallet-approval%3Awc-authority/approve", Some(json!({})))); + calls.push(("/api/apps/wallet-walletconnect/wallet/approvals/wallet-approval%3Awc-authority/complete", Some(json!({"payload_hash":payload,"signer":address,"transaction_hash":format!("0x{}","34".repeat(32))})))); + } + index += 1; + } + // Both a consumed ownership proof and a launch whose session was revoked fail closed. + let (path, body) = &calls[2]; + assert_ne!( + call(&app, &owner.home_token, &token, path, body.clone()) + .await + .0, + StatusCode::OK + ); + crate::auth::revoke_session_grant(dir.path(), &context.session_id, now_ts()).unwrap(); + for (path, body) in calls { + assert_ne!( + call(&app, &owner.home_token, &token, path, body).await.0, + StatusCode::OK, + "{path}: revoked launch replay" + ); + } +} diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index dbba24131..e71b3a095 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -215,6 +215,7 @@ async fn walletconnect_real_project_opaque_preflight() { let mut command = [0u8; 7]; tokio::time::timeout(Duration::from_secs(3), connection.read_exact(&mut command)).await.unwrap().unwrap(); assert_eq!(&command, b"restart"); + gateway_walletconnect::stop_for_restart_test(&f.state).await; f.gateway.abort(); let _ = (&mut f.gateway).await; let registry = f.state.provider_registry.clone(); f.state = test_state(f.data.path()); diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index c89931c1a..8e73baf03 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -186,6 +186,8 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_complete( .is_some_and(|hash| !walletconnect_hash(hash)) || (binding["intent"] == "transaction_intent" && (input.transaction_hash.is_none() || input.signature.is_some())) + || (binding["intent"] != "transaction_intent" + && (input.signature.is_none() || input.transaction_hash.is_some())) { return system_error_response(anyhow::anyhow!( "WalletConnect completion binding or transaction hash is invalid" diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index a5db21a6b..d779fbf88 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -414,6 +414,21 @@ pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayS *expiry = 0; } } +#[cfg(test)] +pub(in crate::api::gateway) async fn stop_for_restart_test(state: &GatewayState) { + let mut inner = state.walletconnect.inner.lock().await; + inner.admissions.clear(); + for socket in inner.sockets.values() { + socket.cancel.send_replace(true); + } + for socket in inner.sockets.values_mut() { + tokio::time::timeout(Duration::from_secs(3), socket.done.wait_for(|done| *done)) + .await + .unwrap() + .unwrap(); + } + inner.sockets.clear(); +} pub(super) async fn admission(State(state): State, headers: HeaderMap) -> Response { let result = async { let authority = connector_authority(&state, &headers)?; From c6f40ce315080e9e65a7f329f6423bbdcb8e5ab6 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:36:52 -0500 Subject: [PATCH 048/139] test(walletconnect): record protocol persistence across every recovery phase --- scripts/walletconnect-real-preflight-smoke.mjs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index 1997e9d92..959ab2fe1 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -50,6 +50,16 @@ try { return options; }); await context.route('**/*', route => new URL(route.request().url()).origin === options.origin ? route.continue() : route.abort()); + context.on('request', request => { + const path = new URL(request.url()).pathname; + if (path === '/api/apps/wallet-walletconnect/storage' && request.method() === 'POST') { + const key = request.postDataJSON().key; + run.runtimeWrites ??= {pairing:0, keychain:0, session:0, other:0}; + const kind = key.endsWith('//pairing') ? 'pairing' : key.endsWith('//keychain') ? 'keychain' + : /session|ethereum_provider/.test(key) ? 'session' : 'other'; + run.runtimeWrites[kind]++; + } + }); context.on('response', response => { const path = new URL(response.url()).pathname; if (path.startsWith('/api/apps/wallet-walletconnect/') && run.network.length < 128) { @@ -73,7 +83,7 @@ try { frame = await (await page.waitForSelector('#wc-real-preflight', {timeout:10000})).contentFrame(); assert.ok(frame); run.phase = 'runtime-store'; - await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width > 0, null, {timeout:20000}); + await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width === 280, null, {timeout:20000}); assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => self.origin), 'null'); assert.equal(await frame.locator('dialog[open] canvas').count(), 1); @@ -104,6 +114,7 @@ try { const trace = await frame.evaluate(() => window.storageTrace); assert.ok(trace.every(entry => !entry.protocol)); run.protocolInShim = false; + for (const kind of ['pairing', 'keychain', 'session']) assert.ok(run.runtimeWrites[kind] > 0, `${kind} persisted through Runtime`); run.status = 'PASS'; } catch { run.status = 'FAIL'; From 22297c6d16794ac02692045376898d09b77d91be Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:41:58 -0500 Subject: [PATCH 049/139] test(walletconnect): restart the source gateway in a fresh process --- .../wallet/walletconnect_real_relay.rs | 85 ++++++++++++++++--- .../src/api/gateway_walletconnect.rs | 15 ---- 2 files changed, 75 insertions(+), 25 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index e71b3a095..6f86b29dc 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -143,6 +143,73 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { println!("PASS: Runtime -> Exit harness -> authenticated Reown WSS upgrade and subscription; project file set; ephemeral localhost port; no 401/403"); } +// A separate process makes restart discard every gateway socket and global. +#[tokio::test] +#[ignore = "private worker for the real-relay paired recovery test"] +async fn walletconnect_gateway_process_worker() { + let mut bytes = Vec::new(); + std::io::Read::take(std::io::stdin(), 8192) + .read_to_end(&mut bytes) + .unwrap(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let data = std::path::Path::new(input["data"].as_str().unwrap()); + let addr = input["addr"].as_str().unwrap(); + let mut state = test_state(data); + state.browser_internet = persistent_internet(data).await; + let registry = Arc::new(ProviderRegistry::new()); + registry + .register_sub_provider( + "exit", + Arc::new(Exit { + path: data.join("real-relay.sock"), + calls: Arc::new(AtomicUsize::new(0)), + }), + ) + .await + .unwrap(); + state.provider_registry = Some(registry); + let app = gateway_router_with_api_url(state, format!("http://{addr}")); + let listener = TcpListener::bind(addr).await.unwrap(); + println!("WC_GATEWAY_READY"); + std::io::Write::flush(&mut std::io::stdout()).unwrap(); + axum::serve(listener, app).await.unwrap(); +} + +async fn start_gateway_process(f: &Fixture) -> tokio::process::Child { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; + let mut child = tokio::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "api::gateway::gateway_tests::wallet::walletconnect::real_relay::walletconnect_gateway_process_worker", "--ignored", "--nocapture"]) + .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()).kill_on_drop(true).spawn().unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(&serde_json::to_vec(&json!({"data":f.data.path(), "addr":f.addr})).unwrap()) + .await + .unwrap(); + let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap()); + tokio::time::timeout(Duration::from_secs(15), async { + let mut count = 0; + loop { + let mut line = String::new(); + let length = stdout.read_line(&mut line).await.unwrap(); + count += length; + assert!( + length > 0 && count <= 32768, + "gateway worker failed before readiness" + ); + if line.trim() == "WC_GATEWAY_READY" { + break; + } + } + }) + .await + .expect("gateway worker startup timeout"); + child.stdout = Some(stdout.into_inner()); + child +} + #[tokio::test] #[ignore = "operator acceptance: real relay, pinned SDK, Playwright Chromium and WebKit"] async fn walletconnect_real_project_opaque_preflight() { @@ -190,6 +257,9 @@ async fn walletconnect_real_project_opaque_preflight() { ) .unwrap(); f.allow().await; + f.gateway.abort(); + let _ = (&mut f.gateway).await; + let mut gateway_process = start_gateway_process(&f).await; let restart_path = f.data.path().join("restart.sock"); let restart = UnixListener::bind(&restart_path).unwrap(); let input = serde_json::to_vec(&json!({ @@ -215,16 +285,10 @@ async fn walletconnect_real_project_opaque_preflight() { let mut command = [0u8; 7]; tokio::time::timeout(Duration::from_secs(3), connection.read_exact(&mut command)).await.unwrap().unwrap(); assert_eq!(&command, b"restart"); - gateway_walletconnect::stop_for_restart_test(&f.state).await; - f.gateway.abort(); let _ = (&mut f.gateway).await; - let registry = f.state.provider_registry.clone(); - f.state = test_state(f.data.path()); - f.state.provider_registry = registry; - f.state.browser_internet = persistent_internet(f.data.path()).await; - let listener = TcpListener::bind(&f.addr).await.unwrap(); - f.app = gateway_router_with_api_url(f.state.clone(), format!("http://{}", f.addr)); - let app = f.app.clone(); - f.gateway = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); + let previous = gateway_process.id(); + gateway_process.kill().await.unwrap(); + gateway_process = start_gateway_process(&f).await; + assert_ne!(gateway_process.id(), previous, "restart requires a fresh gateway process"); connection.write_all(b"ready").await.unwrap(); } } @@ -233,6 +297,7 @@ async fn walletconnect_real_project_opaque_preflight() { if result.is_err() { waiting.abort(); } + gateway_process.kill().await.unwrap(); let output = result.expect("real relay paired recovery timeout"); println!("{}", String::from_utf8_lossy(&output.stdout)); // The Node driver emits only bounded, value-free evidence. SDK diagnostics diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index d779fbf88..a5db21a6b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -414,21 +414,6 @@ pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayS *expiry = 0; } } -#[cfg(test)] -pub(in crate::api::gateway) async fn stop_for_restart_test(state: &GatewayState) { - let mut inner = state.walletconnect.inner.lock().await; - inner.admissions.clear(); - for socket in inner.sockets.values() { - socket.cancel.send_replace(true); - } - for socket in inner.sockets.values_mut() { - tokio::time::timeout(Duration::from_secs(3), socket.done.wait_for(|done| *done)) - .await - .unwrap() - .unwrap(); - } - inner.sockets.clear(); -} pub(super) async fn admission(State(state): State, headers: HeaderMap) -> Response { let result = async { let authority = connector_authority(&state, &headers)?; From 9639f21877ac9bcfc75bd78f78db43db63462a44 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:42:39 -0500 Subject: [PATCH 050/139] test(walletconnect): retain production capsule documents across worker restart --- .../wallet/walletconnect_real_relay.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 6f86b29dc..79474931b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -154,8 +154,20 @@ async fn walletconnect_gateway_process_worker() { let input: Value = serde_json::from_slice(&bytes).unwrap(); let data = std::path::Path::new(input["data"].as_str().unwrap()); let addr = input["addr"].as_str().unwrap(); - let mut state = test_state(data); - state.browser_internet = persistent_internet(data).await; + // Preserve the already staged production documents and adapter on disk. + // test_state() seeds placeholder capsules, so this worker builds state directly. + let mut state = GatewayState { + provider_registry: None, + collaboration_chat_product_port: None, + collaboration_presence_product_port: None, + carrier_endpoint: None, + collaboration_discovery_service: None, + browser_internet: persistent_internet(data).await, + walletconnect: Default::default(), + identity_manager: Arc::new(std::sync::OnceLock::new()), + cache_dir: data.to_path_buf(), + data_dir: data.to_path_buf(), + }; let registry = Arc::new(ProviderRegistry::new()); registry .register_sub_provider( From b94673a9f8d808f50bfaa78ab9e455abff0eb16a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 13:57:51 -0500 Subject: [PATCH 051/139] test(walletconnect): prove rendered QR pixels and retain relay phase evidence --- .../walletconnect-real-preflight-smoke.mjs | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index 959ab2fe1..024c603f5 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -67,6 +67,25 @@ try { } }); const page = await context.newPage(); + run.relay = {opened:0, ready:0, closed:0, errors:0, sent:0, received:0, rpc:{}}; + page.on('websocket', socket => { + if (new URL(socket.url()).pathname !== '/api/apps/wallet-walletconnect/relay') return; + run.relay.opened++; + const observe = (payload, direction) => { + run.relay[direction]++; + try { + const message = JSON.parse(String(payload)); + if (direction === 'received' && message.ready === true) run.relay.ready++; + if (['irn_subscribe','irn_batchSubscribe','irn_publish','wc_proposeSession'].includes(message.method)) { + run.relay.rpc[message.method] = (run.relay.rpc[message.method] || 0) + 1; + } + } catch {} + }; + socket.on('framesent', ({payload}) => observe(payload, 'sent')); + socket.on('framereceived', ({payload}) => observe(payload, 'received')); + socket.on('close', () => run.relay.closed++); + socket.on('socketerror', () => run.relay.errors++); + }); run.phase = 'home'; assert.equal((await page.goto(`${options.origin}/apps/home/`, {timeout:10000})).status(), 200); run.phase = 'capsule'; @@ -83,7 +102,17 @@ try { frame = await (await page.waitForSelector('#wc-real-preflight', {timeout:10000})).contentFrame(); assert.ok(frame); run.phase = 'runtime-store'; - await frame.waitForFunction(() => window.failed || document.querySelector('dialog[open] canvas')?.width === 280, null, {timeout:20000}); + await frame.waitForFunction(() => { + if (window.failed) return true; + const canvas = document.querySelector('dialog[open] canvas'); + if (!canvas) return false; + const pixels = canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data; + let black = false, white = false; + for (let i=0; i 240; } + } + return black && white; + }, null, {timeout:20000}); assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => self.origin), 'null'); assert.equal(await frame.locator('dialog[open] canvas').count(), 1); @@ -123,7 +152,13 @@ try { try { run.state = await Promise.race([ frame.evaluate(() => ({origin:self.origin, phase:window.phase, refusal:window.refusal, - errorName:window.errorName, runtimeTrace:window.runtimeTrace, storageTrace:window.storageTrace})), + errorName:window.errorName, runtimeTrace:window.runtimeTrace, storageTrace:window.storageTrace, + qr:[...document.querySelectorAll('dialog canvas')].slice(0,2).map(canvas => { + const pixels = canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data; + let black=0, white=0; + for (let i=0;i240)white++; } + return {width:canvas.width,height:canvas.height,open:canvas.closest('dialog').open,black,white}; + })})), new Promise((_, reject) => setTimeout(() => reject(new Error('state timeout')), 3000)), ]); } catch { run.stateUnavailable = true; } From cfa0739850135c21689b1083d8adfc834fa9f64c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:02:27 -0500 Subject: [PATCH 052/139] test(walletconnect): expose the capsule frame and poll recovery independently of paint --- scripts/walletconnect-real-preflight-smoke.mjs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index 024c603f5..39391ceb1 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -93,6 +93,7 @@ try { await page.evaluate(origin => { const frame = window.document.createElement('iframe'); frame.id = 'wc-real-preflight'; + frame.style = 'position:fixed;inset:0;width:100%;height:100%;z-index:2147483647'; frame.sandbox = 'allow-downloads allow-forms allow-modals allow-pointer-lock allow-scripts'; frame.src = `${origin}/apps/wallet-walletconnect/wc-real.html`; window.document.body.append(frame); @@ -101,7 +102,7 @@ try { assert.equal(run.csp, expectedCsp); frame = await (await page.waitForSelector('#wc-real-preflight', {timeout:10000})).contentFrame(); assert.ok(frame); - run.phase = 'runtime-store'; + run.phase = 'qr-render'; await frame.waitForFunction(() => { if (window.failed) return true; const canvas = document.querySelector('dialog[open] canvas'); @@ -112,17 +113,17 @@ try { if (pixels[i+3] === 255) { black ||= pixels[i] < 10; white ||= pixels[i] > 240; } } return black && white; - }, null, {timeout:20000}); + }, null, {timeout:20000, polling:100}); assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => self.origin), 'null'); assert.equal(await frame.locator('dialog[open] canvas').count(), 1); run.qr = 'PASS'; run.phase = 'pairing'; - await frame.waitForFunction(() => typeof window.pairingUri === 'string', null, {timeout:10000}); + await frame.waitForFunction(() => typeof window.pairingUri === 'string', null, {timeout:10000, polling:100}); const uri = await frame.evaluate(() => window.pairingUri); await bounded(wallet.core.pairing.pair({uri})); const session = await bounded(approved, 30000); - await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:20000}); + await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:20000, polling:100}); assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => window.provider.session.topic), session.topic); await bounded(wallet.ping({topic:session.topic})); @@ -132,7 +133,7 @@ try { run.phase = phase; if (phase === 'homeRestart') await restart(); await frame.evaluate(() => location.reload()); - await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:30000}); + await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:30000, polling:100}); assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => window.provider.session.topic), session.topic); assert.equal(await frame.locator('dialog[open] canvas').count(), 0); @@ -145,7 +146,8 @@ try { run.protocolInShim = false; for (const kind of ['pairing', 'keychain', 'session']) assert.ok(run.runtimeWrites[kind] > 0, `${kind} persisted through Runtime`); run.status = 'PASS'; - } catch { + } catch (error) { + run.failureKind = ['TimeoutError','AssertionError','Error'].includes(error.name) ? error.name : 'Error'; run.status = 'FAIL'; } finally { if (frame) { From b6c02699a08dfe070920b38975ea17512019267e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:26:53 -0500 Subject: [PATCH 053/139] feat(walletconnect): run signing in the opaque connector and guide interrupted requests --- capsules/home/browser/home-shell-host.js | 5 +- .../browser/home-wallet-connector-host.js | 191 ++++-------------- capsules/home/browser/shell-core.js | 1 - capsules/inbox/browser/inbox.js | 1 + .../browser/wallet-walletconnect.js | 138 ++++--------- .../browser/walletconnect-client.mjs | 99 +++++++++ scripts/browser-internet-consent.test.mjs | 1 + scripts/lib/walletconnect-capsule-fixture.mjs | 43 ++++ .../lib/walletconnect-connector-loader.mjs | 7 - scripts/lib/walletconnect-sdk-fixture.mjs | 5 - scripts/test-source-gate.sh | 1 + .../wallet-connector-transaction-smoke.mjs | 9 +- .../wallet-connectors-uiux-layout-smoke.mjs | 24 ++- scripts/walletconnect-capsule.test.mjs | 20 ++ ...walletconnect-connector-deadlines.test.mjs | 72 ------- scripts/walletconnect-home-host.test.mjs | 191 ------------------ 16 files changed, 268 insertions(+), 540 deletions(-) create mode 100644 capsules/wallet-walletconnect/browser/walletconnect-client.mjs create mode 100644 scripts/lib/walletconnect-capsule-fixture.mjs delete mode 100644 scripts/lib/walletconnect-connector-loader.mjs delete mode 100644 scripts/lib/walletconnect-sdk-fixture.mjs create mode 100644 scripts/walletconnect-capsule.test.mjs delete mode 100644 scripts/walletconnect-connector-deadlines.test.mjs delete mode 100644 scripts/walletconnect-home-host.test.mjs diff --git a/capsules/home/browser/home-shell-host.js b/capsules/home/browser/home-shell-host.js index 615344d66..37b808225 100644 --- a/capsules/home/browser/home-shell-host.js +++ b/capsules/home/browser/home-shell-host.js @@ -93,6 +93,7 @@ const SHELL_MESSAGE_OPEN_TARGET_SOURCES = Object.freeze({ "home-agent": new Set(["marketplace", "system", "inbox"]), "archive-manager": new Set(["library"]), browser: new Set(["library", "inbox"]), + "wallet-walletconnect": new Set(["inbox"]), "chat-room": new Set(["library", "people", "inbox"]), "gba-emulator": new Set(["library"]), "home-cli": "visible-target", @@ -2174,11 +2175,11 @@ window.addEventListener("message", (event) => { console.warn("home ignored an app's Browser open with a query", context.targetId); return; } - if (context.targetId === "browser" && target === "inbox") { + if (["browser", "wallet-walletconnect"].includes(context.targetId) && target === "inbox") { if (!hasExactMessageKeys(data, ["type", "target", "query", "homeToken"]) || !data.query || typeof data.query !== "object" || Array.isArray(data.query) || Object.keys(data.query).length !== 1 - || data.query.notification_id !== "browser-internet:permission") return; + || data.query.notification_id !== (context.targetId === "browser" ? "browser-internet:permission" : "walletconnect-internet:permission")) return; } if (context.targetId === "chat-room" && ["people", "inbox"].includes(target)) { if (!hasExactMessageKeys(data, ["type", "target", "query", "homeToken"]) diff --git a/capsules/home/browser/home-wallet-connector-host.js b/capsules/home/browser/home-wallet-connector-host.js index ae6ba6707..cb7ed91aa 100644 --- a/capsules/home/browser/home-wallet-connector-host.js +++ b/capsules/home/browser/home-wallet-connector-host.js @@ -9,14 +9,7 @@ const RUNTIME_REQUEST_SCHEMA = "elastos.home.wallet-connector.effect.request/v1" const RUNTIME_RESULT_SCHEMA = "elastos.home.wallet-connector.effect.result/v1"; const METAMASK_CONNECTOR_ID = "wallet-metamask"; const UNISAT_CONNECTOR_ID = "wallet-unisat"; -const WALLETCONNECT_ID = "wallet-walletconnect"; -const CONNECTOR_IDS = new Set([METAMASK_CONNECTOR_ID, UNISAT_CONNECTOR_ID, WALLETCONNECT_ID]); -let walletConnectProvider = null; -let walletConnectToken = ""; -let walletConnectGeneration = 0; -let walletConnectPrincipal = ""; -let walletConnectAdapter = null; -const observedWalletConnectProviders = new WeakSet(); +const CONNECTOR_IDS = new Set([METAMASK_CONNECTOR_ID, UNISAT_CONNECTOR_ID]); const METAMASK_RDNS = "io.metamask"; const BRAVE_RDNS = "com.brave.wallet"; const MAX_EIP6963_PROVIDERS = 32; @@ -166,62 +159,7 @@ function selectMetaMaskCompatibleProvider() { throw new Error("MetaMask or Brave Wallet was not found in this browser profile."); } -async function walletConnect(connectorToken) { - const api = (path, init = {}) => fetchJson(`/api/apps/wallet-walletconnect/${path}`, { - ...init, headers: { "x-elastos-walletconnect-connector": connectorToken }, - }); - const config = await api("host-config", { method: "POST" }); - if (config.internet.status !== "granted") throw new Error("Allow WalletConnect internet access in Inbox, then connect again."); - if (walletConnectToken && walletConnectToken !== connectorToken) { - await walletConnectProvider?.signer.client.core.relayer.transportClose(); - } - // Each principal has its own bundled SDK module state and Core storage prefix. - const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(config.principal_id)); - const instance = [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, "0")).join(""); - const adapter = await import(`${config.sdk_asset_path}?instance=${instance}`); - walletConnectProvider = await adapter.connectWalletConnectEvm({ - contextKey: config.principal_id, projectId: config.projectId, chains: [1, 20, 8453, 11155111], api, - runtimeUrl: new URL("/api/apps/wallet-walletconnect", location.origin).href, - relayUrl: `${location.origin.replace(/^http/, "ws")}/api/apps/wallet-walletconnect/relay`, - metadata: { name: "ElastOS Home", description: "Runtime wallet approval", url: location.origin, icons: [] }, - }); - walletConnectToken = connectorToken; - walletConnectPrincipal = config.principal_id; - walletConnectAdapter = adapter; - if (!observedWalletConnectProviders.has(walletConnectProvider)) { - const current = walletConnectProvider; - observedWalletConnectProviders.add(current); - for (const event of ["accountsChanged", "chainChanged", "disconnect"]) { - current.on(event, () => { if (walletConnectProvider === current) walletConnectGeneration++; }); - } - } - return walletConnectProvider; -} - async function performConnectorEffect(connectorId, connectorToken, action) { - if (connectorId === WALLETCONNECT_ID && action.kind === "status") { - const current = await fetchJson("/api/apps/wallet-walletconnect/host-config", { - headers: { "x-elastos-walletconnect-connector": connectorToken }, - }); - const connected = current.internet.status === "granted" && current.principal_id === walletConnectPrincipal - && walletConnectProvider?.session?.expiry > Date.now() / 1000 - && walletConnectProvider?.connected && walletConnectProvider?.signer?.client.core.relayer.connected; - return Object.freeze({ status: connected ? "connected" : "disconnected", revision: walletConnectGeneration }); - } - if (connectorId === WALLETCONNECT_ID && action.kind === "disconnect") { - walletConnectGeneration++; - const api = (path, init = {}) => fetchJson(`/api/apps/wallet-walletconnect/${path}`, { - ...init, headers: { "x-elastos-walletconnect-connector": connectorToken }, - }); - const current = await api("host-config"); - if (walletConnectPrincipal === current.principal_id) await walletConnectAdapter?.disconnectWalletConnectEvm({ api }); - else await walletConnectProvider?.signer.client.core.relayer.transportClose(); - walletConnectProvider = null; walletConnectToken = ""; walletConnectPrincipal = ""; - return Object.freeze({ status: "disconnected" }); - } - if (connectorId === WALLETCONNECT_ID && action.kind === "link") { - return linkEvmWallet(connectorToken, await walletConnect(connectorToken), WALLETCONNECT_ID); - } if (connectorId === METAMASK_CONNECTOR_ID && action.kind === "link") { return linkEvmWallet(connectorToken); } @@ -234,49 +172,33 @@ async function performConnectorEffect(connectorId, connectorToken, action) { throw new Error("Unsupported wallet request."); } -function walletConnectSignData(message, connectorId) { - if (connectorId !== WALLETCONNECT_ID) return message; - if (/^0[xX](?:[0-9a-fA-F]{2})*$/.test(message)) return "0x" + message.slice(2); - return "0x" + [...new TextEncoder().encode(message)].map(byte => byte.toString(16).padStart(2, "0")).join(""); -} - -async function linkEvmWallet(connectorToken, provider = selectMetaMaskCompatibleProvider(), connectorId = METAMASK_CONNECTOR_ID) { - const generation = walletConnectGeneration; +async function linkEvmWallet(connectorToken) { + const provider = selectMetaMaskCompatibleProvider(); const accounts = await provider.request({ method: "eth_requestAccounts" }); const address = requireEvmAddress(firstProviderAccount(accounts)); const chainId = requireEvmChainId(await provider.request({ method: "eth_chainId" })); const challengeResult = await runtimePost( "/api/apps/home/wallet-connector/evm/link/challenge", - connectorBody(connectorId, connectorToken, { + connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { address, chain_id: chainId, }), ); - const challenge = requireEvmChallenge(challengeResult, connectorId); + const challenge = requireEvmChallenge(challengeResult); const signer = requireEvmAddress(await currentEvmAccount(provider)); ensureSameAddress(signer, address, "Wallet account changed before signing."); - if (connectorId === WALLETCONNECT_ID && (generation !== walletConnectGeneration || !Number.isSafeInteger(challenge.expires_at) || challenge.expires_at <= Date.now() / 1000)) throw new Error("Wallet changed. Connect again."); - if (connectorId === WALLETCONNECT_ID && requireEvmChainId(await provider.request({ method: "eth_chainId" })) !== chainId) throw new Error("Wallet network changed. Connect again."); const signature = requireProviderResult(await provider.request({ method: "personal_sign", - params: [walletConnectSignData(challenge.message, connectorId), signer], + params: [challenge.message, signer], }), 16 * 1024, "Wallet returned an invalid signature."); - if (connectorId === WALLETCONNECT_ID) { - const currentSigner = requireEvmAddress(await currentEvmAccount(provider)); - const currentChain = requireEvmChainId(await provider.request({ method: "eth_chainId" })); - ensureSameAddress(currentSigner, address, "Wallet account changed. Connect again."); - if (generation !== walletConnectGeneration || currentChain !== chainId || challenge.expires_at <= Date.now() / 1000) { - throw new Error("Wallet changed or the challenge expired. Connect again."); - } - } const verified = await runtimePost( "/api/apps/home/wallet-connector/evm/link/verify", - connectorBody(connectorId, connectorToken, { + connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { message: challenge.message, signature, }), ); - requireRuntimeCompletion(verified, "evm_link_complete", connectorId, "linked"); + requireRuntimeCompletion(verified, "evm_link_complete", METAMASK_CONNECTOR_ID, "linked"); return Object.freeze({ status: "linked" }); } @@ -308,52 +230,26 @@ async function linkBitcoinWallet(connectorToken) { } async function completeApproval(connectorId, connectorToken, approvalRequestId) { - const provider = connectorId === WALLETCONNECT_ID ? await walletConnect(connectorToken) - : connectorId === METAMASK_CONNECTOR_ID ? selectMetaMaskCompatibleProvider() : requireUniSatProvider(); + const provider = connectorId === METAMASK_CONNECTOR_ID + ? selectMetaMaskCompatibleProvider() + : requireUniSatProvider(); const encodedRequestId = encodeURIComponent(approvalRequestId); - if (connectorId === WALLETCONNECT_ID) { - const review = await runtimePost(`/api/apps/home/wallet-connector/approvals/${encodedRequestId}/review`, connectorBody(connectorId, connectorToken)); - ensureSameAddress(await currentEvmAccount(provider), review.address, "Select the requested account in your phone wallet, then review again."); - const chain = `eip155:${requireEvmChainId(await provider.request({ method: "eth_chainId" }))}`; - if (chain !== review.chain_namespace) throw new Error("Select the request network in your phone wallet, then review again."); - const remaining = review.expires_at - Math.ceil(Date.now() / 1000); - if (!Number.isSafeInteger(review.expires_at) || remaining <= 0 - || review.intent === "transaction_intent" && remaining < 300) { - throw new Error("Wallet request expires soon. Request a fresh review."); - } - } const response = await runtimePost( `/api/apps/home/wallet-connector/approvals/${encodedRequestId}/handoff`, connectorBody(connectorId, connectorToken), ); - const { handoff, evmChains, binding } = requireHandoffResponse( + const { handoff, evmChains } = requireHandoffResponse( response, connectorId, approvalRequestId, ); - if (connectorId !== UNISAT_CONNECTOR_ID) { - return completeEvmApproval(provider, connectorToken, handoff, evmChains, connectorId, binding); + if (connectorId === METAMASK_CONNECTOR_ID) { + return completeEvmApproval(provider, connectorToken, handoff, evmChains); } return completeBitcoinApproval(provider, connectorToken, handoff); } -async function completeEvmApproval(provider, connectorToken, handoff, evmChains, connectorId = METAMASK_CONNECTOR_ID, binding) { - const generation = walletConnectGeneration; - const checkBinding = async (startingRequest = true) => { - if (connectorId !== WALLETCONNECT_ID) return; - const chain = `eip155:${requireEvmChainId(await provider.request({ method: "eth_chainId" }))}`; - const account = requireEvmAddress(await currentEvmAccount(provider)); - ensureSameAddress(account, handoff.signer, "Wallet changed. Request a new review."); - if (chain !== binding.chain_namespace || generation !== walletConnectGeneration - || !Number.isSafeInteger(binding.expires_at) || binding.expires_at <= Date.now() / 1000) { - throw new Error("Wallet request changed or expired. Request a new review."); - } - const ttl = binding.expires_at - Math.ceil(Date.now() / 1000); - if (startingRequest && handoff.intent === "transaction_intent" && ttl < 300) { - throw new Error("Wallet request expires soon. Request a fresh review."); - } - return Math.min(600, Math.max(ttl, 300)); - }; +async function completeEvmApproval(provider, connectorToken, handoff, evmChains) { const signer = requireEvmAddress(await currentEvmAccount(provider)); ensureSameAddress(signer, handoff.signer, "Switch to the linked account before approving."); const path = `/api/apps/home/wallet-connector/approvals/${encodeURIComponent(handoff.request_id)}/complete`; @@ -365,25 +261,17 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, handoff.signer, "Switch to the linked account before approving.", ); - const expiry = await checkBinding(); - const invalidHash = "Wallet returned an invalid transaction hash. The wallet may have sent it. Check your wallet before sending again."; const transactionHash = requireProviderResult(await provider.request({ method: "eth_sendTransaction", params: [handoff.transaction], - }, expiry), 66, invalidHash); - if (!/^0x[0-9a-fA-F]{64}$/.test(transactionHash)) { - throw new Error(invalidHash); - } - try { - const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { - payload_hash: handoff.payload_hash, - signer: currentSigner, - transaction_hash: transactionHash, - })); - requireApprovalCompletion(completed, connectorId, handoff.request_id); - } catch { - throw new Error(`Wallet returned transaction hash ${transactionHash}. Runtime could not confirm it. Keep this hash and check it before sending again.`); - } + }), 66, "Wallet returned an invalid transaction hash."); + if (!/^0x[0-9a-fA-F]{64}$/.test(transactionHash)) throw new Error('Wallet returned an invalid transaction hash. Check your wallet before sending again.'); + const completed = await runtimePost(path, connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { + payload_hash: handoff.payload_hash, + signer: currentSigner, + transaction_hash: transactionHash, + })); + requireApprovalCompletion(completed, METAMASK_CONNECTOR_ID, handoff.request_id); return Object.freeze({ status: "completed", effect: "transaction" }); } const method = handoff.intent === "browser_typed_data_sign" @@ -391,18 +279,16 @@ async function completeEvmApproval(provider, connectorToken, handoff, evmChains, : "personal_sign"; const params = method === "eth_signTypedData_v4" ? [signer, handoff.message] - : [walletConnectSignData(handoff.message, connectorId), signer]; - const expiry = await checkBinding(); - const signature = requireProviderResult(await provider.request({ method, params }, expiry), 16 * 1024, + : [handoff.message, signer]; + const signature = requireProviderResult(await provider.request({ method, params }), 16 * 1024, "Wallet returned an invalid signature."); - await checkBinding(false); - const completed = await runtimePost(path, connectorBody(connectorId, connectorToken, { + const completed = await runtimePost(path, connectorBody(METAMASK_CONNECTOR_ID, connectorToken, { payload_hash: handoff.payload_hash, signature, signature_type: method === "eth_signTypedData_v4" ? "eip712" : "personal_sign", signer, })); - requireApprovalCompletion(completed, connectorId, handoff.request_id); + requireApprovalCompletion(completed, METAMASK_CONNECTOR_ID, handoff.request_id); return Object.freeze({ status: "completed", effect: "signature" }); } @@ -485,8 +371,12 @@ function requireEvmChain(chains, chainId) { function requireHandoffResponse(response, connectorId, requestId) { if ( !hasExactKeys(response, [ - "schema", "action", "connector_id", "request_id", "handoff", "evm_chains", - ...(connectorId === WALLETCONNECT_ID ? ["binding"] : []), + "schema", + "action", + "connector_id", + "request_id", + "handoff", + "evm_chains", ]) || response.schema !== RUNTIME_RESULT_SCHEMA || response.action !== "approval_handoff" @@ -545,14 +435,7 @@ function requireHandoffResponse(response, connectorId, requestId) { ) { throw new Error("Runtime returned an invalid EVM signature handoff."); } - if (connectorId === WALLETCONNECT_ID && ( - !hasExactKeys(response.binding, ["principal_id", "requested_by_actor", "account_id", "chain_namespace", "payload_hash", "expires_at"]) - || !boundedText(response.binding.principal_id, 256) || !boundedText(response.binding.requested_by_actor, 256) - || !boundedText(response.binding.account_id, 256) || !/^eip155:[1-9][0-9]*$/.test(response.binding.chain_namespace) - || response.binding.payload_hash !== handoff.payload_hash - || !Number.isSafeInteger(response.binding.expires_at) || response.binding.expires_at <= Date.now() / 1000 - )) throw new Error("Runtime returned an invalid WalletConnect request binding."); - return { handoff, evmChains: response.evm_chains, binding: response.binding }; + return { handoff, evmChains: response.evm_chains }; } function validTransaction(transaction, signer) { @@ -570,12 +453,12 @@ function validTransaction(transaction, signer) { && /^0x[0-9a-fA-F]+$/.test(transaction.chainId); } -function requireEvmChallenge(response, connectorId = METAMASK_CONNECTOR_ID) { +function requireEvmChallenge(response) { if ( !hasExactKeys(response, ["schema", "action", "connector_id", "challenge"]) || response.schema !== RUNTIME_RESULT_SCHEMA || response.action !== "evm_link_challenge" - || response.connector_id !== connectorId + || response.connector_id !== METAMASK_CONNECTOR_ID ) { throw new Error("Runtime returned an invalid EVM challenge envelope."); } @@ -800,7 +683,7 @@ function validAction(action) { if (!action || typeof action !== "object" || Array.isArray(action)) { return false; } - if (action.kind === "link" || action.kind === "disconnect" || action.kind === "status") { + if (action.kind === "link") { return hasExactKeys(action, ["kind"]); } return action.kind === "approve" diff --git a/capsules/home/browser/shell-core.js b/capsules/home/browser/shell-core.js index 1191d2bb0..4d8b33f5c 100644 --- a/capsules/home/browser/shell-core.js +++ b/capsules/home/browser/shell-core.js @@ -83,7 +83,6 @@ export function createHomeBackgroundImageReader() { export async function fetchJson(url, init) { const requiresHomeAuthority = url.startsWith("/api/apps/home/wallet-connector/") - || url.startsWith("/api/apps/wallet-walletconnect/") || url === "/api/apps/home/launch" || url === "/api/apps/home/active-shell" || url === "/api/apps/home/shared-content/get" diff --git a/capsules/inbox/browser/inbox.js b/capsules/inbox/browser/inbox.js index f1a7657b3..0b33aafc1 100644 --- a/capsules/inbox/browser/inbox.js +++ b/capsules/inbox/browser/inbox.js @@ -536,6 +536,7 @@ const stepUpToken = current.status === "revoked" ? undefined : await requestPasskeyStepUp(operation, current.request); await inboxAction(id, { step_up_token: stepUpToken }); await loadInbox(); notifyHome(); + if (operation === 'walletconnect.internet.grant') window.top.postMessage({type:'home:open-target',homeToken:state.homeToken,target:'wallet-walletconnect',query:{}},homeParentOrigin); } finally { setButtonsDisabled(false); } }; if (actionId?.startsWith("walletconnect-internet-allow:")) { diff --git a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js index 97f49d186..1fd5ee985 100644 --- a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js +++ b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js @@ -1,14 +1,10 @@ +import { installWalletConnectStorage } from './walletconnect-storage.mjs'; +import { createWalletConnectClient } from './walletconnect-client.mjs'; import { createHomeClipboardClient, } from "/apps/home/home-clipboard-client.js?v=home-20260726a"; const CONNECTOR_ID = "wallet-walletconnect"; -const HOST_EFFECT_TYPE = "home:wallet-connector-effect"; -const HOST_EFFECT_SCHEMA = "elastos.home.wallet-connector-effect/v1"; -const HOST_RESULT_TYPE = "home:wallet-connector-effect-result"; -const HOST_RESULT_SCHEMA = "elastos.home.wallet-connector-effect-result/v1"; -// Cover QR pairing (180 s), the Runtime approval window (600 s), and delivery. -const HOST_EFFECT_TIMEOUT_MS = 810_000; const connectButton = document.querySelector("#wallet-connect"); const statusNode = document.querySelector("#wallet-status"); const stateNode = document.querySelector("#wallet-state"); @@ -17,15 +13,21 @@ const requestsNode = document.querySelector("#wallet-requests"); const frameHomeToken = readLaunchToken(); const homeOrigin = readQueryParam("home_origin"); let hostEffectInFlight = false; -let hostRequestSequence = 0; +const clearMemory = installWalletConnectStorage(window); +const runtimeOrigin = new URL(import.meta.url).origin; +const api = (resource, init={}) => fetchJson(resource.startsWith('/api/') ? runtimeOrigin+resource : `${runtimeOrigin}/api/apps/${CONNECTOR_ID}/${resource}`, { + ...init, headers:shellHeaders({'content-type':'application/json'}), +}); +const connector = createWalletConnectClient({api,origin:runtimeOrigin,clearMemory}); +window.addEventListener('focus',()=>refreshWalletState().catch(()=>{})); let connectionTimer; let connectionRevision; function watchConnection() { - if (connectionTimer || typeof window.setInterval !== "function") return; + if (!frameHomeToken || connectionTimer || typeof window.setInterval !== "function") return; connectionTimer = window.setInterval(async () => { if (hostEffectInFlight) return; try { - const current = await requestHomeWalletEffect({ kind: "status" }); + const current = await requestCapsuleWalletEffect({ kind: "status" }); document.querySelector("#wallet-connection").textContent = current.status === "connected" ? "Connected" : "Disconnected"; if (current.status === "connected" && connectionRevision !== undefined && connectionRevision !== current.revision) { showStatus("Wallet changed. Check the account and network on your phone.", "muted"); @@ -46,12 +48,13 @@ boot(); function boot() { document.querySelector("#wallet-disconnect")?.addEventListener("click", async () => { - try { await requestHomeWalletEffect({ kind: "disconnect" }); document.querySelector("#wallet-connection").textContent = "Disconnected"; showStatus("Disconnected. Linked accounts stay in Wallet.", "muted"); } + try { await requestCapsuleWalletEffect({ kind: "disconnect" }); document.querySelector("#wallet-connection").textContent = "Disconnected"; showStatus("Disconnected. Linked accounts stay in Wallet.", "muted"); } catch (error) { showStatus(errorMessage(error), "error"); } }); connectButton?.addEventListener("click", onConnect); accountsNode?.addEventListener("click", onAccountClick); requestsNode?.addEventListener("click", onRequestClick); + watchConnection(); setState("0 linked"); refreshWalletState().catch((error) => { showStatus(errorMessage(error), "error"); @@ -62,7 +65,7 @@ async function onConnect() { setButtonBusy(connectButton, true); showStatus("Approve in your phone wallet.", "muted"); try { - await requestHomeWalletEffect({ kind: "link" }); + await requestCapsuleWalletEffect({ kind: "link" }); document.querySelector("#wallet-connection").textContent = "Connected"; watchConnection(); showStatus("Approval method added.", "success"); @@ -141,7 +144,7 @@ function renderRequests(requests) { } requestsNode.replaceChildren(); const connectorRequests = requests.filter((request) => ( - !isManagedWalletRequest(request) && isMetaMaskSignableRequest(request) + !isManagedWalletRequest(request) && isWalletConnectSignableRequest(request) )); if (connectorRequests.length === 0) { requestsNode.append(emptyNode("No approval requests.")); @@ -168,6 +171,12 @@ function requestCard(request) { || readText(request?.resource) || "Approval requested."; main.append(title, meta, reason); + if (request.status === 'approved' && request.intent === 'transaction_intent') { + const recovery = document.createElement('p'); + recovery.textContent = 'Check your phone wallet. It may have sent this transaction. Check Wallet activity before you send again.'; + card.append(main,recovery); + return card; + } const sign = document.createElement("button"); sign.className = "wallet-button"; sign.type = "button"; @@ -203,7 +212,7 @@ async function onRequestClick(event) { setButtonBusy(button, true); showStatus("Preparing request.", "muted"); try { - const result = await requestHomeWalletEffect({ kind: "approve", approvalRequestId }); + const result = await requestCapsuleWalletEffect({ kind: "approve", approvalRequestId }); watchConnection(); showStatus( result.effect === "transaction" ? "Transaction sent." : "Request signed.", @@ -218,96 +227,19 @@ async function onRequestClick(event) { } } -function requestHomeWalletEffect(action) { - if (!frameHomeToken || !homeOrigin || window.top === window) { - return Promise.reject(new Error("Open this approval method from Wallet.")); - } - if (hostEffectInFlight) { - return Promise.reject(new Error("A wallet request is already active.")); - } - const requestId = nextHostRequestId(); +async function requestCapsuleWalletEffect(action) { + if (!frameHomeToken || hostEffectInFlight) throw new Error('A wallet request is already active.'); hostEffectInFlight = true; - return new Promise((resolve, reject) => { - const timeout = window.setTimeout(() => { - finish(); - reject(new Error("Wallet request timed out.")); - }, action.kind === "status" ? 10000 : ["approve", "link"].includes(action.kind) ? HOST_EFFECT_TIMEOUT_MS : 30000); - const finish = () => { - window.clearTimeout(timeout); - window.removeEventListener("message", onMessage); - hostEffectInFlight = false; - }; - const onMessage = (event) => { - const data = event.data; - if ( - event.source !== window.top - || event.origin !== homeOrigin - || data?.type !== HOST_RESULT_TYPE - || data.schema !== HOST_RESULT_SCHEMA - || data.requestId !== requestId - || data.connectorId !== CONNECTOR_ID - ) { - return; - } - const hasResult = hasExactKeys(data, [ - "type", - "schema", - "requestId", - "connectorId", - "result", - ]); - const hasError = hasExactKeys(data, [ - "type", - "schema", - "requestId", - "connectorId", - "error", - ]); - if (!hasResult && !hasError) { - return; - } - finish(); - if (hasError) { - reject(new Error(readText(data.error) || "Wallet request failed.")); - return; - } - if (action.kind === "status") { - if (!hasExactKeys(data.result, ["status", "revision"]) || !["connected", "disconnected"].includes(data.result.status) - || !Number.isSafeInteger(data.result.revision)) { reject(new Error("Home returned an invalid connection state.")); return; } - resolve(data.result); return; - } - const expectedResultKeys = action.kind !== "approve" ? ["status"] : ["status", "effect"]; - if ( - !hasExactKeys(data.result, expectedResultKeys) - || data.result.status !== (action.kind === "link" ? "linked" : action.kind === "disconnect" ? "disconnected" : "completed") - || ( - action.kind === "approve" - && !["signature", "transaction"].includes(data.result.effect) - ) - ) { - reject(new Error("Home returned an invalid wallet result.")); - return; + try { + if (['link','approve'].includes(action.kind)) { + const consent = await api('internet',{method:'POST',body:JSON.stringify({action:'request'})}); + if (consent.status !== 'granted') { + window.top.postMessage({type:'home:open-target',target:'inbox',query:{notification_id:'walletconnect-internet:permission'},homeToken:frameHomeToken},homeOrigin); + throw new Error('Allow WalletConnect internet access in Inbox, then connect again.'); } - resolve(data.result); - }; - window.addEventListener("message", onMessage); - window.top.postMessage({ - type: HOST_EFFECT_TYPE, - schema: HOST_EFFECT_SCHEMA, - requestId, - connectorId: CONNECTOR_ID, - connectorToken: frameHomeToken, - action, - }, homeOrigin); - }); -} - -function nextHostRequestId() { - hostRequestSequence += 1; - const random = typeof window.crypto?.randomUUID === "function" - ? window.crypto.randomUUID() - : `${Date.now().toString(36)}-${hostRequestSequence}`; - return `wallet-effect:${random}`; + } + return await connector.effect(action); + } finally { hostEffectInFlight = false; } } function walletIntentLabel(intent) { @@ -341,7 +273,7 @@ function isManagedWalletRequest(request) { return ["managed_evm", "managed_btc_p2wpkh"].includes(readText(request?.proof_type)); } -function isMetaMaskSignableRequest(request) { +function isWalletConnectSignableRequest(request) { return readText(request?.connector_id) === CONNECTOR_ID && readText(request?.intent) !== "bitcoin_bip322_proof" && ["siwe", "siwe_erc1271"].includes(readText(request?.proof_type)); @@ -359,7 +291,7 @@ async function fetchJson(url, init) { const response = await fetch(url, init); if (!response.ok) { const detail = await response.text().catch(() => ""); - throw new Error(`request failed: ${response.status}${detail.trim() ? ` ${detail.trim()}` : ""}`); + throw new Error(response.status === 403 ? 'This wallet window expired. Close it and open WalletConnect again.' : detail.trim() || 'Runtime could not complete this wallet request. Try again.'); } return response.json(); } diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs new file mode 100644 index 000000000..3f87a1f38 --- /dev/null +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -0,0 +1,99 @@ +// This module runs only in the connector's opaque frame. Runtime owns approval authority. +export function createWalletConnectClient({ api, origin, loadAdapter = () => import('./vendor/reown-appkit.js'), clearMemory = () => {} }) { + let provider, adapter, generation = 0; + const address = async () => { + const accounts = await provider.request({method:'eth_accounts'}); + const value = accounts?.[0]; + if (!/^0x[0-9a-fA-F]{40}$/.test(value || '')) throw new Error('Select an account in your phone wallet.'); + return value; + }; + const chain = async () => { + const value = await provider.request({method:'eth_chainId'}); + if (!/^0x[0-9a-fA-F]+$/.test(value || '')) throw new Error('Wallet returned an invalid chain.'); + return `eip155:${Number.parseInt(value,16)}`; + }; + const same = (a,b) => String(a).toLowerCase() === String(b).toLowerCase(); + const signData = message => /^0[xX](?:[0-9a-fA-F]{2})*$/.test(message) ? '0x'+message.slice(2) + : '0x'+[...new TextEncoder().encode(message)].map(b=>b.toString(16).padStart(2,'0')).join(''); + const connect = async () => { + const config = await api('wallet/config'); + const permission = await api('internet'); + if (permission.status !== 'granted') throw new Error('Allow WalletConnect internet access in Inbox, then connect again.'); + adapter ??= await loadAdapter(); + const current = await adapter.connectWalletConnectEvm({ + contextKey:'wallet-walletconnect', projectId:config.walletconnect.project_id, chains:[1,20,8453,11155111], api, + runtimeUrl:`${origin}/api/apps/wallet-walletconnect`, relayUrl:`${origin.replace(/^http/,'ws')}/api/apps/wallet-walletconnect/relay`, + metadata:{name:'ElastOS Home',description:'Runtime wallet approval',url:origin,icons:[]}, + }); + if (current !== provider) { + provider = current; + for (const name of ['accountsChanged','chainChanged','disconnect']) provider.on(name,()=>generation++); + } + return provider; + }; + const disconnect = async () => { + generation++; + try { await adapter?.disconnectWalletConnectEvm({api}); } + finally { + provider = undefined; clearMemory(); + await api('storage',{method:'DELETE'}); + } + return {status:'disconnected'}; + }; + return { async effect(action) { + if (action.kind === 'disconnect') return disconnect(); + if (action.kind === 'status') { + const permission = await api('internet'); + if (permission.status !== 'granted' && provider) await disconnect(); + return {status:provider?.connected && provider.session?.expiry > Date.now()/1000 + && provider.signer?.client.core.relayer.connected ? 'connected':'disconnected',revision:generation}; + } + await connect(); + const revision = generation; + const signer = await address(), namespace = await chain(); + if (action.kind === 'link') { + const challenge = await api('/api/auth/evm/challenge',{method:'POST',body:JSON.stringify({address:signer,chain_id:Number(namespace.split(':')[1])})}); + const check = async () => { + if (!same(await address(),signer) || await chain() !== namespace || generation !== revision + || !Number.isSafeInteger(challenge.expires_at) || challenge.expires_at <= Date.now()/1000) throw new Error('Wallet changed or the challenge expired. Connect again.'); + }; + await check(); + const signature = await provider.request({method:'personal_sign',params:[signData(challenge.message),signer]}); + await check(); + await api('/api/auth/evm/verify',{method:'POST',body:JSON.stringify({message:challenge.message,signature})}); + return {status:'linked'}; + } + if (action.kind !== 'approve') throw new Error('Unsupported wallet request.'); + const path = `wallet/approvals/${encodeURIComponent(action.approvalRequestId)}`; + const requests = (await api('wallet/approvals')).approval_requests || []; + const review = requests.find(r=>r.request_id === action.approvalRequestId); + if (!review || review.status !== 'pending' || !same(review.address,signer) || review.chain_namespace !== namespace) throw new Error('Select the requested account and network in your phone wallet, then review again.'); + const ttl = review.expires_at - Math.ceil(Date.now()/1000); + if (!Number.isSafeInteger(review.expires_at) || ttl <= 0 || review.intent === 'transaction_intent' && ttl < 300) throw new Error('Wallet request expires soon. Request a fresh review.'); + const {handoff,binding} = await api(`${path}/approve`,{method:'POST',body:'{}'}); + if (!handoff || !binding || handoff.request_id !== action.approvalRequestId + || handoff.payload_hash !== binding.payload_hash || !same(handoff.signer,signer) + || binding.chain_namespace !== namespace || !/^0x[0-9a-fA-F]{64}$/.test(handoff.payload_hash || '')) throw new Error('Runtime returned an invalid wallet binding.'); + const check = async () => { + if (!same(await address(),signer) || await chain() !== namespace || generation !== revision + || !Number.isSafeInteger(binding.expires_at) || binding.expires_at <= Date.now()/1000) throw new Error('Wallet request changed or expired. Request a new review.'); + return Math.min(600,Math.max(binding.expires_at-Math.ceil(Date.now()/1000),300)); + }; + const expiry = await check(); + if (handoff.intent === 'transaction_intent') { + const transaction = handoff.transaction; + if (!transaction || !same(transaction.from,signer) || `eip155:${Number.parseInt(transaction.chainId,16)}` !== namespace) throw new Error('Runtime returned an invalid transaction.'); + const hash = await provider.request({method:'eth_sendTransaction',params:[transaction]},expiry); + if (typeof hash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(hash)) throw new Error('Wallet returned an invalid transaction hash. The wallet may have sent it. Check your wallet before sending again.'); + // A returned hash is retained even if the account, network or expiry changed while sending. + try { await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,transaction_hash:hash})}); } + catch { throw new Error(`Wallet returned transaction hash ${hash}. Runtime could not confirm it. Keep this hash and check it before sending again.`); } + return {status:'completed',effect:'transaction'}; + } + if (handoff.signature_type !== 'personal_sign' || typeof handoff.message !== 'string') throw new Error('Runtime returned an invalid signature request.'); + const signature = await provider.request({method:'personal_sign',params:[signData(handoff.message),signer]},expiry); + await check(); + await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,signature,signature_type:'personal_sign'})}); + return {status:'completed',effect:'signature'}; + }}; +} diff --git a/scripts/browser-internet-consent.test.mjs b/scripts/browser-internet-consent.test.mjs index 497638ce5..c1920b223 100644 --- a/scripts/browser-internet-consent.test.mjs +++ b/scripts/browser-internet-consent.test.mjs @@ -415,6 +415,7 @@ test("WalletConnect Inbox keeps requests pending, uses passkey consent and separ await frame.getByRole("button",{name:"Turn Off",exact:true}).waitFor(); assert.equal(await frame.locator("#pending-count").innerText(),"0"); assert.deepEqual(await page.evaluate(()=>approvals),["walletconnect.internet.grant"]); + await page.waitForFunction(()=>messages.some(m=>m.type==='home:open-target' && m.target==='wallet-walletconnect' && Object.keys(m.query).length===0)); await frame.getByRole("button",{name:"Turn Off",exact:true}).click(); await frame.getByRole("button",{name:"Turn Off",exact:true}).waitFor({state:"hidden"}); assert.deepEqual(await page.evaluate(()=>approvals),["walletconnect.internet.grant","walletconnect.internet.revoke"]); diff --git a/scripts/lib/walletconnect-capsule-fixture.mjs b/scripts/lib/walletconnect-capsule-fixture.mjs new file mode 100644 index 000000000..a179f7dcb --- /dev/null +++ b/scripts/lib/walletconnect-capsule-fixture.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { createWalletConnectClient } from '../../capsules/wallet-walletconnect/browser/walletconnect-client.mjs'; +export const address = `0x${'12'.repeat(20)}`, payloadHash=`0x${'34'.repeat(32)}`, transactionHash=`0x${'56'.repeat(32)}`; +export async function exerciseWalletConnect(scenario='valid') { + const clock=Date.now, calls=[],routes=[],events=new Map(); let changed=false, memoryCleared=false; + const signatureIntent=scenario.startsWith('signature-'); + const kind=scenario.replace(/^signature-/,''); + const lifetime=scenario==='signature-short'?180:scenario==='long-request'?1800:600; + const signature=`0x${'ab'.repeat(65)}`; + const message=scenario==='link-uppercase-hex'?'0X4142':scenario==='link-odd-hex'?'0x123':'Runtime ownership proof · fixture'; + const change=()=>{changed=true;if(kind==='account-change-during-send')events.get('accountsChanged')?.([]); + if(kind==='chain-change-during-send')events.get('chainChanged')?.('0x1');if(kind==='expired-during-send')Date.now=()=>clock()+601000;}; + const provider={connected:true,session:{expiry:clock()/1000+3600},signer:{client:{core:{relayer:{connected:true}}}}, + on:(name,fn)=>events.set(name,fn),async request(input,expiry){calls.push({...input,expiry}); + if(input.method==='eth_accounts')return [scenario==='wrong-account'||changed&&kind==='account-change-during-send'?`0x${'ab'.repeat(20)}`:address]; + if(input.method==='eth_chainId')return scenario==='wrong-chain'||changed&&kind==='chain-change-during-send'?'0x1':'0x14'; + if(input.method==='personal_sign'){if(signatureIntent)change();return signature;} + if(input.method==='eth_sendTransaction'){change();return scenario==='invalid-hash'?'Open a fake recovery website':transactionHash;} + throw new Error('Unexpected wallet call'); + }}; + const api=async(path,input)=>{routes.push({path,input}); + if(path==='wallet/config')return {walletconnect:{project_id:'fixture-project'}}; + if(path==='internet')return {status:'granted'}; + if(path==='storage')return {}; + if(path.endsWith('/challenge'))return {schema:'elastos.auth.challenge/v1',message,expires_at:Math.floor(clock()/1000)+600}; + if(path.endsWith('/verify')){const body=JSON.parse(input.body);assert.equal(body.message,message);assert.equal(body.signature,signature);return {status:'linked'};} + if(path==='wallet/approvals')return {approval_requests:[{request_id:'approval:fixture',status:scenario==='approved'?'approved':'pending',address, + intent:signatureIntent?'browser_personal_sign':'transaction_intent',chain_namespace:'eip155:20',expires_at:Math.floor(clock()/1000)+lifetime}]}; + if(path.endsWith('/approve'))return {handoff:{request_id:'approval:fixture',intent:signatureIntent?'browser_personal_sign':'transaction_intent', + payload_hash:payloadHash,signer:address,signature_type:'personal_sign',message:'Runtime approval fixture', + transaction:{from:address,to:`0x${'78'.repeat(20)}`,value:'0x1',data:'0x',gas:'0x5208',gasPrice:'0x1',nonce:'0x1',chainId:'0x14'}}, + binding:{principal_id:'fixture',requested_by_actor:'documents',account_id:'fixture-account',chain_namespace:'eip155:20',payload_hash:payloadHash, + expires_at:scenario==='expired'?1:Math.floor(clock()/1000)+lifetime}}; + if(path.endsWith('/complete')){const body=JSON.parse(input.body);assert.equal(body.payload_hash,payloadHash);assert.equal(body.signer,address); + if(scenario==='completion-refused')throw new Error('Completion refused');return {};} + throw new Error('Unexpected Runtime resource'); + }; + const client=createWalletConnectClient({api,origin:'http://localhost:61180',clearMemory:()=>{memoryCleared=true;}, + loadAdapter:async()=>({connectWalletConnectEvm:async options=>{assert.equal(options.contextKey,'wallet-walletconnect');return provider;},disconnectWalletConnectEvm:async()=>{}})}); + try {return {result:await client.effect({kind:scenario.startsWith('link')?'link':scenario==='disconnect'?'disconnect':'approve',approvalRequestId:'approval:fixture'}),calls,routes,memoryCleared};} + catch(error){return {error:error.message,calls,routes,memoryCleared};} + finally{Date.now=clock;} +} diff --git a/scripts/lib/walletconnect-connector-loader.mjs b/scripts/lib/walletconnect-connector-loader.mjs deleted file mode 100644 index 5de26ebef..000000000 --- a/scripts/lib/walletconnect-connector-loader.mjs +++ /dev/null @@ -1,7 +0,0 @@ -// Resolve the capsule's served asset import while importing its whole real module. -export function resolve(specifier, context, next) { - if (specifier.startsWith("/apps/home/home-clipboard-client.js?")) { - return next(new URL("../../capsules/home/browser/home-clipboard-client.js", import.meta.url).href, context); - } - return next(specifier, context); -} diff --git a/scripts/lib/walletconnect-sdk-fixture.mjs b/scripts/lib/walletconnect-sdk-fixture.mjs deleted file mode 100644 index ee0443fc3..000000000 --- a/scripts/lib/walletconnect-sdk-fixture.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export async function connectWalletConnectEvm(options) { - if (new URL(options.runtimeUrl).origin !== globalThis.location.origin) throw new Error("SDK RPC URLs require the Home origin"); - globalThis.__wcFixtureOptions = options; - return globalThis.__wcFixtureProvider; -} diff --git a/scripts/test-source-gate.sh b/scripts/test-source-gate.sh index 86aedf932..89942cffa 100755 --- a/scripts/test-source-gate.sh +++ b/scripts/test-source-gate.sh @@ -33,6 +33,7 @@ product_ui() { node scripts/home-shell-recovery-smoke.mjs node scripts/home-agent-shell-smoke.mjs node scripts/people-discovery-smoke.mjs + node --test scripts/walletconnect-capsule.test.mjs node scripts/home-clipboard-source-gate.mjs node --test scripts/home-clipboard-source-gate.test.mjs node scripts/public-copy-entropy-check.mjs diff --git a/scripts/wallet-connector-transaction-smoke.mjs b/scripts/wallet-connector-transaction-smoke.mjs index 1cc87454c..462bf8d9d 100755 --- a/scripts/wallet-connector-transaction-smoke.mjs +++ b/scripts/wallet-connector-transaction-smoke.mjs @@ -450,9 +450,16 @@ async function runHostedConnectorSmoke(connectorId = "wallet-metamask") { }; } +async function runWalletConnectSmoke() { + const {exerciseWalletConnect} = await import('./lib/walletconnect-capsule-fixture.mjs'); + const result = await exerciseWalletConnect(); + if (result.error) throw new Error(result.error); + return {connectorId:'wallet-walletconnect',effectOwner:'capsule',result:result.result}; +} + const results = [ await runHostedConnectorSmoke(), - await runHostedConnectorSmoke("wallet-walletconnect"), + await runWalletConnectSmoke(), ]; console.log(JSON.stringify({ ok: true, results }, null, 2)); diff --git a/scripts/wallet-connectors-uiux-layout-smoke.mjs b/scripts/wallet-connectors-uiux-layout-smoke.mjs index d1785fbf5..e4ba16387 100644 --- a/scripts/wallet-connectors-uiux-layout-smoke.mjs +++ b/scripts/wallet-connectors-uiux-layout-smoke.mjs @@ -79,7 +79,7 @@ const connectors = Object.freeze([ { id: "wallet-walletconnect", title: "WalletConnect", - lockedStatus: "Open from Wallet to add an approval method.", + lockedStatus: "Open from Wallet to review approval requests.", token: "wallet-walletconnect-layout-token", accountSummary: { accounts: [ @@ -139,6 +139,7 @@ function contentType(path) { ".css": "text/css; charset=utf-8", ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2", @@ -166,7 +167,7 @@ function staticPath(pathname) { } function fixtureHtml(baseUrl, connector, mode) { - const hasToken = mode === "verified"; + const hasToken = mode !== "locked"; const query = new URLSearchParams({ home_origin: baseUrl }); const src = `${baseUrl}/apps/${connector.id}/?${query.toString()}${ hasToken ? `#home_token=${encodeURIComponent(connector.token)}` : "" @@ -227,6 +228,7 @@ function fixtureHtml(baseUrl, connector, mode) { } function startServer() { + let recovery = false; const traces = new Map(); for (const connector of connectors) { traces.set(connector.id, { @@ -256,7 +258,8 @@ function startServer() { const connector = connectors.find((entry) => entry.id === url.searchParams.get("connector")); const mode = url.searchParams.get("mode"); assert(connector, "unknown connector fixture"); - assert(mode === "locked" || mode === "verified", "unknown connector mode"); + assert(["locked","verified","recovery"].includes(mode), "unknown connector mode"); + recovery = mode === 'recovery'; const body = Buffer.from(fixtureHtml(baseUrl(server), connector, mode)); response.writeHead(200, { "cache-control": "no-store", @@ -290,7 +293,9 @@ function startServer() { json(response, 401, { error: "invalid token" }); return; } - json(response, 200, matchedConnector.requestSummary); + const summary = structuredClone(matchedConnector.requestSummary); + if (recovery) summary.approval_requests[0].status = 'approved'; + json(response, 200, summary); return; } const asset = staticPath(url.pathname); @@ -523,6 +528,17 @@ async function run() { assert(consoleErrors.length === 0, `${connector.title} page had console errors`, consoleErrors); assert(requestFailures.length === 0, `${connector.title} page had request failures`, requestFailures); await page.close(); + if (connector.id === 'wallet-walletconnect') { + for (const width of [1280,390]) { + const recoveryPage = await browser.newPage({viewport:{width,height:900}}); + await recoveryPage.goto(`${server.baseUrl}/fixture?connector=${connector.id}&mode=recovery`); + const recoveryFrame = await waitForConnectorFrame(recoveryPage); + await recoveryFrame.getByText('Check your phone wallet.',{exact:false}).waitFor(); + assert.equal(await recoveryFrame.locator('[data-wallet-request-sign]').count(),0,'unfinished transaction offers recovery without another send'); + screenshots.push(await saveScreenshot(recoveryPage,`walletconnect-recovery-${width}.png`)); + await recoveryPage.close(); + } + } } } finally { await browser.close(); diff --git a/scripts/walletconnect-capsule.test.mjs b/scripts/walletconnect-capsule.test.mjs new file mode 100644 index 000000000..b084591c5 --- /dev/null +++ b/scripts/walletconnect-capsule.test.mjs @@ -0,0 +1,20 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync,readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { exerciseWalletConnect,transactionHash } from './lib/walletconnect-capsule-fixture.mjs'; +const sent = r=>r.calls.filter(c=>c.method==='eth_sendTransaction'); +const completed = r=>r.routes.filter(c=>c.path.endsWith('/complete')); +test('opaque capsule sends the exact Runtime transaction once',async()=>{const r=await exerciseWalletConnect();assert.equal(r.error,undefined);assert.equal(sent(r).length,1);assert.equal(completed(r).length,1);}); +for(const scenario of ['wrong-account','wrong-chain','expired','approved'])test(`capsule refuses ${scenario} before sending`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(typeof r.error,'string');assert.equal(sent(r).length,0);assert.equal(completed(r).length,0);}); +for(const scenario of ['account-change-during-send','chain-change-during-send','expired-during-send'])test(`capsule preserves the returned hash after ${scenario}`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(r.error,undefined);assert.equal(completed(r).length,1);assert.equal(JSON.parse(completed(r)[0].input.body).transaction_hash,transactionHash);}); +test('completion refusal retains the returned transaction hash',async()=>{const r=await exerciseWalletConnect('completion-refused');assert.ok(r.error.includes(transactionHash));assert.match(r.error,/check it before sending again/);}); +test('wallet chosen text is refused as a transaction hash',async()=>{const r=await exerciseWalletConnect('invalid-hash');assert.match(r.error,/invalid transaction hash/);assert.doesNotMatch(r.error,/fake recovery website/);assert.equal(completed(r).length,0);}); +for(const change of ['account-change-during-send','chain-change-during-send','expired-during-send'])test(`unused signature stops after ${change}`,async()=>{const r=await exerciseWalletConnect(`signature-${change}`);assert.equal(typeof r.error,'string');assert.equal(completed(r).length,0);}); +for(const [scenario,expiry] of [['signature-short',300],['long-request',600]])test(`capsule bounds the SDK timeout for ${scenario}`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(r.error,undefined);assert.equal(r.calls.find(c=>['personal_sign','eth_sendTransaction'].includes(c.method)).expiry,expiry);}); +for(const [scenario,data] of [['link','0x52756e74696d65206f776e6572736869702070726f6f6620c2b72066697874757265'],['link-uppercase-hex','0x4142'],['link-odd-hex','0x3078313233']])test(`capsule signs the exact ownership DATA for ${scenario}`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(r.error,undefined);assert.equal(r.calls.find(c=>c.method==='personal_sign').params[0],data);}); +test('disconnect clears Runtime storage and memory while retaining linked accounts',async()=>{const r=await exerciseWalletConnect('disconnect');assert.equal(r.result.status,'disconnected');assert.equal(r.memoryCleared,true);assert.ok(r.routes.some(c=>c.path==='storage'&&c.input.method==='DELETE'));assert.ok(!r.routes.some(c=>c.path.includes('accounts')));}); +test('Home capsules contain no WalletConnect SDK import or signer',()=>{ + const scan=path=>{for(const e of readdirSync(path,{withFileTypes:true})){const p=join(path,e.name);if(e.isDirectory())scan(p);else if(/\.[cm]?js$/.test(e.name))assert.doesNotMatch(readFileSync(p,'utf8'),/connectWalletConnectEvm|@walletconnect\/|import\s*\([^)]*reown-appkit/);}}; + for(const e of readdirSync('capsules',{withFileTypes:true}))if(e.isDirectory()&&e.name.startsWith('home'))scan(join('capsules',e.name)); +}); diff --git a/scripts/walletconnect-connector-deadlines.test.mjs b/scripts/walletconnect-connector-deadlines.test.mjs deleted file mode 100644 index 1d37651f2..000000000 --- a/scripts/walletconnect-connector-deadlines.test.mjs +++ /dev/null @@ -1,72 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { register } from "node:module"; -register(new URL("./lib/walletconnect-connector-loader.mjs", import.meta.url)); - -class Element { - children = []; dataset = {}; listeners = new Map(); textContent = ""; - addEventListener(type, fn) { this.listeners.set(type, fn); } - append(...children) { this.children.push(...children); } - replaceChildren(...children) { this.children = children; } - closest() { return this; } -} -let sequence = 0; -const tick = () => new Promise(resolve => setImmediate(resolve)); -const transactionHash = `0x${"ab".repeat(32)}`; - -async function fixture(kind) { - const origin = "http://localhost:61183"; - const nodes = new Map(["wallet-connect", "wallet-disconnect", "wallet-connection", "wallet-status", "wallet-state", "wallet-accounts", "wallet-requests"].map(id => [`#${id}`, new Element()])); - globalThis.document = { querySelector: selector => nodes.get(selector), createElement: () => new Element() }; - const events = new Map(); const timers = new Map(); let now = 0, timerId = 0, effect; - const home = { postMessage(message) { if (message.type === "home:wallet-connector-effect") effect = message; } }; - globalThis.window = { - location: { search: `?home_origin=${encodeURIComponent(origin)}`, hash: "#home_token=deadline-fixture", origin: "null" }, - top: home, parent: home, crypto: { randomUUID: () => `deadline-${++sequence}` }, - addEventListener(type, callback) { if (!events.has(type)) events.set(type, new Set()); events.get(type).add(callback); }, - removeEventListener(type, callback) { events.get(type)?.delete(callback); }, - setTimeout(fn, ms) { timers.set(++timerId, { fn, at: now + ms }); return timerId; }, - clearTimeout(id) { timers.delete(id); }, - }; - globalThis.fetch = async path => ({ ok: true, json: async () => path.endsWith("/accounts") ? { accounts: [] } : { approval_requests: [{ - request_id: "approval:deadline", status: "pending", intent: "transaction_intent", capsule_id: "documents", chain_namespace: "eip155:20", - proof_type: "siwe", connector_id: "wallet-walletconnect", address: `0x${"12".repeat(20)}`, - }] } }); - await import(`../capsules/wallet-walletconnect/browser/wallet-walletconnect.js?deadline=${++sequence}`); - await tick(); - const root = nodes.get("#wallet-requests"); - const button = root.children[0].children.at(-1); - const pending = kind === "link" ? nodes.get("#wallet-connect").listeners.get("click")() - : root.listeners.get("click")({ target: button }); - assert.equal(effect.action.kind, kind); - return { - async advance(ms) { - now += ms; - for (const [id, timer] of [...timers]) if (timer.at <= now) { timers.delete(id); timer.fn(); } - await tick(); - }, - async reply() { - const data = { type: "home:wallet-connector-effect-result", schema: "elastos.home.wallet-connector-effect-result/v1", - requestId: effect.requestId, connectorId: "wallet-walletconnect", - ...(kind === "link" ? { result: { status: "linked" } } : { error: `Wallet returned transaction hash ${transactionHash}. Keep this hash and check it before sending again.` }), - }; - for (const fn of [...events.get("message")]) fn({ source: home, origin, data }); - await pending; - }, - pending, status: nodes.get("#wallet-status"), - }; -} - -for (const kind of ["approve", "link"]) { - test(`WalletConnect ${kind} still receives its Home reply after 180 seconds`, async () => { - const f = await fixture(kind); - await f.advance(181000); - await f.reply(); - assert.ok(kind === "link" ? f.status.textContent === "Approval method added." : f.status.textContent.includes(transactionHash), f.status.textContent); - }); -} -test("an unresponsive Home effect has a bounded screen deadline", async () => { - const f = await fixture("approve"); - await f.advance(811000); await f.pending; - assert.equal(f.status.textContent, "Wallet request timed out."); -}); diff --git a/scripts/walletconnect-home-host.test.mjs b/scripts/walletconnect-home-host.test.mjs deleted file mode 100644 index b19ef838c..000000000 --- a/scripts/walletconnect-home-host.test.mjs +++ /dev/null @@ -1,191 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { pathToFileURL } from "node:url"; -import { resolve } from "node:path"; - -const address = `0x${"12".repeat(20)}`; -const payloadHash = `0x${"34".repeat(32)}`; -const signature = `0x${"ab".repeat(65)}`; -const linkMessage = "Runtime ownership proof · fixture"; -const linkMessages = { "link-uppercase-hex": "0X4142", "link-odd-hex": "0x123" }; -const transactionHash = `0x${"56".repeat(32)}`; -const origin = "http://localhost:61180"; -const connector = "wallet-walletconnect"; - -async function fixture(scenario) { - const signatureIntent = scenario.startsWith("signature-"); - const lifetime = scenario === "signature-short" ? 180 : scenario === "long-request" ? 1800 : 600; - const clock = Date.now; - const events = new Map(); - let changed = false; - const changeKind = scenario.replace(/^signature-/, ""); - const changeDuringReply = () => { - changed = true; - if (changeKind === "account-change-during-send") events.get("accountsChanged")?.([]); - if (changeKind === "chain-change-during-send") events.get("chainChanged")?.("0x1"); - if (changeKind === "expired-during-send") Date.now = () => clock() + 601000; - }; - globalThis.document = { querySelector() { return null; } }; - globalThis.location = { origin }; - globalThis.window = { addEventListener() {}, dispatchEvent() {} }; - const { setHomeAuthorityToken } = await import("../capsules/home/browser/shell-core.js?v=home-wallpaper-20261030b"); - setHomeAuthorityToken("home-authority-fixture"); - const host = await import(`../capsules/home/browser/home-wallet-connector-host.js?fixture=${scenario}`); - const calls = []; - globalThis.__wcFixtureProvider = { - connected: true, on(name, callback) { events.set(name, callback); }, - async request(input, expiry) { - calls.push({ ...input, expiry }); - if (input.method === "eth_requestAccounts") return [address]; - if (input.method === "personal_sign") { - if (scenario.startsWith("signature-")) changeDuringReply(); - return signature; - } - if (input.method === "eth_accounts") return [scenario === "wrong-account" || changed && changeKind === "account-change-during-send" ? `0x${"ab".repeat(20)}` : address]; - if (input.method === "eth_chainId") return scenario === "wrong-chain" || changed && changeKind === "chain-change-during-send" ? "0x1" : "0x14"; - if (input.method === "eth_sendTransaction") { - changeDuringReply(); - return scenario === "invalid-hash" ? "Open the wallet's fake recovery website" : transactionHash; - } - throw new Error(`Unexpected wallet call: ${input.method}`); - }, - }; - const routes = []; - globalThis.fetch = async (path, input) => { - routes.push(path); - assert.equal(input.headers["x-elastos-home-token"], "home-authority-fixture"); - let value; - if (path.endsWith("host-config")) value = { - projectId: "fixture-project", principal_id: "principal-fixture", internet: { status: "granted" }, - sdk_asset_path: pathToFileURL(resolve("scripts/lib/walletconnect-sdk-fixture.mjs")).href, - }; - else if (path.endsWith("/evm/link/challenge")) value = { - schema: "elastos.home.wallet-connector.effect.result/v1", action: "evm_link_challenge", connector_id: connector, - challenge: { schema: "elastos.auth.challenge/v1", challenge_id: "challenge:fixture", message: linkMessages[scenario] || linkMessage, expires_at: Math.floor(Date.now() / 1000) + 600, resources: [] }, - }; - else if (path.endsWith("/evm/link/verify")) { - const body = JSON.parse(input.body); - assert.equal(body.message, linkMessages[scenario] || linkMessage); assert.equal(body.signature, signature); - value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "evm_link_complete", connector_id: connector, status: "linked" }; - } - else if (path.endsWith("/review")) value = { address, intent: signatureIntent ? "browser_personal_sign" : "transaction_intent", chain_namespace: "eip155:20", expires_at: Math.floor(Date.now() / 1000) + lifetime }; - else if (path.endsWith("/handoff")) { - value = { - schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_handoff", - connector_id: connector, request_id: "approval:fixture", evm_chains: [], - handoff: { schema: "elastos.wallet.webconnect_handoff/v1", request_id: "approval:fixture", intent: "transaction_intent", - payload_hash: payloadHash, signer: address, status: "awaiting_wallet_transaction", - transaction: { from: address, to: `0x${"78".repeat(20)}`, value: "0x1", data: "0x", gas: "0x5208", gasPrice: "0x1", nonce: "0x1", chainId: "0x14" }, - }, - binding: { principal_id: "principal-fixture", requested_by_actor: "documents", account_id: "account-fixture", chain_namespace: "eip155:20", - payload_hash: payloadHash, expires_at: scenario === "expired" ? 1 : Math.floor(Date.now() / 1000) + lifetime }, - }; - if (scenario.startsWith("signature-")) { - delete value.handoff.transaction; - Object.assign(value.handoff, { intent: "browser_personal_sign", status: "awaiting_wallet_signature", message: "Runtime approval fixture", signature_type: "personal_sign" }); - } - } - else if (path.endsWith("/complete")) { - const body = JSON.parse(input.body); - assert.equal(body.payload_hash, payloadHash); - assert.equal(body.signer, address); - if (signatureIntent) assert.equal(body.signature, signature); - else assert.equal(body.transaction_hash, transactionHash); - if (scenario === "completion-refused") return { ok: false, status: 403, text: async () => "wallet approval request expired" }; - value = { schema: "elastos.home.wallet-connector.effect.result/v1", action: "approval_complete", connector_id: connector, - request_id: "approval:fixture", status: "completed" }; - } else throw new Error(`Unexpected Runtime route: ${path}`); - return { ok: true, json: async () => value }; - }; - let reply; - const complete = new Promise(resolveReply => { reply = resolveReply; }); - const context = { kind: "app-frame", targetId: connector, homeToken: "connector-fixture", walletEffectState: { inFlight: false, requestIds: new Set() } }; - const data = { type: host.WALLET_CONNECTOR_EFFECT_TYPE, schema: host.WALLET_CONNECTOR_EFFECT_SCHEMA, - requestId: "request:fixture", connectorId: scenario === "wrong-capsule" ? "wallet-metamask" : connector, - connectorToken: "connector-fixture", action: scenario.startsWith("link") ? { kind: "link" } : { kind: "approve", approvalRequestId: "approval:fixture" } }; - if (scenario === "injected-payload") data.action.payload = { to: "attacker" }; - try { - assert.equal(host.handleHomeWalletConnectorEffect({ source: { postMessage: reply } }, context, data), true); - return { response: await complete, calls, routes }; - } finally { Date.now = clock; } -} - -test("trusted Home signs the exact Runtime transaction once", async () => { - const result = await fixture("valid"); - assert.equal(result.response.error, undefined, result.response.error); - assert.equal(result.calls.filter(c => c.method === "eth_sendTransaction").length, 1); - assert.ok(result.calls.find(c => c.method === "eth_sendTransaction").expiry >= 300); - assert.ok(result.calls.find(c => c.method === "eth_sendTransaction").expiry <= 600); - assert.equal(result.calls.find(c => c.method === "eth_sendTransaction").params[0].to, `0x${"78".repeat(20)}`); -}); -for (const scenario of ["wrong-account", "wrong-chain", "wrong-capsule", "expired", "injected-payload"]) { - test(`trusted Home refuses ${scenario} before a signing effect`, async () => { - const result = await fixture(scenario); - assert.equal(typeof result.response.error, "string"); - assert.equal(result.calls.filter(c => c.method === "eth_sendTransaction").length, 0); - assert.equal(result.routes.filter(p => p.endsWith("/complete")).length, 0); - }); -} - -for (const scenario of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { - test(`trusted Home preserves a returned transaction hash after ${scenario}`, async () => { - const result = await fixture(scenario); - assert.equal(result.response.error, undefined, result.response.error); - assert.equal(result.calls.filter(call => call.method === "eth_sendTransaction").length, 1); - assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); - }); -} - -test("a refused transaction completion retains its hash and asks for checking before another send", async () => { - const result = await fixture("completion-refused"); - assert.ok(result.response.error.includes(transactionHash)); - assert.match(result.response.error, /Keep this hash and check it before sending again/); - assert.doesNotMatch(result.response.error, /new review/); - assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); -}); - -test("wallet-chosen text cannot appear as a returned transaction hash", async () => { - const result = await fixture("invalid-hash"); - assert.match(result.response.error, /invalid transaction hash/); - assert.match(result.response.error, /Check your wallet before sending again/); - assert.doesNotMatch(result.response.error, /fake recovery website/); - assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 0); -}); - -test("a 180-second Runtime signature keeps its expiry with a 300-second SDK timeout", async () => { - const result = await fixture("signature-short"); - assert.equal(result.response.error, undefined, result.response.error); - assert.equal(result.calls.find(call => call.method === "personal_sign").expiry, 300); - assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 1); -}); - -test("a longer Runtime request caps its SDK timeout at 600 seconds", async () => { - const result = await fixture("long-request"); - assert.equal(result.response.error, undefined, result.response.error); - assert.equal(result.calls.find(call => call.method === "eth_sendTransaction").expiry, 600); -}); - -for (const change of ["account-change-during-send", "chain-change-during-send", "expired-during-send"]) { - test(`trusted Home stops an unused signature after ${change}`, async () => { - const result = await fixture(`signature-${change}`); - assert.equal(typeof result.response.error, "string"); - assert.equal(result.calls.filter(call => call.method === "personal_sign").length, 1); - assert.equal(result.routes.filter(path => path.endsWith("/complete")).length, 0); - }); -} - -test("WalletConnect signs the exact UTF-8 ownership proof as EIP-1193 DATA", async () => { - const result = await fixture("link"); - assert.equal(result.response.error, undefined, result.response.error); - assert.equal(result.response.result.status, "linked"); - assert.deepEqual(result.calls.find(c => c.method === "personal_sign").params, - ["0x" + Buffer.from(linkMessage, "utf8").toString("hex"), address]); -}); - -for (const [scenario, expected] of [["link-uppercase-hex", "0x4142"], ["link-odd-hex", "0x3078313233"]]) { - test(`WalletConnect personal_sign matches wallet-provider bytes for ${scenario}`, async () => { - const result = await fixture(scenario); - assert.equal(result.response.error, undefined, result.response.error); - assert.equal(result.calls.find(c => c.method === "personal_sign").params[0], expected); - }); -} From 4c6a449abc87a2e66bc84e5ea75f9c3ce484b42a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:27:43 -0500 Subject: [PATCH 054/139] fix(walletconnect): retire Home authority and clear revoked capsule sessions --- .../src/api/browser_capsules.rs | 6 +- .../crates/elastos-server/src/api/gateway.rs | 13 +- .../src/api/gateway_home_wallet_connector.rs | 120 +++--------------- .../src/api/gateway_tests/content_sandbox.rs | 2 +- .../api/gateway_tests/wallet/connectors.rs | 97 ++++++++++++++ .../api/gateway_tests/wallet/walletconnect.rs | 106 ++++++++++++++-- .../src/api/gateway_wallet_accounts.rs | 24 +++- .../src/api/gateway_wallet_connectors.rs | 15 ++- .../src/api/gateway_walletconnect.rs | 108 +++++++++++++--- elastos/crates/elastos-server/src/auth.rs | 37 ++++++ 10 files changed, 377 insertions(+), 151 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/browser_capsules.rs b/elastos/crates/elastos-server/src/api/browser_capsules.rs index 90168fe91..50fd22d2a 100644 --- a/elastos/crates/elastos-server/src/api/browser_capsules.rs +++ b/elastos/crates/elastos-server/src/api/browser_capsules.rs @@ -406,7 +406,11 @@ fn shell_content_security_policy( format!("{home_source} 'unsafe-inline'"), ) }; - let connect_source = format!("{default_source} {}", home_websocket_origin(&home_source)?); + let connect_source = if is_home_host { + default_source.clone() + } else { + format!("{default_source} {}", home_websocket_origin(&home_source)?) + }; // No allow-popups: a new window escapes connect-src and frame-src. Home // opens web links for its apps (`home:open-external`). let sandbox = if is_home_host { diff --git a/elastos/crates/elastos-server/src/api/gateway.rs b/elastos/crates/elastos-server/src/api/gateway.rs index 5cd1dd85e..d93e519c4 100644 --- a/elastos/crates/elastos-server/src/api/gateway.rs +++ b/elastos/crates/elastos-server/src/api/gateway.rs @@ -128,6 +128,7 @@ use gateway_home_external_link::*; pub(crate) use gateway_home_runtime::is_wallet_connector_capsule_id; use gateway_home_runtime::*; use gateway_home_shared_content::*; +pub(crate) use gateway_walletconnect::clear_principal_storage as clear_walletconnect_principal_storage; pub(crate) fn principal_root_protected_object_inventory( localhost_root: &str, @@ -870,7 +871,9 @@ fn gateway_router_with_api_url(state: GatewayState, gateway_api_url: String) -> ) .route( "/api/apps/wallet-walletconnect/storage", - get(gateway_walletconnect::storage).post(gateway_walletconnect::storage), + get(gateway_walletconnect::storage) + .post(gateway_walletconnect::storage) + .delete(gateway_walletconnect::storage), ) .route( "/api/apps/wallet-walletconnect/relay", @@ -880,10 +883,6 @@ fn gateway_router_with_api_url(state: GatewayState, gateway_api_url: String) -> "/api/apps/wallet-walletconnect/relay-admission", post(gateway_walletconnect::admission), ) - .route( - "/api/apps/wallet-walletconnect/host-config", - get(gateway_walletconnect::host_config).post(gateway_walletconnect::host_config), - ) .route("/api/wallet/qr", post(wallet_receive_qr)) .route( "/api/apps/wallet/wallet/managed", @@ -1042,10 +1041,6 @@ fn gateway_router_with_api_url(state: GatewayState, gateway_api_url: String) -> "/api/apps/home/wallet-connector/bitcoin/link/verify", post(home_wallet_connector_bitcoin_link_verify), ) - .route( - "/api/apps/home/wallet-connector/approvals/:request_id/review", - post(home_wallet_connector_approval_review), - ) .route( "/api/apps/home/wallet-connector/approvals/:request_id/handoff", post(home_wallet_connector_approval_handoff), diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index fd7728949..d4940567a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -5,7 +5,7 @@ use serde_json::json; const HOME_WALLET_CONNECTOR_REQUEST_SCHEMA: &str = "elastos.home.wallet-connector.effect.request/v1"; const HOME_WALLET_CONNECTOR_RESULT_SCHEMA: &str = "elastos.home.wallet-connector.effect.result/v1"; -const HOSTED_WALLET_CONNECTOR_IDS: &[&str] = +const INJECTED_WALLET_CONNECTOR_IDS: &[&str] = &[WALLET_METAMASK_CAPSULE_ID, WALLET_UNISAT_CAPSULE_ID]; #[derive(Debug, Deserialize)] @@ -109,9 +109,9 @@ struct HomeWalletConnectorTransaction { chain_id: String, } -pub(super) struct HomeWalletConnectorAuthority { - pub(super) context: HomeLaunchTokenContext, - pub(super) wallet: RuntimeWalletAuthority, +struct HomeWalletConnectorAuthority { + context: HomeLaunchTokenContext, + wallet: RuntimeWalletAuthority, } pub(super) async fn home_wallet_connector_evm_link_challenge( @@ -125,11 +125,7 @@ pub(super) async fn home_wallet_connector_evm_link_challenge( &input.schema, &input.connector_id, &input.connector_token, - if input.connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { - WALLET_WALLETCONNECT_CAPSULE_ID - } else { - WALLET_METAMASK_CAPSULE_ID - }, + WALLET_METAMASK_CAPSULE_ID, ) { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), @@ -175,11 +171,7 @@ pub(super) async fn home_wallet_connector_evm_link_verify( &input.schema, &input.connector_id, &input.connector_token, - if input.connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { - WALLET_WALLETCONNECT_CAPSULE_ID - } else { - WALLET_METAMASK_CAPSULE_ID - }, + WALLET_METAMASK_CAPSULE_ID, ) { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), @@ -306,39 +298,6 @@ pub(super) async fn home_wallet_connector_bitcoin_link_verify( } } -pub(super) async fn home_wallet_connector_approval_review( - State(state): State, - headers: HeaderMap, - Path(request_id): Path, - Json(input): Json, -) -> Response { - let result = async { - validate_home_wallet_connector_request_id(&request_id)?; - let authority = require_home_wallet_connector_authority( - &state, - &headers, - &input.schema, - &input.connector_id, - &input.connector_token, - WALLET_WALLETCONNECT_CAPSULE_ID, - )?; - let request = - pending_wallet_approval_request(&state, &authority.wallet, &request_id).await?; - anyhow::ensure!( - request.connector_id.as_deref() == Some(WALLET_WALLETCONNECT_CAPSULE_ID) - && request.status == "pending" - && request.expires_at > now_ts(), - "WalletConnect request changed or expired" - ); - Ok::<_, anyhow::Error>(request) - } - .await; - match result { - Ok(request) => Json(request).into_response(), - Err(e) => system_error_response(e), - } -} - pub(super) async fn home_wallet_connector_approval_handoff( State(state): State, headers: HeaderMap, @@ -393,34 +352,15 @@ pub(super) async fn home_wallet_connector_approval_handoff( )); } }; - let mut response = json!({ + Json(json!({ "schema": HOME_WALLET_CONNECTOR_RESULT_SCHEMA, "action": "approval_handoff", "connector_id": input.connector_id, "request_id": request_id, "handoff": handoff, "evm_chains": wallet_connector_evm_chains(), - }); - if input.connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { - let Some(binding) = outcome.approval_request else { - return system_error_response(anyhow::anyhow!( - "WalletConnect approval binding is missing" - )); - }; - if binding["principal_id"].as_str() != Some(authority.context.principal_id.as_str()) - || binding["payload_hash"] != response["handoff"]["payload_hash"] - { - return system_error_response(anyhow::anyhow!( - "WalletConnect approval binding mismatch" - )); - } - response["binding"] = json!({ - "principal_id":binding["principal_id"], "requested_by_actor":binding["requested_by_actor"], - "account_id":binding["account_id"], "chain_namespace":binding["chain_namespace"], - "payload_hash":binding["payload_hash"], "expires_at":binding["expires_at"], - }); - } - Json(response).into_response() + })) + .into_response() } Err(err) => system_error_response(err), } @@ -476,29 +416,7 @@ pub(super) async fn home_wallet_connector_approval_complete( } } -pub(super) fn require_home_wallet_connector_authority( - state: &GatewayState, - headers: &HeaderMap, - schema: &str, - connector_id: &str, - connector_token: &str, - expected_connector_id: &str, -) -> anyhow::Result { - let authority = revalidate_home_wallet_connector_authority( - state, - headers, - schema, - connector_id, - connector_token, - expected_connector_id, - )?; - ensure_wallet_connector_configured(&state.data_dir, connector_id)?; - Ok(authority) -} - -// Runtime transports verify the installed SDK at admission. Recurring checks -// still verify both live launch authorities and the configuration shape. -pub(super) fn revalidate_home_wallet_connector_authority( +fn require_home_wallet_connector_authority( state: &GatewayState, headers: &HeaderMap, schema: &str, @@ -509,14 +427,12 @@ pub(super) fn revalidate_home_wallet_connector_authority( if schema != HOME_WALLET_CONNECTOR_REQUEST_SCHEMA { anyhow::bail!("unsupported Home wallet-connector request schema"); } - if connector_id != expected_connector_id || !HOSTED_WALLET_CONNECTOR_IDS.contains(&connector_id) + if connector_id != expected_connector_id + || !INJECTED_WALLET_CONNECTOR_IDS.contains(&connector_id) { anyhow::bail!("Home wallet-connector actor mismatch"); } - if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { - let config = load_walletconnect_connector_config(&state.data_dir)?; - validate_walletconnect_connector_config(&config)?; - } + ensure_wallet_connector_configured(&state.data_dir, connector_id)?; let home = require_home_runtime_wallet_authority(&state.data_dir, headers)?; let connector_launch = @@ -584,17 +500,13 @@ fn validate_home_wallet_connector_handoff( } match connector_id { - WALLET_METAMASK_CAPSULE_ID | WALLET_WALLETCONNECT_CAPSULE_ID - if handoff.intent == "bitcoin_bip322_proof" => - { + WALLET_METAMASK_CAPSULE_ID if handoff.intent == "bitcoin_bip322_proof" => { anyhow::bail!("MetaMask handoff cannot carry a Bitcoin approval") } WALLET_UNISAT_CAPSULE_ID if handoff.intent != "bitcoin_bip322_proof" => { anyhow::bail!("UniSat handoff must carry a Bitcoin approval") } - WALLET_METAMASK_CAPSULE_ID | WALLET_WALLETCONNECT_CAPSULE_ID - if handoff.intent == "transaction_intent" => - { + WALLET_METAMASK_CAPSULE_ID if handoff.intent == "transaction_intent" => { if handoff.status != "awaiting_wallet_transaction" || handoff.transaction.is_none() || handoff.message.is_some() @@ -603,7 +515,7 @@ fn validate_home_wallet_connector_handoff( anyhow::bail!("Wallet connector transaction handoff is invalid"); } } - WALLET_METAMASK_CAPSULE_ID | WALLET_WALLETCONNECT_CAPSULE_ID => { + WALLET_METAMASK_CAPSULE_ID => { if handoff.status != "awaiting_wallet_signature" || handoff.transaction.is_some() || handoff.message.is_none() diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index d13847292..9bbfe800e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -289,7 +289,7 @@ async fn content_sandbox_site_files_and_admitted_bundle_preserve_provenance() { .unwrap(); assert_eq!(home.status(), StatusCode::OK); assert_eq!(home.headers().get("content-security-policy").unwrap(), - "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' ws://localhost:61180; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"); + "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self'; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"); let health = app .oneshot( Request::builder() diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 0df2ec83a..24a25e9b6 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1505,3 +1505,100 @@ async fn test_walletconnect_capsule_config_link_and_effect_authority_matrix() { ); } } + +#[tokio::test] +async fn test_walletconnect_unfinished_transaction_is_visible_without_another_handoff() { + let dir = tempfile::tempdir().unwrap(); + let owner = passkey_authority(dir.path()); + seed_walletconnect_connector_config(dir.path()); + let token = projection_launch_token_for_authority_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &owner, + ); + let provider = MockWalletProvider { + approvals: TokioMutex::new(vec![json!({ + "request_id":"wallet-approval:unfinished","status":"approved","intent":"transaction_intent", + "requested_by_actor":"documents","resource":"elastos://transaction","reason":"Fixture","account_id":"fixture-account", + "address":format!("0x{}","12".repeat(20)),"proof_type":"siwe","chain_namespace":"eip155:1", + "connector_id":WALLET_WALLETCONNECT_CAPSULE_ID,"principal_id":owner.principal_id, + "payload_hash":format!("0x{}","ab".repeat(32)),"created_at":now_ts(),"expires_at":now_ts()+600, + })]), + ..Default::default() + }; + let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); + let response = app + .clone() + .oneshot( + test_browser_request("localhost:61180", "null") + .uri("/api/apps/wallet-walletconnect/wallet/approvals") + .header("x-elastos-home-token", &token) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), 65536) + .await + .unwrap(); + let summary: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(summary["pending_count"], 0); + assert_eq!(summary["approval_requests"][0]["status"], "approved"); + let response=app.oneshot(test_browser_request("localhost:61180","null").method("POST") + .uri("/api/apps/wallet-walletconnect/wallet/approvals/wallet-approval%3Aunfinished/approve") + .header("x-elastos-home-token",token).header(CONTENT_TYPE,"application/json").body(Body::from("{}")).unwrap()).await.unwrap(); + assert_ne!(response.status(), StatusCode::OK); +} + +#[tokio::test] +async fn test_walletconnect_account_removal_clears_its_store_through_wallet_route() { + for connector_id in [WALLET_WALLETCONNECT_CAPSULE_ID, WALLET_METAMASK_CAPSULE_ID] { + let dir = tempfile::tempdir().unwrap(); + let owner = passkey_authority(dir.path()); + let token = app_token_for_authority(dir.path(), WALLET_CAPSULE_ID, &owner); + let principal = &owner.principal_id; + let directory = dir + .path() + .join("ElastOS/SystemServices/WalletConnect/sessions"); + std::fs::create_dir_all(&directory).unwrap(); + let store = directory.join(format!( + "{}.json", + hex::encode(Sha256::digest(principal.as_bytes())) + )); + std::fs::write(&store, b"{}").unwrap(); + let provider = MockWalletProvider { + accounts: TokioMutex::new(vec![json!({ + "account_id":"fixture-account","principal_id":principal,"proof_binding_id":"fixture-proof", + "chain_namespace":"eip155:1","address":format!("0x{}","12".repeat(20)),"proof_type":"siwe", + "connector_id":connector_id,"linked_at":now_ts(), + })]), + ..Default::default() + }; + let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); + let step_up = step_up_token_for_app_context( + dir.path(), + WALLET_CAPSULE_ID, + &token, + "wallet.account.delete", + &json!({"account_id":"fixture-account"}), + ); + let response = app + .oneshot( + test_browser_request("localhost:61180", "null") + .method("DELETE") + .uri("/api/apps/wallet/wallet/accounts/fixture-account") + .header("x-elastos-home-token", token) + .header(CONTENT_TYPE, "application/json") + .body(Body::from(json!({"step_up_token":step_up}).to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + store.exists(), + connector_id != WALLET_WALLETCONNECT_CAPSULE_ID + ); + } +} diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 2ac5a7f69..1d3d4aa2a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -326,23 +326,16 @@ impl Fixture { } #[tokio::test] -async fn walletconnect_home_and_connector_share_one_consent_request() { +async fn walletconnect_connector_reuses_one_consent_request() { let f = Fixture::new().await; - let (status, host) = f - .route( - &f.connector, - "/api/apps/wallet-walletconnect/host-config", - Some(json!({})), - ) + let (status, first) = f + .route(&f.connector, INTERNET, Some(json!({"action":"request"}))) .await; assert_eq!(status, StatusCode::OK); - let (_, connector) = f + let (_, second) = f .route(&f.connector, INTERNET, Some(json!({"action":"request"}))) .await; - assert_eq!( - host["internet"]["request"]["id"], - connector["request"]["id"] - ); + assert_eq!(first["request"]["id"], second["request"]["id"]); assert_eq!(f.calls.load(Ordering::SeqCst), 0); } @@ -499,6 +492,7 @@ async fn walletconnect_real_relay_requires_consent_allowlist_and_connector() { #[tokio::test] async fn walletconnect_storage_is_principal_scoped_and_survives_service_restart() { let mut f = Fixture::new().await; + f.allow().await; let (status, _) = f .route( &f.connector, @@ -962,3 +956,91 @@ async fn walletconnect_caps_unadmitted_opaque_sockets_and_recovers() { recovered.close(None).await.unwrap(); assert_eq!(f.calls.load(Ordering::SeqCst), 0); } + +#[tokio::test] +async fn walletconnect_disconnect_and_turn_off_clear_sessions_and_refuse_late_writes() { + let f = Fixture::new().await; + f.allow().await; + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"session","value":"fixture"})) + ) + .await + .0, + StatusCode::OK + ); + let response = f + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, &f.addr) + .header("origin", "null") + .header("x-elastos-home-token", &f.connector) + .method("DELETE") + .uri(STORAGE) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(f.route(&f.connector, STORAGE, None).await.1, json!({})); + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"session","value":"fixture"})) + ) + .await + .0, + StatusCode::OK + ); + let (_, grant) = f.route(&f.inbox, INTERNET, None).await; + f.answer(&grant, true).await; + assert_eq!(f.route(&f.connector, STORAGE, None).await.1, json!({})); + assert_ne!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"late","value":"refused"})) + ) + .await + .0, + StatusCode::OK + ); +} + +#[tokio::test] +async fn walletconnect_cleanup_refuses_linked_parent_and_preserves_other_files() { + let f = Fixture::new().await; + f.allow().await; + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"session","value":"fixture"})) + ) + .await + .0, + StatusCode::OK + ); + let data = f.data.path(); + let sessions = data.join("ElastOS/SystemServices/WalletConnect/sessions"); + let other = tempfile::tempdir().unwrap(); + let principal = + runtime_wallet_authority_for_app_token(data, WALLET_WALLETCONNECT_CAPSULE_ID, &f.connector) + .home_launch_context() + .principal_id; + let name = format!("{}.json", hex::encode(Sha256::digest(principal.as_bytes()))); + std::fs::write(other.path().join(&name), "preserve").unwrap(); + std::fs::rename(&sessions, sessions.with_extension("held")).unwrap(); + std::os::unix::fs::symlink(other.path(), &sessions).unwrap(); + assert!(gateway_walletconnect::clear_principal_storage(data, &principal).is_err()); + assert_eq!( + std::fs::read_to_string(other.path().join(name)).unwrap(), + "preserve" + ); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs index 0809ab03b..6ca534179 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs @@ -29,7 +29,17 @@ pub(in crate::api::gateway) async fn runtime_wallet_data( .await? .result { - elastos_wallet_contract::WalletResultV2::Ok { data } => Ok(data), + elastos_wallet_contract::WalletResultV2::Ok { data } => { + if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID + && !data["account"]["revoked_at"].is_null() + { + gateway_walletconnect::clear_principal_storage( + &state.data_dir, + authority.verified_context().principal_id(), + )?; + } + Ok(data) + } elastos_wallet_contract::WalletResultV2::Error { message, .. } => anyhow::bail!(message), } } @@ -49,7 +59,17 @@ pub(in crate::api::gateway) async fn runtime_wallet_data_with_request_id( .await? .result { - elastos_wallet_contract::WalletResultV2::Ok { data } => Ok(data), + elastos_wallet_contract::WalletResultV2::Ok { data } => { + if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID + && !data["account"]["revoked_at"].is_null() + { + gateway_walletconnect::clear_principal_storage( + &state.data_dir, + authority.verified_context().principal_id(), + )?; + } + Ok(data) + } elastos_wallet_contract::WalletResultV2::Error { message, .. } => anyhow::bail!(message), } } diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 8e73baf03..034311f18 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -74,12 +74,23 @@ pub(in crate::api::gateway) async fn wallet_connector_approvals( Ok(authority) => authority, Err(err) => return system_error_response(err), }; - let mut summary = system_wallet_approvals_summary(&state, &authority, false).await; + let mut summary = system_wallet_approvals_summary( + &state, + &authority, + wallet_connector == WALLET_WALLETCONNECT_CAPSULE_ID, + ) + .await; summary.approval_requests.retain(|request| { !is_managed_wallet_proof_type(&request.proof_type) && request.connector_id.as_deref() == Some(wallet_connector.as_str()) + && (request.status == "pending" + || (request.status == "approved" && request.intent == "transaction_intent")) }); - summary.pending_count = summary.approval_requests.len(); + summary.pending_count = summary + .approval_requests + .iter() + .filter(|r| r.status == "pending") + .count(); Json(summary).into_response() } diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index a5db21a6b..149009676 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -249,6 +249,7 @@ pub(super) async fn answer( .await??; } inner.sockets.clear(); + clear_all_storage(&state.data_dir)?; return Ok("WalletConnect connection turned off.".into()); } } @@ -333,7 +334,7 @@ pub(super) async fn internet( input.action == "request", "Invalid WalletConnect internet action" ); - ensure_admin_context(&state.data_dir, &authority.home_launch_context())?; + ensure_admin_context(&state.data_dir, &authority.home_launch_context()).map_err(|_| anyhow::anyhow!("Only this Home's owner can allow WalletConnect internet access. Ask the owner to review Inbox."))?; ensure_consent_request(&state, &authority.home_launch_context(), &inner)?; } Ok::<_, anyhow::Error>(public(load(&state.data_dir)?.as_ref())) @@ -443,25 +444,6 @@ pub(super) async fn admission(State(state): State, headers: Header .await; private_response(result) } -pub(super) async fn host_config( - State(state): State, - method: axum::http::Method, - headers: HeaderMap, -) -> Response { - let result = async { - let authority = connector_authority(&state, &headers)?; - if method == axum::http::Method::POST { verify_sdk(&state).await?; } - let inner = state.walletconnect.inner.lock().await; - if method == axum::http::Method::POST { - ensure_consent_request(&state, &authority.home_launch_context(), &inner)?; - } - let config = load_walletconnect_connector_config(&state.data_dir)?; - Ok::<_, anyhow::Error>(json!({"projectId":config.project_id, "principal_id":authority.home_launch_context().principal_id, - "internet":public(load(&state.data_dir)?.as_ref()), - "sdk_asset_path":"/apps/wallet-walletconnect/vendor/reown-appkit.js"})) - }.await; - private_response(result) -} fn private_response(result: anyhow::Result) -> Response { let mut response = match result { Ok(value) => Json(value).into_response(), @@ -500,6 +482,20 @@ pub(super) async fn storage( &state.data_dir, &authority.home_launch_context().principal_id, ); + if method == axum::http::Method::DELETE { + clear_principal_storage( + &state.data_dir, + &authority.home_launch_context().principal_id, + )?; + return Ok(BTreeMap::new()); + } + if method == axum::http::Method::POST { + check_owner(&state, false).await?; + } + let _files = session_files_lock()?; + // Removal and storage commits share this lock. Revalidate after acquiring + // it so a write admitted before principal removal cannot recreate keys. + connector_authority(&state, &headers)?; let mut values: BTreeMap = read(&path, MAX_BYTES)?.unwrap_or_default(); if method == axum::http::Method::POST { @@ -842,3 +838,75 @@ mod tests { .contains("idle")); } } + +// Runtime owns these exact, principal-derived session paths; UI never selects a path. +pub(crate) fn clear_principal_storage(data: &FsPath, principal: &str) -> anyhow::Result<()> { + let _files = session_files_lock()?; + let path = storage_path(data, principal); + match std::fs::symlink_metadata(&path) { + Ok(meta) => { + anyhow::ensure!( + meta.is_file() && !meta.file_type().is_symlink(), + "WalletConnect session requires a regular file" + ); + remove_session_file(data, &path, &meta)?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), + } + Ok(()) +} +fn clear_all_storage(data: &FsPath) -> anyhow::Result<()> { + let _files = session_files_lock()?; + let dir = root(data).join("sessions"); + if !dir.try_exists()? { + return Ok(()); + } + anyhow::ensure!( + !std::fs::symlink_metadata(&dir)?.file_type().is_symlink(), + "WalletConnect sessions require their Runtime directory" + ); + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_str().unwrap_or_default(); + anyhow::ensure!( + name.strip_suffix(".json").is_some_and(|stem| stem.len() == 64 && stem.bytes().all(|b| b.is_ascii_hexdigit())), + "Invalid WalletConnect session file" + ); + anyhow::ensure!( + entry.file_type()?.is_file(), + "WalletConnect session requires a regular file" + ); + let path = entry.path(); + remove_session_file(data, &path, &std::fs::symlink_metadata(&path)?)?; + } + Ok(()) +} + +fn remove_session_file( + data: &FsPath, + path: &FsPath, + metadata: &std::fs::Metadata, +) -> anyhow::Result<()> { + #[cfg(unix)] + { + elastos_common::owned_removal::remove_owned( + data, + path.strip_prefix(data)?, + Some(elastos_common::owned_removal::FileIdentity::of(metadata)), + )?; + Ok(()) + } + #[cfg(not(unix))] + { + let _ = (data, path, metadata); + anyhow::bail!("WalletConnect session cleanup requires its supported host adapter") + } +} + +fn session_files_lock() -> anyhow::Result> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + LOCK.lock() + .map_err(|_| anyhow::anyhow!("WalletConnect session storage is unavailable")) +} diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index 0404ce548..a1bb326e9 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -4536,9 +4536,19 @@ fn mutate_auth_state( let lock = lock_auth_state_file(open_auth_state_lock(data_dir)?)?; let (mut state, device_key_identity) = load_auth_state_with_identity(data_dir)?; let baseline = AuditBaseline::new(&state, device_key_identity); + let previous_principals = state + .principals + .iter() + .map(|p| p.principal_id.clone()) + .collect::>(); ensure_audit_chain_state(data_dir, &mut state)?; let value = mutation(&mut state)?; save_auth_state(data_dir, &state, Some(&baseline))?; + for principal in previous_principals { + if !state.principals.iter().any(|p| p.principal_id == principal) { + crate::api::gateway::clear_walletconnect_principal_storage(data_dir, &principal)?; + } + } unlock_auth_state_file(lock)?; Ok(value) } @@ -15771,6 +15781,33 @@ mod tests { assert!(error.to_string().contains("1-64 objects")); } + #[test] + fn walletconnect_removed_principal_clears_only_its_session_file() { + let data = tempfile::tempdir().unwrap(); + let principal = + upsert_principal_for_binding(data.path(), passkey_binding(1, 100, 100), 100).unwrap(); + let directory = data + .path() + .join("ElastOS/SystemServices/WalletConnect/sessions"); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join(format!( + "{}.json", + hex::encode(sha2::Sha256::digest(principal.principal_id.as_bytes())) + )); + std::fs::write(&path, b"{}").unwrap(); + let other = directory.join(format!("{}.json", "aa".repeat(32))); + std::fs::write(&other, b"preserve").unwrap(); + mutate_auth_state(data.path(), |state| { + state + .principals + .retain(|p| p.principal_id != principal.principal_id); + Ok(()) + }) + .unwrap(); + assert!(!path.exists()); + assert_eq!(std::fs::read(other).unwrap(), b"preserve"); + } + #[test] fn passkey_revoke_marks_binding_and_sessions_revoked() { let data_dir = tempfile::tempdir().unwrap(); From a7f9742b4565819259b58fea5489a9699becf8ae Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:27:43 -0500 Subject: [PATCH 055/139] docs(walletconnect): describe capsule custody and keep one dependency lock --- .../wallet-walletconnect/vendor/adapter.json | 2 +- .../vendor/package-lock.json | 4930 ----------------- docs/WALLET_PROVIDER.md | 91 +- elastos/CHANGELOG.md | 2 + scripts/vendor-walletconnect-adapter.sh | 3 +- 5 files changed, 53 insertions(+), 4975 deletions(-) delete mode 100644 capsules/wallet-walletconnect/vendor/package-lock.json diff --git a/capsules/wallet-walletconnect/vendor/adapter.json b/capsules/wallet-walletconnect/vendor/adapter.json index 394fbe2a6..ef5eb326a 100644 --- a/capsules/wallet-walletconnect/vendor/adapter.json +++ b/capsules/wallet-walletconnect/vendor/adapter.json @@ -7,6 +7,6 @@ "adapter.mjs": "8365b7d00728a0242f3065f39bfc43d8cff192587b2b9a05036d029b3f22e7af", "runtime-storage.mjs": "3e3d746baf073b0b0704b97a2bd7cdc67931fdb13ea08578d5c3ad4b2c7a81d0", "runtime-websocket.mjs": "69912984aa26ddc315871695b5f19c136aec254e1e846554d5609de83c3d3121", - "../vendor-walletconnect-adapter.sh": "ea02a352688ec39ddf818ac29e8473a8225e414ea7fc62f142b589c0a3cea1d7" + "../vendor-walletconnect-adapter.sh": "adc5ef76c22b3698d733f8039dafc0bd5593c319f07261f613681308a4089546" } } diff --git a/capsules/wallet-walletconnect/vendor/package-lock.json b/capsules/wallet-walletconnect/vendor/package-lock.json deleted file mode 100644 index f231e7c35..000000000 --- a/capsules/wallet-walletconnect/vendor/package-lock.json +++ /dev/null @@ -1,4930 +0,0 @@ -{ - "name": "walletconnect", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "dependencies": { - "@walletconnect/ethereum-provider": "2.23.9", - "qrcode": "1.5.4" - }, - "devDependencies": { - "esbuild": "0.28.0" - } - }, - "node_modules/@adraffy/ens-normalize": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", - "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", - "license": "MIT" - }, - "node_modules/@base-org/account": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@base-org/account/-/account-2.4.0.tgz", - "integrity": "sha512-A4Umpi8B9/pqR78D1Yoze4xHyQaujioVRqqO3d6xuDFw9VRtjg6tK3bPlwE0aW+nVH/ntllCpPa2PbI8Rnjcug==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@coinbase/cdp-sdk": "^1.0.0", - "@noble/hashes": "1.4.0", - "clsx": "1.2.1", - "eventemitter3": "5.0.1", - "idb-keyval": "6.2.1", - "ox": "0.6.9", - "preact": "10.24.2", - "viem": "^2.31.7", - "zustand": "5.0.3" - } - }, - "node_modules/@coinbase/cdp-sdk": { - "version": "1.62.0", - "resolved": "https://registry.npmjs.org/@coinbase/cdp-sdk/-/cdp-sdk-1.62.0.tgz", - "integrity": "sha512-i25CM7YkheI4bIUUfdEl1ZFl8OhPtlr6HsOULSSPrOOetEEIo6KC81vr3RmrhejwYLzC9GSbVbfxy2pxgjPIXQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana-program/system": "^0.16.0", - "@solana-program/token": "^0.16.0", - "@solana/kit": "^8.6.0", - "abitype": "1.0.6", - "axios": "^1.18.0", - "axios-retry": "^4.5.0", - "bs58": "^6.0.0", - "jose": "^6.2.0", - "md5": "^2.3.0", - "uncrypto": "^0.1.3", - "viem": "^2.47.0", - "zod": "^3.25.76" - }, - "peerDependencies": { - "@x402/core": "^2.29.0", - "@x402/evm": "^2.29.0", - "@x402/extensions": "^2.29.0", - "@x402/svm": "^2.29.0" - }, - "peerDependenciesMeta": { - "@x402/core": { - "optional": true - }, - "@x402/evm": { - "optional": true - }, - "@x402/extensions": { - "optional": true - }, - "@x402/svm": { - "optional": true - } - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", - "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", - "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", - "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", - "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", - "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", - "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", - "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", - "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", - "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", - "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", - "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", - "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", - "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", - "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", - "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", - "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", - "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", - "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", - "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", - "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", - "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", - "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", - "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", - "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", - "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", - "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@lit-labs/ssr-dom-shim": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz", - "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==", - "license": "BSD-3-Clause" - }, - "node_modules/@lit/react": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@lit/react/-/react-1.0.8.tgz", - "integrity": "sha512-p2+YcF+JE67SRX3mMlJ1TKCSTsgyOVdAwd/nxp3NuV1+Cb6MWALbN6nT7Ld4tpmYofcE5kcaSY1YBB9erY+6fw==", - "license": "BSD-3-Clause", - "optional": true, - "peerDependencies": { - "@types/react": "17 || 18 || 19" - } - }, - "node_modules/@lit/reactive-element": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz", - "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==", - "license": "BSD-3-Clause", - "dependencies": { - "@lit-labs/ssr-dom-shim": "^1.5.0" - } - }, - "node_modules/@msgpack/msgpack": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz", - "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==", - "license": "ISC", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@noble/ciphers": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", - "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/curves": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.8.0.tgz", - "integrity": "sha512-j84kjAbzEnQHaSIhRPUmB3/eVXu2k3dKPl2LOrR8fSOIL+89U+7lV117EWHtq/GHM3ReGHM46iRBdZfpc4HRUQ==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.7.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/curves/node_modules/@noble/hashes": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.0.tgz", - "integrity": "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz", - "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@phosphor-icons/webcomponents": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@phosphor-icons/webcomponents/-/webcomponents-2.1.5.tgz", - "integrity": "sha512-JcvQkZxvcX2jK+QCclm8+e8HXqtdFW9xV4/kk2aL9Y3dJA2oQVt+pzbv1orkumz3rfx4K9mn9fDoMr1He1yr7Q==", - "license": "MIT", - "dependencies": { - "lit": "^3" - } - }, - "node_modules/@reown/appkit": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit/-/appkit-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-7JjEp+JNxRUDOa7CxOCbUbG8uYVo38ojc9FN/fuzJuJADUzKDaH287MLV9qI1ZyQyXA8qXvhXRqjtw+3xo2/7A==", - "hasInstallScript": true, - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-pay": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-scaffold-ui": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", - "@walletconnect/universal-provider": "2.23.2", - "bs58": "6.0.0", - "semver": "7.7.2", - "valtio": "2.1.7", - "viem": ">=2.37.9" - }, - "optionalDependencies": { - "@lit/react": "1.0.8" - } - }, - "node_modules/@reown/appkit-common": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-common/-/appkit-common-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-wf53EzDmCJ5ICtDY5B1MddVeCwoqDGPVmaxD4wQJLR9uanhBXfKq1sJou+Uj8lZCyI72Z+r9YlsePOlYH2Ge3A==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "big.js": "6.2.2", - "dayjs": "1.11.13", - "viem": ">=2.37.9" - } - }, - "node_modules/@reown/appkit-controllers": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-controllers/-/appkit-controllers-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-wY5yvMB0o2AwitwDHHO0u2tmqR+n3Crv0AHjIcY037PC3mhF9TPEUKqE9vlrFImQWQRxl0WRfuKfzmUAPxZExw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", - "@walletconnect/universal-provider": "2.23.2", - "valtio": "2.1.7", - "viem": ">=2.37.9" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@msgpack/msgpack": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", - "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", - "license": "ISC", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@noble/curves": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", - "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/core": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", - "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/jsonrpc-ws-connection": "1.0.16", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "@walletconnect/window-getters": "1.0.1", - "es-toolkit": "1.39.3", - "events": "3.3.0", - "uint8arrays": "3.1.1" - }, - "engines": { - "node": ">=18.20.8" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/sign-client": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", - "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/core": "2.23.2", - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/logger": "3.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/types": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", - "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/universal-provider": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", - "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/jsonrpc-http-connection": "1.0.8", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/sign-client": "2.23.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "es-toolkit": "1.39.3", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/@walletconnect/utils": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", - "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@msgpack/msgpack": "3.1.2", - "@noble/ciphers": "1.3.0", - "@noble/curves": "1.9.7", - "@noble/hashes": "1.8.0", - "@scure/base": "1.2.6", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/window-getters": "1.0.1", - "@walletconnect/window-metadata": "1.0.1", - "blakejs": "1.2.1", - "bs58": "6.0.0", - "detect-browser": "5.3.0", - "ox": "0.9.3", - "uint8arrays": "3.1.1" - } - }, - "node_modules/@reown/appkit-controllers/node_modules/abitype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", - "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/wevm" - }, - "peerDependencies": { - "typescript": ">=5.0.4", - "zod": "^3.22.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - }, - "zod": { - "optional": true - } - } - }, - "node_modules/@reown/appkit-controllers/node_modules/es-toolkit": { - "version": "1.39.3", - "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", - "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", - "license": "MIT", - "workspaces": [ - "docs", - "benchmarks" - ] - }, - "node_modules/@reown/appkit-controllers/node_modules/ox": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", - "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "^1.11.0", - "@noble/ciphers": "^1.3.0", - "@noble/curves": "1.9.1", - "@noble/hashes": "^1.8.0", - "@scure/bip32": "^1.7.0", - "@scure/bip39": "^1.6.0", - "abitype": "^1.0.9", - "eventemitter3": "5.0.1" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@reown/appkit-controllers/node_modules/ox/node_modules/@noble/curves": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", - "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit-pay": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-pay/-/appkit-pay-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-sVE8UT7CDA8zsg3opvbGjSZHSnohOVPF77vP6Ln4G0+vfoiXNhZaZa89Pg0MDjh+KGy0OulWVUdXuZ9jJQFvPg==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", - "lit": "3.3.0", - "valtio": "2.1.7" - } - }, - "node_modules/@reown/appkit-polyfills": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-polyfills/-/appkit-polyfills-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-OyYavslCegfUlKu8Ah6BZhbqQrK7bImvUm+EKjjvnfNN9J0F9uWMFwbTpZxenBcfAI6cyaD9aTTUunMn5no1Og==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "buffer": "6.0.3" - } - }, - "node_modules/@reown/appkit-scaffold-ui": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-scaffold-ui/-/appkit-scaffold-ui-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-f+SYFGDy+uY1EAvWcH6vZgga1bOuzBvYSKYiRX2QQy8INtZqwwiLLvS4cgm5Yp1WvYRal5RdfZkKl5qha498gw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-pay": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-ui": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-utils": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", - "lit": "3.3.0" - } - }, - "node_modules/@reown/appkit-ui": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-ui/-/appkit-ui-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-E1u2ZVZV0iFDSgrgtdQTZAXNbI+Lakj8E8V+jJQ47JaEVKv9SROvPu2fVqfIrqHQF68NmAk1dnbYi4luOiM0Fg==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@phosphor-icons/webcomponents": "2.1.5", - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", - "lit": "3.3.0", - "qrcode": "1.5.3" - } - }, - "node_modules/@reown/appkit-ui/node_modules/qrcode": { - "version": "1.5.3", - "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.3.tgz", - "integrity": "sha512-puyri6ApkEHYiVl4CFzo1tDkAZ+ATcnbJrJ6RiBM1Fhctdn/ix9MTE3hRph33omisEbC/2fcfemsseiKgBPKZg==", - "license": "MIT", - "dependencies": { - "dijkstrajs": "^1.0.1", - "encode-utf8": "^1.0.3", - "pngjs": "^5.0.0", - "yargs": "^15.3.1" - }, - "bin": { - "qrcode": "bin/qrcode" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/@reown/appkit-utils": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-utils/-/appkit-utils-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-9El8sYbXDaMYxg4R6LujA965yYQGjNcPMXqympLtzNl1es5qkniW7eAdEpLmZrsaqNrfTaHT1G65wYy7sA595w==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-controllers": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-wallet": "1.8.17-wc-circular-dependencies-fix.0", - "@wallet-standard/wallet": "1.1.0", - "@walletconnect/logger": "3.0.2", - "@walletconnect/universal-provider": "2.23.2", - "valtio": "2.1.7", - "viem": ">=2.37.9" - }, - "optionalDependencies": { - "@base-org/account": "2.4.0", - "@safe-global/safe-apps-provider": "0.18.6", - "@safe-global/safe-apps-sdk": "9.1.0" - }, - "peerDependencies": { - "valtio": "2.1.7" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@msgpack/msgpack": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", - "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", - "license": "ISC", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@noble/curves": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", - "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@walletconnect/core": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", - "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/jsonrpc-ws-connection": "1.0.16", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "@walletconnect/window-getters": "1.0.1", - "es-toolkit": "1.39.3", - "events": "3.3.0", - "uint8arrays": "3.1.1" - }, - "engines": { - "node": ">=18.20.8" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@walletconnect/sign-client": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", - "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/core": "2.23.2", - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/logger": "3.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@walletconnect/types": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", - "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@walletconnect/universal-provider": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", - "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/jsonrpc-http-connection": "1.0.8", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/sign-client": "2.23.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "es-toolkit": "1.39.3", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit-utils/node_modules/@walletconnect/utils": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", - "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@msgpack/msgpack": "3.1.2", - "@noble/ciphers": "1.3.0", - "@noble/curves": "1.9.7", - "@noble/hashes": "1.8.0", - "@scure/base": "1.2.6", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/window-getters": "1.0.1", - "@walletconnect/window-metadata": "1.0.1", - "blakejs": "1.2.1", - "bs58": "6.0.0", - "detect-browser": "5.3.0", - "ox": "0.9.3", - "uint8arrays": "3.1.1" - } - }, - "node_modules/@reown/appkit-utils/node_modules/abitype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", - "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/wevm" - }, - "peerDependencies": { - "typescript": ">=5.0.4", - "zod": "^3.22.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - }, - "zod": { - "optional": true - } - } - }, - "node_modules/@reown/appkit-utils/node_modules/es-toolkit": { - "version": "1.39.3", - "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", - "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", - "license": "MIT", - "workspaces": [ - "docs", - "benchmarks" - ] - }, - "node_modules/@reown/appkit-utils/node_modules/ox": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", - "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "^1.11.0", - "@noble/ciphers": "^1.3.0", - "@noble/curves": "1.9.1", - "@noble/hashes": "^1.8.0", - "@scure/bip32": "^1.7.0", - "@scure/bip39": "^1.6.0", - "abitype": "^1.0.9", - "eventemitter3": "5.0.1" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@reown/appkit-utils/node_modules/ox/node_modules/@noble/curves": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", - "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit-wallet": { - "version": "1.8.17-wc-circular-dependencies-fix.0", - "resolved": "https://registry.npmjs.org/@reown/appkit-wallet/-/appkit-wallet-1.8.17-wc-circular-dependencies-fix.0.tgz", - "integrity": "sha512-s0RTVNtgPtXGs+eZELVvTu1FRLuN15MyhVS//3/4XafVQkBBJarciXk9pFP71xeSHRzjYR1lXHnVw28687cUvQ==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit-common": "1.8.17-wc-circular-dependencies-fix.0", - "@reown/appkit-polyfills": "1.8.17-wc-circular-dependencies-fix.0", - "@walletconnect/logger": "3.0.2", - "zod": "3.22.4" - } - }, - "node_modules/@reown/appkit-wallet/node_modules/zod": { - "version": "3.22.4", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz", - "integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/@reown/appkit/node_modules/@msgpack/msgpack": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.2.tgz", - "integrity": "sha512-JEW4DEtBzfe8HvUYecLU9e6+XJnKDlUAIve8FvPzF3Kzs6Xo/KuZkZJsDH0wJXl/qEZbeeE7edxDNY3kMs39hQ==", - "license": "ISC", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@reown/appkit/node_modules/@noble/curves": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", - "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@reown/appkit/node_modules/@walletconnect/core": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.2.tgz", - "integrity": "sha512-KkaTELRu8t/mt3J9doCQ1fBGCbYsCNfpo2JpKdCwKQR7PVjVKeVpYQK/blVkA5m6uLPpBtVRbOMKjnHW1m7JLw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/jsonrpc-ws-connection": "1.0.16", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "@walletconnect/window-getters": "1.0.1", - "es-toolkit": "1.39.3", - "events": "3.3.0", - "uint8arrays": "3.1.1" - }, - "engines": { - "node": ">=18.20.8" - } - }, - "node_modules/@reown/appkit/node_modules/@walletconnect/sign-client": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.2.tgz", - "integrity": "sha512-LL5KgmJHvY5NqQn+ZHQJLia1p6fpUWXHtiG97S5rNfyuPx6gT/Jkkwqc2LwdmAjFkr61t8zTagHC9ETq203mNA==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/core": "2.23.2", - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/logger": "3.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit/node_modules/@walletconnect/types": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.2.tgz", - "integrity": "sha512-5dxBCdUM+4Dqe1/A7uqkm2tWPXce4UUGSr+ImfI0YjwEExQS8+TzdOlhMt3n32ncnBCllU5paG+fsndT06R0iw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit/node_modules/@walletconnect/universal-provider": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.2.tgz", - "integrity": "sha512-vs9iorPUAiVesFJ95O6XvLjmRgF+B2TspxJNL90ZULbrkRw4JFsmaRdb965PZKc+s182k1MkS/MQ0o964xRcEw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/jsonrpc-http-connection": "1.0.8", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/sign-client": "2.23.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/utils": "2.23.2", - "es-toolkit": "1.39.3", - "events": "3.3.0" - } - }, - "node_modules/@reown/appkit/node_modules/@walletconnect/utils": { - "version": "2.23.2", - "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.2.tgz", - "integrity": "sha512-ReSjU3kX+3i3tYJQZbVfetY5SSUL+iM6uiIVVD1PJalePa/5A40VgLVRTF7sDCJTIFfpf3Mt4bFjeaYuoxWtIw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@msgpack/msgpack": "3.1.2", - "@noble/ciphers": "1.3.0", - "@noble/curves": "1.9.7", - "@noble/hashes": "1.8.0", - "@scure/base": "1.2.6", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.2", - "@walletconnect/window-getters": "1.0.1", - "@walletconnect/window-metadata": "1.0.1", - "blakejs": "1.2.1", - "bs58": "6.0.0", - "detect-browser": "5.3.0", - "ox": "0.9.3", - "uint8arrays": "3.1.1" - } - }, - "node_modules/@reown/appkit/node_modules/abitype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", - "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/wevm" - }, - "peerDependencies": { - "typescript": ">=5.0.4", - "zod": "^3.22.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - }, - "zod": { - "optional": true - } - } - }, - "node_modules/@reown/appkit/node_modules/es-toolkit": { - "version": "1.39.3", - "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.3.tgz", - "integrity": "sha512-Qb/TCFCldgOy8lZ5uC7nLGdqJwSabkQiYQShmw4jyiPk1pZzaYWTwaYKYP7EgLccWYgZocMrtItrwh683voaww==", - "license": "MIT", - "workspaces": [ - "docs", - "benchmarks" - ] - }, - "node_modules/@reown/appkit/node_modules/ox": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", - "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "^1.11.0", - "@noble/ciphers": "^1.3.0", - "@noble/curves": "1.9.1", - "@noble/hashes": "^1.8.0", - "@scure/bip32": "^1.7.0", - "@scure/bip39": "^1.6.0", - "abitype": "^1.0.9", - "eventemitter3": "5.0.1" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@reown/appkit/node_modules/ox/node_modules/@noble/curves": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", - "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@safe-global/safe-apps-provider": { - "version": "0.18.6", - "resolved": "https://registry.npmjs.org/@safe-global/safe-apps-provider/-/safe-apps-provider-0.18.6.tgz", - "integrity": "sha512-4LhMmjPWlIO8TTDC2AwLk44XKXaK6hfBTWyljDm0HQ6TWlOEijVWNrt2s3OCVMSxlXAcEzYfqyu1daHZooTC2Q==", - "license": "MIT", - "optional": true, - "dependencies": { - "@safe-global/safe-apps-sdk": "^9.1.0", - "events": "^3.3.0" - } - }, - "node_modules/@safe-global/safe-apps-sdk": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/@safe-global/safe-apps-sdk/-/safe-apps-sdk-9.1.0.tgz", - "integrity": "sha512-N5p/ulfnnA2Pi2M3YeWjULeWbjo7ei22JwU/IXnhoHzKq3pYCN6ynL9mJBOlvDVv892EgLPCWCOwQk/uBT2v0Q==", - "license": "MIT", - "optional": true, - "dependencies": { - "@safe-global/safe-gateway-typescript-sdk": "^3.5.3", - "viem": "^2.1.1" - } - }, - "node_modules/@safe-global/safe-gateway-typescript-sdk": { - "version": "3.23.1", - "resolved": "https://registry.npmjs.org/@safe-global/safe-gateway-typescript-sdk/-/safe-gateway-typescript-sdk-3.23.1.tgz", - "integrity": "sha512-6ORQfwtEJYpalCeVO21L4XXGSdbEMfyp2hEv6cP82afKXSwvse6d3sdelgaPWUxHIsFRkWvHDdzh8IyyKHZKxw==", - "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=16" - } - }, - "node_modules/@scure/base": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", - "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", - "license": "MIT", - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@scure/bip32": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", - "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", - "license": "MIT", - "dependencies": { - "@noble/curves": "~1.9.0", - "@noble/hashes": "~1.8.0", - "@scure/base": "~1.2.5" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@scure/bip32/node_modules/@noble/curves": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", - "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@scure/bip32/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@scure/bip39": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", - "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "~1.8.0", - "@scure/base": "~1.2.5" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@scure/bip39/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@solana-program/system": { - "version": "0.16.0", - "resolved": "https://registry.npmjs.org/@solana-program/system/-/system-0.16.0.tgz", - "integrity": "sha512-/RG6q2E2vG/XpdOt8Jj/kbQktPlL5JyJuNGAeN9wDcxKDKQtrGTJpDrJgQUxiEy23fsPNXQbLN8XeCtYoMof3Q==", - "license": "Apache-2.0", - "optional": true, - "peerDependencies": { - "@solana/kit": "^8.5.0" - } - }, - "node_modules/@solana-program/token": { - "version": "0.16.1", - "resolved": "https://registry.npmjs.org/@solana-program/token/-/token-0.16.1.tgz", - "integrity": "sha512-X9dsvbh+VDq4SuCfvxn95P1DCvtBYHJOBiVmgBJMfW8l/lp8uSwEhy9IurpcdltnGi5kNIkCm4sk4YOXKAMiCw==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@solana-program/system": "^0.14.0" - }, - "peerDependencies": { - "@solana/kit": "^8.0.0" - } - }, - "node_modules/@solana-program/token/node_modules/@solana-program/system": { - "version": "0.14.1", - "resolved": "https://registry.npmjs.org/@solana-program/system/-/system-0.14.1.tgz", - "integrity": "sha512-K6ZiIrAKoJAfcwfUdsoFvfSAxeRJaRrV7BPFTJvUVRS4m3zszN+nLcdaNMMe2F1/zTriZqC+xh+Kgw6ziGUqpQ==", - "license": "Apache-2.0", - "optional": true, - "peerDependencies": { - "@solana/kit": "^8.0.0" - } - }, - "node_modules/@solana/accounts": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/accounts/-/accounts-8.6.0.tgz", - "integrity": "sha512-yIcrKjbUXzs1K6KkcRJfAHFOsn8Jpp9AeczcHOHQoBv11AxHM5KmdCTv8rnv7OObq696sd3gpbamVxtqnL0meQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/rpc-spec": "8.6.0", - "@solana/rpc-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/addresses": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/addresses/-/addresses-8.6.0.tgz", - "integrity": "sha512-V30spa+zKsY7i4elEEOZQB/1xpRc0CzbSypI/yTZwj/Bg1o09T6A+pflMDTBoIWH3sglmigdK1jApEOOA7Bypg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/assertions": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/nominal-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/assertions": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/assertions/-/assertions-8.6.0.tgz", - "integrity": "sha512-zQFbZoPFE3GqBw/7JyZxaH5t/Ibm7eHOmOfRI542/zz0BHWSnMkR0N5aSndPJd9creMUP+mFtX8hAr6bZ6rDBg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/codecs": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/codecs/-/codecs-8.6.0.tgz", - "integrity": "sha512-7vUVLdYlTay3rsijiBPN4g992V8RXbgY2DNAXrsE6eHFnwaX8gzdDNASgF4Z0mbgNC026qdLG6LTY4l16tvE8g==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/codecs-data-structures": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/fixed-points": "8.6.0", - "@solana/options": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/codecs-core": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/codecs-core/-/codecs-core-8.6.0.tgz", - "integrity": "sha512-1N2XZ1yCJGmdTE3g5Fh6/UOE6y46qing+7CZpxfrgB4Q+1l+R/d0z4G15IpQUNl3vzqML8CFF791f/A1XSVmJA==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/codecs-data-structures": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/codecs-data-structures/-/codecs-data-structures-8.6.0.tgz", - "integrity": "sha512-BLwclFSLVqugUktXucjGfpUFSaX4V7payjSi6x0DDdLs6PaFfjiH3ykQPV5QRkTeOlf0xC6dOMUUntDhYzVyGw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/codecs-numbers": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/codecs-numbers/-/codecs-numbers-8.6.0.tgz", - "integrity": "sha512-GRIArvWJiYxH5w1RMKn7IOCLy0uYB/WRT2kFW/uyXHzL1VNFyud2BIzG0D3iM+AxTd85SdS/x93aV7NEw0mTOQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/codecs-strings": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/codecs-strings/-/codecs-strings-8.6.0.tgz", - "integrity": "sha512-bLS/o5NdCRb9xj23zLACPjxYvDhdjvSDH4XoBAmQ1CPn3cDvVqVvAz0T41Bs/LMykhamkmpqTcWLoTOVqjTz3w==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "fastestsmallesttextencoderdecoder": "^1.0.22", - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "fastestsmallesttextencoderdecoder": { - "optional": true - }, - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/errors": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/errors/-/errors-8.6.0.tgz", - "integrity": "sha512-viHL51ymR1HZB7ZTp0ESkLOyHCa4bPfok9dvRYbMmYokY5ys1xinISKHUhcOHsg9zbuAWBRJUOnZRWAPbb4+yA==", - "license": "MIT", - "optional": true, - "dependencies": { - "chalk": "5.6.2", - "commander": "15.0.0" - }, - "bin": { - "errors": "bin/cli.mjs" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/fast-stable-stringify": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/fast-stable-stringify/-/fast-stable-stringify-8.6.0.tgz", - "integrity": "sha512-PVuzLesqjvuW1qeg0brkUtpRnQYCLS0mB7SsFu+iio+dxFzbrrHzkSYVoUBEEbjXysCq1L350Frs1+v7CEsXGQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/fixed-points": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/fixed-points/-/fixed-points-8.6.0.tgz", - "integrity": "sha512-yS0XIHwWETtTjAgUHPhpQpcigPvC6phba3vW7rvVPSvVz1FhxNki82ojyl1pISglK7IkUTYcGhaXDhsY/oz8rQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/functional": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/functional/-/functional-8.6.0.tgz", - "integrity": "sha512-greLf2tiMJ5oWaSdp3zkAcUF3sIG3CU1UssxoMYNHy/xywbZifKnOl5syQjKY1XdYPZZmLAWJBFYCkzVns5bxA==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/instruction-plans": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/instruction-plans/-/instruction-plans-8.6.0.tgz", - "integrity": "sha512-hq1bLZStauHKmwHWheCoF9UxcFlJsYm9X4saUj4llkJl6GmTrDTmeiE93mJngz4GO6cAkm65D/AjYRcp69jUVw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/promises": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/instructions": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/instructions/-/instructions-8.6.0.tgz", - "integrity": "sha512-1mXhgf5XaIJir02TgkUwzNRJs8mCCRRRsW45ZwqCp66bnIxmxEy3a91twgGXvBfE6dvzzg3TNSjcfqGQ/ADBog==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/keys": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/keys/-/keys-8.6.0.tgz", - "integrity": "sha512-vxj3zmcHfY0EqDSJR8nn7w/qQAdCG3uSyGGcIfLgf/ZhVUgVDYDUyUqrxSL5DxAs64czhSu+ufRh7B5AKwMtaQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/assertions": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/nominal-types": "8.6.0", - "@solana/promises": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/kit": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/kit/-/kit-8.6.0.tgz", - "integrity": "sha512-UaigU+LiTzkU237FxfiJhxufvEfb1J02djJOnGpSz1GAjZtbZ8oc4EkQ1bS4sHewSRyR9RUk6yhBb5bLHG0w4w==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/accounts": "8.6.0", - "@solana/addresses": "8.6.0", - "@solana/codecs": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/instruction-plans": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/offchain-messages": "8.6.0", - "@solana/plugin-core": "8.6.0", - "@solana/plugin-interfaces": "8.6.0", - "@solana/program-client-core": "8.6.0", - "@solana/programs": "8.6.0", - "@solana/promises": "8.6.0", - "@solana/rpc": "8.6.0", - "@solana/rpc-api": "8.6.0", - "@solana/rpc-parsed-types": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "@solana/rpc-subscriptions": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/signers": "8.6.0", - "@solana/subscribable": "8.6.0", - "@solana/sysvars": "8.6.0", - "@solana/transaction-confirmation": "8.6.0", - "@solana/transaction-introspection": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/nominal-types": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/nominal-types/-/nominal-types-8.6.0.tgz", - "integrity": "sha512-uuRReiuEWfTTwtlJNvTSStuHrDF45Itl2k3BGg/4kHWxqUdtS5u4PK4bMgzoPWoyPorDj5y6TEMa+MydM5D7Sg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/offchain-messages": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/offchain-messages/-/offchain-messages-8.6.0.tgz", - "integrity": "sha512-VFic3fotmL9fIjs7Amk402CMWLeWwhNQvAF9cyZO++x42oU2FNeTe27rxfgFLYPaIHaRonlII+5pmsHQHA240Q==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-data-structures": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/nominal-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/options": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/options/-/options-8.6.0.tgz", - "integrity": "sha512-WFsTtIQukNGGHRImcmn8Se8o6A4vu4wY0fuLSeB/L7C45FPoQI2fTIud6hf9g2fum0dR3U0pFNIciwQjlVq2LA==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/codecs-core": "8.6.0", - "@solana/codecs-data-structures": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/plugin-core": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/plugin-core/-/plugin-core-8.6.0.tgz", - "integrity": "sha512-wvjpR66FreDxDXfF5RrIay7aXW+JfcmSj1TiDu+rUyWaV1Xu390E/KKL3dM6OfkIOtP66H9M9w1XihB8syMkfg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/plugin-interfaces": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/plugin-interfaces/-/plugin-interfaces-8.6.0.tgz", - "integrity": "sha512-ta+JYsKD7GMUoBLbeE1nYKDPN9nOwQN1y04xR4tbyfDbNsGLPz3fTKH8Y48bOs552sW4OcUB8F3pGVZefqPyWg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/accounts": "8.6.0", - "@solana/addresses": "8.6.0", - "@solana/instruction-plans": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/rpc-spec": "8.6.0", - "@solana/rpc-subscriptions-spec": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/signers": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/program-client-core": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/program-client-core/-/program-client-core-8.6.0.tgz", - "integrity": "sha512-e6Wx2Y2UrQ0dPB6hndVcyUXQwBt9/DLr8k2P7tRgW0JNVhHNylZQ6aYQAqxZzS8Z92gGz7l3XL+r9tCLKBkIVw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/accounts": "8.6.0", - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/instruction-plans": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/plugin-interfaces": "8.6.0", - "@solana/rpc-api": "8.6.0", - "@solana/signers": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/programs": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/programs/-/programs-8.6.0.tgz", - "integrity": "sha512-JKGtqXtiT4zon7xZkmys2G1/HchwbNjzbP+E+0Rp/Cko+svB9w9SE2PROEVJZS8UH98lbi1epjsHYAgESamwvg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/promises": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/promises/-/promises-8.6.0.tgz", - "integrity": "sha512-HLlAMwXnEyhg9HxVJGDlWgFlM4QUt/Qq0nL69bbC7COCHhUQFRcKLq5uIbaXPy7FNJlNBSTTCBZwI0IK9up0SQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc/-/rpc-8.6.0.tgz", - "integrity": "sha512-u5dg96ThDVAeklC9vtVpuYL7wRqkyolm++qYKd6yL7tPRdKZNxdGHbFHQR2qIcMQ0oVfEA9tGnQhplj+6Yt/0g==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/fast-stable-stringify": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/rpc-api": "8.6.0", - "@solana/rpc-spec": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "@solana/rpc-transformers": "8.6.0", - "@solana/rpc-transport-http": "8.6.0", - "@solana/rpc-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-api": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-api/-/rpc-api-8.6.0.tgz", - "integrity": "sha512-NFHtOB9z4HyV8frN84o+d9jKj5luRzrySZJLgwMgcG/Q2fWahTDrP+ZqRKLmqibvFBg/fwhcxl77+TfKZjpvhA==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/rpc-parsed-types": "8.6.0", - "@solana/rpc-spec": "8.6.0", - "@solana/rpc-transformers": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-parsed-types": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-parsed-types/-/rpc-parsed-types-8.6.0.tgz", - "integrity": "sha512-wZKtQOS3RdHZqJ3ycpdibup31tfbY6lHYGUKjmzeF6N2E2y7WEpB7qiEr9AMBB00mDUtorcqBMpOli6PyT4Gog==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-spec": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-spec/-/rpc-spec-8.6.0.tgz", - "integrity": "sha512-V1c+r6HXTb/nCEl5SHKLPzzb6aMEbr0lFOcgjEX8TQ8fE6ZlLzNz3tKvcgbBlOJCeyVXSrcNl3tv8i8xNp+n/g==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "@solana/subscribable": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-spec-types": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-spec-types/-/rpc-spec-types-8.6.0.tgz", - "integrity": "sha512-6+2F2BN2CXp4g7cnvLp2mRo/XwdN5At7f3HbdEablxNe1UvI5S8WIEY3l/Y+nh2NQIaEVz9fLjmTYV+UfZNzEg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-subscriptions": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions/-/rpc-subscriptions-8.6.0.tgz", - "integrity": "sha512-ZaoFtiKg25KqYykBslB8TDWqfm7S162FyTJvFI0HL0U94K1O675IG2h913mes3voatigpqLneFxkNrVs5yE7tA==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/fast-stable-stringify": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/promises": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "@solana/rpc-subscriptions-api": "8.6.0", - "@solana/rpc-subscriptions-channel-websocket": "8.6.0", - "@solana/rpc-subscriptions-spec": "8.6.0", - "@solana/rpc-transformers": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/subscribable": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-subscriptions-api": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-api/-/rpc-subscriptions-api-8.6.0.tgz", - "integrity": "sha512-Cbyi0ZpwNCcxRgjjc1vKVWBdwNOAKGT1VjryfQU/FDySUo2Lg8u5LUsJb6d53QD5dhEU+0nooxfBmRUUyebZug==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/rpc-subscriptions-spec": "8.6.0", - "@solana/rpc-transformers": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-subscriptions-channel-websocket": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-channel-websocket/-/rpc-subscriptions-channel-websocket-8.6.0.tgz", - "integrity": "sha512-k1UmMiIJFeo7wAUTiqg7Ni6gdsJAd65D3Wxqdtf5iBX9TjkvWGrL3KXdJq2ZzS1c9eqd220W0v7fkFTA8tfX5Q==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/rpc-subscriptions-spec": "8.6.0", - "@solana/subscribable": "8.6.0", - "ws": "^8.21.3" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-subscriptions-spec": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-subscriptions-spec/-/rpc-subscriptions-spec-8.6.0.tgz", - "integrity": "sha512-m7lBQS9hgzWN1ZI+JUy5rV8ctG7oy0WbGHoj4vevB4esK2SYUyI0eQB4GrQhVwGnkyTxATS/R91ZZzWYDKGXlg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/promises": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "@solana/subscribable": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-transformers": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-transformers/-/rpc-transformers-8.6.0.tgz", - "integrity": "sha512-aSfctQeLTszEQdNGDrPWbi/7voJYrYo/rvIZRDbokYQRDwMuphw7kENGdwaQB7A9XSX0tsPe+dKkbxjWf0Druw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/nominal-types": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "@solana/rpc-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-transport-http": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-transport-http/-/rpc-transport-http-8.6.0.tgz", - "integrity": "sha512-jr7ef/UOIO7bRjI7DEXji3J7nCFO3jIYPGw3L0fyF7VEJox9Bh8TNHsn9G9jv1kqdwkUnFrPPWVMvmAWQwSmvg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/rpc-spec": "8.6.0", - "@solana/rpc-spec-types": "8.6.0", - "undici-types": "^8.12.3" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/rpc-types": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/rpc-types/-/rpc-types-8.6.0.tgz", - "integrity": "sha512-gg05ZjZq8sFcf0JKO6/MQ1oYSFQuT5SU51dhirGjfl8UCxX/Q6ocsUgzb9a/zPNrRsXJkduaZF1bARah7MrrYw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/fixed-points": "8.6.0", - "@solana/nominal-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/signers": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/signers/-/signers-8.6.0.tgz", - "integrity": "sha512-q8FNQfGnMsHc7VLBhh+TwsMfodiYtYhoTqNj6lDIP2bz93l173rzcZWSRH/hg/7ksFdhHuV4nEkWj0L65N0S0Q==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/instruction-plans": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/nominal-types": "8.6.0", - "@solana/offchain-messages": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/subscribable": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/subscribable/-/subscribable-8.6.0.tgz", - "integrity": "sha512-z6qRloUTxoI459dUV2K/HQZO1HYuP5f6NQxXxd25TtM2TDpnjOzoO3pJAlOZP3cwXGgtGk6UWmMEY1a4j0TILw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/errors": "8.6.0", - "@solana/promises": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/sysvars": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/sysvars/-/sysvars-8.6.0.tgz", - "integrity": "sha512-oAIVThVcZr2qDwdvc3Fx+CKCbG1d4VwwRDXbu/tDKVDUIZXDWoTP//BX0u1FimkuirMHHW9Sl+AsSGFba0KPew==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/accounts": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-data-structures": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/rpc-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/transaction-confirmation": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/transaction-confirmation/-/transaction-confirmation-8.6.0.tgz", - "integrity": "sha512-kd7LwN1k6L+k9jXMjzm6KqGDuUsETZ1pWMnWY7ZT+1bDjRPbki/RylQc+2CIF7YYphT5GIloTmUziAAmhyw4eQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/promises": "8.6.0", - "@solana/rpc": "8.6.0", - "@solana/rpc-subscriptions": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/transaction-introspection": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/transaction-introspection/-/transaction-introspection-8.6.0.tgz", - "integrity": "sha512-/7MYRLnM7AF0983oaicjhvWWQEdeFgknBiKG5LVFd8WT68m5vL18d7/fZHkvsA41zWkIIrRVuh0PM4COeENNlQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/transaction-messages": "8.6.0", - "@solana/transactions": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/transaction-messages": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/transaction-messages/-/transaction-messages-8.6.0.tgz", - "integrity": "sha512-Zb7mB8Xu+AXaNiSmgghsyliGNoi7HO4hKdyQC0Qth4hW9QOBMdjSJ687KIUwsAzDSVXwdIbsnkUPpwCl1fcMdw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-data-structures": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/nominal-types": "8.6.0", - "@solana/rpc-types": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@solana/transactions": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/@solana/transactions/-/transactions-8.6.0.tgz", - "integrity": "sha512-m2i0dxDtB9mGqhJd714OQpKzGFp9cQbU80kwIBFflOrHdZ2cJzZ61xjGe+vegz/WGsqPec604pUbHKXXIFkNjg==", - "license": "MIT", - "optional": true, - "dependencies": { - "@solana/addresses": "8.6.0", - "@solana/codecs-core": "8.6.0", - "@solana/codecs-data-structures": "8.6.0", - "@solana/codecs-numbers": "8.6.0", - "@solana/codecs-strings": "8.6.0", - "@solana/errors": "8.6.0", - "@solana/functional": "8.6.0", - "@solana/instructions": "8.6.0", - "@solana/keys": "8.6.0", - "@solana/nominal-types": "8.6.0", - "@solana/rpc-types": "8.6.0", - "@solana/transaction-messages": "8.6.0" - }, - "engines": { - "node": ">=20.18.0" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@types/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", - "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "csstype": "^3.2.2" - } - }, - "node_modules/@types/trusted-types": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", - "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", - "license": "MIT" - }, - "node_modules/@wallet-standard/base": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@wallet-standard/base/-/base-1.1.1.tgz", - "integrity": "sha512-gggIHTtxicF9XFMQ12DkfS6NAG92Ak795JeSA7f2whAQ6Y3AkMWWuCMxSZXG2NIPN42kEaZSNVjqMsJRaJRxMQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=22" - } - }, - "node_modules/@wallet-standard/wallet": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@wallet-standard/wallet/-/wallet-1.1.0.tgz", - "integrity": "sha512-Gt8TnSlDZpAl+RWOOAB/kuvC7RpcdWAlFbHNoi4gsXsfaWa1QCT6LBcfIYTPdOZC9OVZUDwqGuGAcqZejDmHjg==", - "license": "Apache-2.0", - "dependencies": { - "@wallet-standard/base": "^1.1.0" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@walletconnect/core": { - "version": "2.23.9", - "resolved": "https://registry.npmjs.org/@walletconnect/core/-/core-2.23.9.tgz", - "integrity": "sha512-ws4WG8LeagUo2ERRo02HryXRcpwIRmCQ3pHLW5gWbVReLXXIpgk6ZAfID3fEGHevIwwnHSGww+nNhNpdXyiq0g==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/jsonrpc-ws-connection": "1.0.16", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.9", - "@walletconnect/utils": "2.23.9", - "@walletconnect/window-getters": "1.0.1", - "es-toolkit": "1.44.0", - "events": "3.3.0", - "uint8arrays": "3.1.1" - }, - "engines": { - "node": ">=18.20.8" - } - }, - "node_modules/@walletconnect/environment": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@walletconnect/environment/-/environment-1.0.1.tgz", - "integrity": "sha512-T426LLZtHj8e8rYnKfzsw1aG6+M0BT1ZxayMdv/p8yM0MU+eJDISqNY3/bccxRr4LrF9csq02Rhqt08Ibl0VRg==", - "license": "MIT", - "dependencies": { - "tslib": "1.14.1" - } - }, - "node_modules/@walletconnect/ethereum-provider": { - "version": "2.23.9", - "resolved": "https://registry.npmjs.org/@walletconnect/ethereum-provider/-/ethereum-provider-2.23.9.tgz", - "integrity": "sha512-Cb72KWl9S6mMs+c1MVGlSx07Dap1LFznYyWrg/XT5B8VtBKaH9Sw2lAvAL0ajGet6J5sq8sUx1pkg68tZwkqmA==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@reown/appkit": "1.8.17-wc-circular-dependencies-fix.0", - "@walletconnect/jsonrpc-http-connection": "1.0.8", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/sign-client": "2.23.9", - "@walletconnect/types": "2.23.9", - "@walletconnect/universal-provider": "2.23.9", - "@walletconnect/utils": "2.23.9", - "events": "3.3.0" - } - }, - "node_modules/@walletconnect/events": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@walletconnect/events/-/events-1.0.1.tgz", - "integrity": "sha512-NPTqaoi0oPBVNuLv7qPaJazmGHs5JGyO8eEAk5VGKmJzDR7AHzD4k6ilox5kxk1iwiOnFopBOOMLs86Oa76HpQ==", - "license": "MIT", - "dependencies": { - "keyvaluestorage-interface": "^1.0.0", - "tslib": "1.14.1" - } - }, - "node_modules/@walletconnect/heartbeat": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@walletconnect/heartbeat/-/heartbeat-1.2.2.tgz", - "integrity": "sha512-uASiRmC5MwhuRuf05vq4AT48Pq8RMi876zV8rr8cV969uTOzWdB/k+Lj5yI2PBtB1bGQisGen7MM1GcZlQTBXw==", - "license": "MIT", - "dependencies": { - "@walletconnect/events": "^1.0.1", - "@walletconnect/time": "^1.0.2", - "events": "^3.3.0" - } - }, - "node_modules/@walletconnect/jsonrpc-http-connection": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-http-connection/-/jsonrpc-http-connection-1.0.8.tgz", - "integrity": "sha512-+B7cRuaxijLeFDJUq5hAzNyef3e3tBDIxyaCNmFtjwnod5AGis3RToNqzFU33vpVcxFhofkpE7Cx+5MYejbMGw==", - "license": "MIT", - "dependencies": { - "@walletconnect/jsonrpc-utils": "^1.0.6", - "@walletconnect/safe-json": "^1.0.1", - "cross-fetch": "^3.1.4", - "events": "^3.3.0" - } - }, - "node_modules/@walletconnect/jsonrpc-provider": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-provider/-/jsonrpc-provider-1.0.14.tgz", - "integrity": "sha512-rtsNY1XqHvWj0EtITNeuf8PHMvlCLiS3EjQL+WOkxEOA4KPxsohFnBDeyPYiNm4ZvkQdLnece36opYidmtbmow==", - "license": "MIT", - "dependencies": { - "@walletconnect/jsonrpc-utils": "^1.0.8", - "@walletconnect/safe-json": "^1.0.2", - "events": "^3.3.0" - } - }, - "node_modules/@walletconnect/jsonrpc-types": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-types/-/jsonrpc-types-1.0.4.tgz", - "integrity": "sha512-P6679fG/M+wuWg9TY8mh6xFSdYnFyFjwFelxyISxMDrlbXokorEVXYOxiqEbrU3x1BmBoCAJJ+vtEaEoMlpCBQ==", - "license": "MIT", - "dependencies": { - "events": "^3.3.0", - "keyvaluestorage-interface": "^1.0.0" - } - }, - "node_modules/@walletconnect/jsonrpc-utils": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-utils/-/jsonrpc-utils-1.0.8.tgz", - "integrity": "sha512-vdeb03bD8VzJUL6ZtzRYsFMq1eZQcM3EAzT0a3st59dyLfJ0wq+tKMpmGH7HlB7waD858UWgfIcudbPFsbzVdw==", - "license": "MIT", - "dependencies": { - "@walletconnect/environment": "^1.0.1", - "@walletconnect/jsonrpc-types": "^1.0.3", - "tslib": "1.14.1" - } - }, - "node_modules/@walletconnect/jsonrpc-ws-connection": { - "version": "1.0.16", - "resolved": "https://registry.npmjs.org/@walletconnect/jsonrpc-ws-connection/-/jsonrpc-ws-connection-1.0.16.tgz", - "integrity": "sha512-G81JmsMqh5nJheE1mPst1W0WfVv0SG3N7JggwLLGnI7iuDZJq8cRJvQwLGKHn5H1WTW7DEPCo00zz5w62AbL3Q==", - "license": "MIT", - "dependencies": { - "@walletconnect/jsonrpc-utils": "^1.0.6", - "@walletconnect/safe-json": "^1.0.2", - "events": "^3.3.0", - "ws": "^7.5.1" - } - }, - "node_modules/@walletconnect/jsonrpc-ws-connection/node_modules/ws": { - "version": "7.5.13", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", - "integrity": "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA==", - "license": "MIT", - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/@walletconnect/keyvaluestorage": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@walletconnect/keyvaluestorage/-/keyvaluestorage-1.1.1.tgz", - "integrity": "sha512-V7ZQq2+mSxAq7MrRqDxanTzu2RcElfK1PfNYiaVnJgJ7Q7G7hTVwF8voIBx92qsRyGHZihrwNPHuZd1aKkd0rA==", - "license": "MIT", - "dependencies": { - "@walletconnect/safe-json": "^1.0.1", - "idb-keyval": "^6.2.1", - "unstorage": "^1.9.0" - }, - "peerDependencies": { - "@react-native-async-storage/async-storage": "1.x" - }, - "peerDependenciesMeta": { - "@react-native-async-storage/async-storage": { - "optional": true - } - } - }, - "node_modules/@walletconnect/logger": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@walletconnect/logger/-/logger-3.0.2.tgz", - "integrity": "sha512-7wR3wAwJTOmX4gbcUZcFMov8fjftY05+5cO/d4cpDD8wDzJ+cIlKdYOXaXfxHLSYeDazMXIsxMYjHYVDfkx+nA==", - "license": "MIT", - "dependencies": { - "@walletconnect/safe-json": "^1.0.2", - "pino": "10.0.0" - } - }, - "node_modules/@walletconnect/relay-api": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@walletconnect/relay-api/-/relay-api-1.0.11.tgz", - "integrity": "sha512-tLPErkze/HmC9aCmdZOhtVmYZq1wKfWTJtygQHoWtgg722Jd4homo54Cs4ak2RUFUZIGO2RsOpIcWipaua5D5Q==", - "license": "MIT", - "dependencies": { - "@walletconnect/jsonrpc-types": "^1.0.2" - } - }, - "node_modules/@walletconnect/relay-auth": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@walletconnect/relay-auth/-/relay-auth-1.1.0.tgz", - "integrity": "sha512-qFw+a9uRz26jRCDgL7Q5TA9qYIgcNY8jpJzI1zAWNZ8i7mQjaijRnWFKsCHAU9CyGjvt6RKrRXyFtFOpWTVmCQ==", - "license": "MIT", - "dependencies": { - "@noble/curves": "1.8.0", - "@noble/hashes": "1.7.0", - "@walletconnect/safe-json": "^1.0.1", - "@walletconnect/time": "^1.0.2", - "uint8arrays": "^3.0.0" - } - }, - "node_modules/@walletconnect/relay-auth/node_modules/@noble/hashes": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.7.0.tgz", - "integrity": "sha512-HXydb0DgzTpDPwbVeDGCG1gIu7X6+AuU6Zl6av/E/KG8LMsvPntvq+w17CHRpKBmN6Ybdrt1eP3k4cj8DJa78w==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@walletconnect/safe-json": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@walletconnect/safe-json/-/safe-json-1.0.2.tgz", - "integrity": "sha512-Ogb7I27kZ3LPC3ibn8ldyUr5544t3/STow9+lzz7Sfo808YD7SBWk7SAsdBFlYgP2zDRy2hS3sKRcuSRM0OTmA==", - "license": "MIT", - "dependencies": { - "tslib": "1.14.1" - } - }, - "node_modules/@walletconnect/sign-client": { - "version": "2.23.9", - "resolved": "https://registry.npmjs.org/@walletconnect/sign-client/-/sign-client-2.23.9.tgz", - "integrity": "sha512-Xj+hw4E6mGRyhCdVOT/RMgnG+up/Y3v0ho5PlkVozvXWeVSqHNh9DmjLuU97a7OACoGd/oHBF6g3NVqD7MgCMQ==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/core": "2.23.9", - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/logger": "3.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.9", - "@walletconnect/utils": "2.23.9", - "events": "3.3.0" - } - }, - "node_modules/@walletconnect/time": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@walletconnect/time/-/time-1.0.2.tgz", - "integrity": "sha512-uzdd9woDcJ1AaBZRhqy5rNC9laqWGErfc4dxA9a87mPdKOgWMD85mcFo9dIYIts/Jwocfwn07EC6EzclKubk/g==", - "license": "MIT", - "dependencies": { - "tslib": "1.14.1" - } - }, - "node_modules/@walletconnect/types": { - "version": "2.23.9", - "resolved": "https://registry.npmjs.org/@walletconnect/types/-/types-2.23.9.tgz", - "integrity": "sha512-IUl1PpD/Dig8IE2OZ9XtjbPohEyOZJ73xs92EDUzoIyzRtfm36g2D340pY3iu3AAdLv1yFiaZafB8Hf8RFze8A==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/heartbeat": "1.2.2", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "events": "3.3.0" - } - }, - "node_modules/@walletconnect/universal-provider": { - "version": "2.23.9", - "resolved": "https://registry.npmjs.org/@walletconnect/universal-provider/-/universal-provider-2.23.9.tgz", - "integrity": "sha512-dNk6X1USUcIX1nx3H61V3pO15E/2ejyeBsKLBOo8YXrnYCrKGG/KB1LIqJXHpQlXT+9bJE9cOnn61ETdCXgkPw==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@walletconnect/events": "1.0.1", - "@walletconnect/jsonrpc-http-connection": "1.0.8", - "@walletconnect/jsonrpc-provider": "1.0.14", - "@walletconnect/jsonrpc-types": "1.0.4", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/sign-client": "2.23.9", - "@walletconnect/types": "2.23.9", - "@walletconnect/utils": "2.23.9", - "es-toolkit": "1.44.0", - "events": "3.3.0" - } - }, - "node_modules/@walletconnect/utils": { - "version": "2.23.9", - "resolved": "https://registry.npmjs.org/@walletconnect/utils/-/utils-2.23.9.tgz", - "integrity": "sha512-C5TltCs8UPypNiteYnKSv8+ZDK2EjVDyXCxN6kA9bkA+j6KGsNIV7l9MUA8WBAvE5Gi5EcBdhD3R9Hpo/1HHqQ==", - "license": "SEE LICENSE IN LICENSE.md", - "dependencies": { - "@msgpack/msgpack": "3.1.3", - "@noble/ciphers": "1.3.0", - "@noble/curves": "1.9.7", - "@noble/hashes": "1.8.0", - "@scure/base": "1.2.6", - "@walletconnect/jsonrpc-utils": "1.0.8", - "@walletconnect/keyvaluestorage": "1.1.1", - "@walletconnect/logger": "3.0.2", - "@walletconnect/relay-api": "1.0.11", - "@walletconnect/relay-auth": "1.1.0", - "@walletconnect/safe-json": "1.0.2", - "@walletconnect/time": "1.0.2", - "@walletconnect/types": "2.23.9", - "@walletconnect/window-getters": "1.0.1", - "@walletconnect/window-metadata": "1.0.1", - "blakejs": "1.2.1", - "detect-browser": "5.3.0", - "ox": "0.9.3", - "uint8arrays": "3.1.1" - } - }, - "node_modules/@walletconnect/utils/node_modules/@noble/curves": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", - "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@walletconnect/utils/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@walletconnect/utils/node_modules/abitype": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.3.0.tgz", - "integrity": "sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/wevm" - }, - "peerDependencies": { - "typescript": ">=5.0.4", - "zod": "^3.22.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - }, - "zod": { - "optional": true - } - } - }, - "node_modules/@walletconnect/utils/node_modules/ox": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/ox/-/ox-0.9.3.tgz", - "integrity": "sha512-KzyJP+fPV4uhuuqrTZyok4DC7vFzi7HLUFiUNEmpbyh59htKWkOC98IONC1zgXJPbHAhQgqs6B0Z6StCGhmQvg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "^1.11.0", - "@noble/ciphers": "^1.3.0", - "@noble/curves": "1.9.1", - "@noble/hashes": "^1.8.0", - "@scure/bip32": "^1.7.0", - "@scure/bip39": "^1.6.0", - "abitype": "^1.0.9", - "eventemitter3": "5.0.1" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@walletconnect/utils/node_modules/ox/node_modules/@noble/curves": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", - "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@walletconnect/window-getters": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@walletconnect/window-getters/-/window-getters-1.0.1.tgz", - "integrity": "sha512-vHp+HqzGxORPAN8gY03qnbTMnhqIwjeRJNOMOAzePRg4xVEEE2WvYsI9G2NMjOknA8hnuYbU3/hwLcKbjhc8+Q==", - "license": "MIT", - "dependencies": { - "tslib": "1.14.1" - } - }, - "node_modules/@walletconnect/window-metadata": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@walletconnect/window-metadata/-/window-metadata-1.0.1.tgz", - "integrity": "sha512-9koTqyGrM2cqFRW517BPY/iEtUDx2r1+Pwwu5m7sJ7ka79wi3EyqhqcICk/yDmv6jAS1rjKgTKXlEhanYjijcA==", - "license": "MIT", - "dependencies": { - "@walletconnect/window-getters": "^1.0.1", - "tslib": "1.14.1" - } - }, - "node_modules/abitype": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.0.6.tgz", - "integrity": "sha512-MMSqYh4+C/aVqI2RQaWqbvI4Kxo5cQV40WQ4QFtDnNzCkqChm8MuENhElmynZlO0qUy/ObkEUaXtKqYnx1Kp3A==", - "license": "MIT", - "optional": true, - "funding": { - "url": "https://github.com/sponsors/wevm" - }, - "peerDependencies": { - "typescript": ">=5.0.4", - "zod": "^3 >=3.22.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - }, - "zod": { - "optional": true - } - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "license": "MIT", - "optional": true - }, - "node_modules/atomic-sleep": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", - "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", - "license": "MIT", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/axios": { - "version": "1.21.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.21.1.tgz", - "integrity": "sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "follow-redirects": "^1.16.2", - "form-data": "^4.0.6", - "https-proxy-agent": "^5.0.1", - "proxy-from-env": "^2.1.0" - } - }, - "node_modules/axios-retry": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-4.5.0.tgz", - "integrity": "sha512-aR99oXhpEDGo0UuAlYcn2iGRds30k366Zfa05XWScR9QaQD4JYiP3/1Qt1u7YlefUOK+cn0CcwoL1oefavQUlQ==", - "deprecated": "axios-retry is no longer maintained. See https://github.com/softonic/axios-retry for alternatives.", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "is-retry-allowed": "^2.2.0" - }, - "peerDependencies": { - "axios": "0.x || 1.x" - } - }, - "node_modules/base-x": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz", - "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==", - "license": "MIT" - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/big.js": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/big.js/-/big.js-6.2.2.tgz", - "integrity": "sha512-y/ie+Faknx7sZA5MfGA2xKlu0GDv8RWrXGsmlteyJQ2lvoKv9GBK/fpRMc2qlSoBAgNxrixICFCBefIq8WCQpQ==", - "license": "MIT", - "engines": { - "node": "*" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/bigjs" - } - }, - "node_modules/blakejs": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/blakejs/-/blakejs-1.2.1.tgz", - "integrity": "sha512-QXUSXI3QVc/gJME0dBpXrag1kbzOqCjCX8/b54ntNyW6sjtoqxqRk3LTmXzaJoh71zMsDCjM+47jS7XiwN/+fQ==", - "license": "MIT" - }, - "node_modules/bs58": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", - "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", - "license": "MIT", - "dependencies": { - "base-x": "^5.0.0" - } - }, - "node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/chalk": { - "version": "5.6.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", - "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", - "license": "MIT", - "optional": true, - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/charenc": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", - "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", - "license": "BSD-3-Clause", - "optional": true, - "engines": { - "node": "*" - } - }, - "node_modules/chokidar": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", - "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", - "license": "MIT", - "dependencies": { - "readdirp": "^5.0.0" - }, - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/cliui": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", - "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^6.2.0" - } - }, - "node_modules/clsx": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", - "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "license": "MIT", - "optional": true, - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/commander": { - "version": "15.0.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", - "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=22.12.0" - } - }, - "node_modules/cookie-es": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-1.2.3.tgz", - "integrity": "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw==", - "license": "MIT" - }, - "node_modules/cross-fetch": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.2.0.tgz", - "integrity": "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==", - "license": "MIT", - "dependencies": { - "node-fetch": "^2.7.0" - } - }, - "node_modules/crossws": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/crossws/-/crossws-0.3.5.tgz", - "integrity": "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==", - "license": "MIT", - "dependencies": { - "uncrypto": "^0.1.3" - } - }, - "node_modules/crypt": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", - "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", - "license": "BSD-3-Clause", - "optional": true, - "engines": { - "node": "*" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "license": "MIT", - "optional": true, - "peer": true - }, - "node_modules/dayjs": { - "version": "1.11.13", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", - "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==", - "license": "MIT" - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "optional": true, - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decamelize": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", - "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/defu": { - "version": "6.1.7", - "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", - "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", - "license": "MIT" - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/destr": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", - "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", - "license": "MIT" - }, - "node_modules/detect-browser": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/detect-browser/-/detect-browser-5.3.0.tgz", - "integrity": "sha512-53rsFbGdwMwlF7qvCt0ypLM5V5/Mbl0szB7GPN8y9NCcbknYOeVVXdrXEq+90IwAfrrzt6Hd+u2E2ntakICU8w==", - "license": "MIT" - }, - "node_modules/dijkstrajs": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", - "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", - "license": "MIT" - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "optional": true, - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "license": "MIT" - }, - "node_modules/encode-utf8": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/encode-utf8/-/encode-utf8-1.0.3.tgz", - "integrity": "sha512-ucAnuBEhUK4boH2HjVYG5Q2mQyPorvv0u/ocS+zhdw0S8AlHYY+GOFhP1Gio5z4icpP2ivFSvhtFjQi8+T9ppw==", - "license": "MIT" - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", - "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", - "license": "MIT", - "optional": true, - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "license": "MIT", - "optional": true, - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-toolkit": { - "version": "1.44.0", - "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.44.0.tgz", - "integrity": "sha512-6penXeZalaV88MM3cGkFZZfOoLGWshWWfdy0tWw/RlVVyhvMaWSBTOvXNeiW3e5FwdS5ePW0LGEu17zT139ktg==", - "license": "MIT", - "workspaces": [ - "docs", - "benchmarks" - ] - }, - "node_modules/esbuild": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", - "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.0", - "@esbuild/android-arm": "0.28.0", - "@esbuild/android-arm64": "0.28.0", - "@esbuild/android-x64": "0.28.0", - "@esbuild/darwin-arm64": "0.28.0", - "@esbuild/darwin-x64": "0.28.0", - "@esbuild/freebsd-arm64": "0.28.0", - "@esbuild/freebsd-x64": "0.28.0", - "@esbuild/linux-arm": "0.28.0", - "@esbuild/linux-arm64": "0.28.0", - "@esbuild/linux-ia32": "0.28.0", - "@esbuild/linux-loong64": "0.28.0", - "@esbuild/linux-mips64el": "0.28.0", - "@esbuild/linux-ppc64": "0.28.0", - "@esbuild/linux-riscv64": "0.28.0", - "@esbuild/linux-s390x": "0.28.0", - "@esbuild/linux-x64": "0.28.0", - "@esbuild/netbsd-arm64": "0.28.0", - "@esbuild/netbsd-x64": "0.28.0", - "@esbuild/openbsd-arm64": "0.28.0", - "@esbuild/openbsd-x64": "0.28.0", - "@esbuild/openharmony-arm64": "0.28.0", - "@esbuild/sunos-x64": "0.28.0", - "@esbuild/win32-arm64": "0.28.0", - "@esbuild/win32-ia32": "0.28.0", - "@esbuild/win32-x64": "0.28.0" - } - }, - "node_modules/eventemitter3": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", - "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", - "license": "MIT" - }, - "node_modules/events": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", - "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", - "license": "MIT", - "engines": { - "node": ">=0.8.x" - } - }, - "node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "license": "MIT", - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/follow-redirects": { - "version": "1.16.3", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", - "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "optional": true, - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/form-data": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", - "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.4", - "mime-types": "^2.1.35" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "optional": true, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "optional": true, - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/h3": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.11.tgz", - "integrity": "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==", - "license": "MIT", - "dependencies": { - "cookie-es": "^1.2.3", - "crossws": "^0.3.5", - "defu": "^6.1.6", - "destr": "^2.0.5", - "iron-webcrypto": "^1.2.1", - "node-mock-http": "^1.0.4", - "radix3": "^1.1.2", - "ufo": "^1.6.3", - "uncrypto": "^0.1.3" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "license": "MIT", - "optional": true, - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "license": "MIT", - "optional": true, - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "license": "MIT", - "optional": true, - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/idb-keyval": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/idb-keyval/-/idb-keyval-6.2.1.tgz", - "integrity": "sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==", - "license": "Apache-2.0" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/iron-webcrypto": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz", - "integrity": "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/brc-dd" - } - }, - "node_modules/is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "license": "MIT", - "optional": true - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-retry-allowed": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-2.2.0.tgz", - "integrity": "sha512-XVm7LOeLpTW4jV19QSH38vkswxoLud8sQ57YwJVTPWdiaI9I8keEhGFpBlslyVsgdQy4Opg8QOLb8YRgsyZiQg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isows": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", - "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "peerDependencies": { - "ws": "*" - } - }, - "node_modules/jose": { - "version": "6.2.17", - "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", - "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", - "license": "MIT", - "optional": true, - "funding": { - "url": "https://github.com/sponsors/panva" - } - }, - "node_modules/keyvaluestorage-interface": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/keyvaluestorage-interface/-/keyvaluestorage-interface-1.0.0.tgz", - "integrity": "sha512-8t6Q3TclQ4uZynJY9IGr2+SsIGwK9JHcO6ootkHCGA0CrQCRy+VkouYNO2xicET6b9al7QKzpebNow+gkpCL8g==", - "license": "MIT" - }, - "node_modules/lit": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.0.tgz", - "integrity": "sha512-DGVsqsOIHBww2DqnuZzW7QsuCdahp50ojuDaBPC7jUDRpYoH0z7kHBBYZewRzer75FwtrkmkKk7iOAwSaWdBmw==", - "license": "BSD-3-Clause", - "dependencies": { - "@lit/reactive-element": "^2.1.0", - "lit-element": "^4.2.0", - "lit-html": "^3.3.0" - } - }, - "node_modules/lit-element": { - "version": "4.2.2", - "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz", - "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==", - "license": "BSD-3-Clause", - "dependencies": { - "@lit-labs/ssr-dom-shim": "^1.5.0", - "@lit/reactive-element": "^2.1.0", - "lit-html": "^3.3.0" - } - }, - "node_modules/lit-html": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz", - "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==", - "license": "BSD-3-Clause", - "dependencies": { - "@types/trusted-types": "^2.0.2" - } - }, - "node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "license": "MIT", - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/md5": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", - "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "charenc": "0.0.2", - "crypt": "0.0.2", - "is-buffer": "~1.1.6" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "optional": true, - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT", - "optional": true - }, - "node_modules/multiformats": { - "version": "9.9.0", - "resolved": "https://registry.npmjs.org/multiformats/-/multiformats-9.9.0.tgz", - "integrity": "sha512-HoMUjhH9T8DDBNT+6xzkrd9ga/XiBI4xLr58LJACwK6G3HTOPeMz4nB4KJs33L2BelrIJa7P0VuNaVF3hMYfjg==", - "license": "(Apache-2.0 AND MIT)" - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-fetch-native": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", - "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", - "license": "MIT" - }, - "node_modules/node-mock-http": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.5.tgz", - "integrity": "sha512-KQyt/wLjG3TAc7DOUhpqWzgd4ERxR80JOlTK5VE5R1S12IaPVN5qkj4klBce9HPG1Njuup4Sb5bljaT34lIyjw==", - "license": "MIT" - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ofetch": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/ofetch/-/ofetch-1.5.1.tgz", - "integrity": "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==", - "license": "MIT", - "dependencies": { - "destr": "^2.0.5", - "node-fetch-native": "^1.6.7", - "ufo": "^1.6.1" - } - }, - "node_modules/on-exit-leak-free": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", - "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/ox": { - "version": "0.6.9", - "resolved": "https://registry.npmjs.org/ox/-/ox-0.6.9.tgz", - "integrity": "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "optional": true, - "dependencies": { - "@adraffy/ens-normalize": "^1.10.1", - "@noble/curves": "^1.6.0", - "@noble/hashes": "^1.5.0", - "@scure/bip32": "^1.5.0", - "@scure/bip39": "^1.4.0", - "abitype": "^1.0.6", - "eventemitter3": "5.0.1" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/ox/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "optional": true, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "license": "MIT", - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "license": "MIT", - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pino": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/pino/-/pino-10.0.0.tgz", - "integrity": "sha512-eI9pKwWEix40kfvSzqEP6ldqOoBIN7dwD/o91TY5z8vQI12sAffpR/pOqAD1IVVwIVHDpHjkq0joBPdJD0rafA==", - "license": "MIT", - "dependencies": { - "atomic-sleep": "^1.0.0", - "on-exit-leak-free": "^2.1.0", - "pino-abstract-transport": "^2.0.0", - "pino-std-serializers": "^7.0.0", - "process-warning": "^5.0.0", - "quick-format-unescaped": "^4.0.3", - "real-require": "^0.2.0", - "safe-stable-stringify": "^2.3.1", - "slow-redact": "^0.3.0", - "sonic-boom": "^4.0.1", - "thread-stream": "^3.0.0" - }, - "bin": { - "pino": "bin.js" - } - }, - "node_modules/pino-abstract-transport": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", - "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", - "license": "MIT", - "dependencies": { - "split2": "^4.0.0" - } - }, - "node_modules/pino-std-serializers": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", - "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", - "license": "MIT" - }, - "node_modules/pngjs": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", - "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", - "license": "MIT", - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/preact": { - "version": "10.24.2", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.24.2.tgz", - "integrity": "sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==", - "license": "MIT", - "optional": true, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/preact" - } - }, - "node_modules/process-warning": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", - "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/proxy-compare": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/proxy-compare/-/proxy-compare-3.0.1.tgz", - "integrity": "sha512-V9plBAt3qjMlS1+nC8771KNf6oJ12gExvaxnNzN/9yVRLdTv/lc+oJlnSzrdYDAvBfTStPCoiaCOTmTs0adv7Q==", - "license": "MIT" - }, - "node_modules/proxy-from-env": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", - "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/qrcode": { - "version": "1.5.4", - "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", - "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", - "license": "MIT", - "dependencies": { - "dijkstrajs": "^1.0.1", - "pngjs": "^5.0.0", - "yargs": "^15.3.1" - }, - "bin": { - "qrcode": "bin/qrcode" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/quick-format-unescaped": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", - "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", - "license": "MIT" - }, - "node_modules/radix3": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/radix3/-/radix3-1.1.2.tgz", - "integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==", - "license": "MIT" - }, - "node_modules/readdirp": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", - "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", - "license": "MIT", - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/real-require": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", - "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", - "license": "MIT", - "engines": { - "node": ">= 12.13.0" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/require-main-filename": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", - "license": "ISC" - }, - "node_modules/safe-stable-stringify": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", - "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/semver": { - "version": "7.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", - "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", - "license": "ISC" - }, - "node_modules/slow-redact": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/slow-redact/-/slow-redact-0.3.2.tgz", - "integrity": "sha512-MseHyi2+E/hBRqdOi5COy6wZ7j7DxXRz9NkseavNYSvvWC06D8a5cidVZX3tcG5eCW3NIyVU4zT63hw0Q486jw==", - "license": "MIT" - }, - "node_modules/sonic-boom": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", - "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", - "license": "MIT", - "dependencies": { - "atomic-sleep": "^1.0.0" - } - }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/thread-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz", - "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==", - "license": "MIT", - "dependencies": { - "real-require": "^0.2.0" - } - }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT" - }, - "node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "license": "0BSD" - }, - "node_modules/ufo": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", - "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", - "license": "MIT" - }, - "node_modules/uint8arrays": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/uint8arrays/-/uint8arrays-3.1.1.tgz", - "integrity": "sha512-+QJa8QRnbdXVpHYjLoTpJIdCTiw9Ir62nocClWuXIq2JIh4Uta0cQsTSpFL678p2CN8B+XSApwcU+pQEqVpKWg==", - "license": "MIT", - "dependencies": { - "multiformats": "^9.4.2" - } - }, - "node_modules/uncrypto": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz", - "integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==", - "license": "MIT" - }, - "node_modules/undici-types": { - "version": "8.12.4", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.12.4.tgz", - "integrity": "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ==", - "license": "MIT", - "optional": true - }, - "node_modules/unstorage": { - "version": "1.17.6", - "resolved": "https://registry.npmjs.org/unstorage/-/unstorage-1.17.6.tgz", - "integrity": "sha512-gjKtcmn/KwZuJZO9o2sc0esAQnhmTw0LviDHwevTXbJMYs0dRTp8ZEEWXHU0vTpzbN3cA0yxlTeyXssMp3zDqw==", - "license": "MIT", - "dependencies": { - "anymatch": "^3.1.3", - "chokidar": "^5.0.0", - "destr": "^2.0.5", - "h3": "^1.15.11", - "lru-cache": "^11.5.3", - "node-fetch-native": "^1.6.7", - "ofetch": "^1.5.1", - "ufo": "^1.6.4" - }, - "peerDependencies": { - "@azure/app-configuration": "^1.8.0", - "@azure/cosmos": "^4.2.0", - "@azure/data-tables": "^13.3.0", - "@azure/identity": "^4.6.0", - "@azure/keyvault-secrets": "^4.9.0", - "@azure/storage-blob": "^12.26.0", - "@capacitor/preferences": "^6 || ^7 || ^8", - "@deno/kv": ">=0.9.0", - "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0 || ^11.0.0", - "@planetscale/database": "^1.19.0", - "@upstash/redis": "^1.34.3", - "@vercel/blob": ">=0.27.1", - "@vercel/functions": "^2.2.12 || ^3.0.0", - "@vercel/kv": "^1 || ^2 || ^3", - "aws4fetch": "^1.0.20", - "db0": ">=0.2.1", - "idb-keyval": "^6.2.1", - "ioredis": "^5.4.2", - "uploadthing": "^7.4.4" - }, - "peerDependenciesMeta": { - "@azure/app-configuration": { - "optional": true - }, - "@azure/cosmos": { - "optional": true - }, - "@azure/data-tables": { - "optional": true - }, - "@azure/identity": { - "optional": true - }, - "@azure/keyvault-secrets": { - "optional": true - }, - "@azure/storage-blob": { - "optional": true - }, - "@capacitor/preferences": { - "optional": true - }, - "@deno/kv": { - "optional": true - }, - "@netlify/blobs": { - "optional": true - }, - "@planetscale/database": { - "optional": true - }, - "@upstash/redis": { - "optional": true - }, - "@vercel/blob": { - "optional": true - }, - "@vercel/functions": { - "optional": true - }, - "@vercel/kv": { - "optional": true - }, - "aws4fetch": { - "optional": true - }, - "db0": { - "optional": true - }, - "idb-keyval": { - "optional": true - }, - "ioredis": { - "optional": true - }, - "uploadthing": { - "optional": true - } - } - }, - "node_modules/valtio": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/valtio/-/valtio-2.1.7.tgz", - "integrity": "sha512-DwJhCDpujuQuKdJ2H84VbTjEJJteaSmqsuUltsfbfdbotVfNeTE4K/qc/Wi57I9x8/2ed4JNdjEna7O6PfavRg==", - "license": "MIT", - "dependencies": { - "proxy-compare": "^3.0.1" - }, - "engines": { - "node": ">=12.20.0" - }, - "peerDependencies": { - "@types/react": ">=18.0.0", - "react": ">=18.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "react": { - "optional": true - } - } - }, - "node_modules/viem": { - "version": "2.57.19", - "resolved": "https://registry.npmjs.org/viem/-/viem-2.57.19.tgz", - "integrity": "sha512-ULAHSwef42oL1reV41Os40iR34PF9BFNIX/RBapHLAJL1X6VmrgQikS4q4ulZ7/8GqlFLqrRI5GoNms3hcxsHw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "dependencies": { - "@noble/curves": "1.9.1", - "@noble/hashes": "1.8.0", - "@scure/bip32": "1.7.0", - "@scure/bip39": "1.6.0", - "abitype": "1.2.3", - "isows": "1.0.7", - "ox": "0.14.65", - "ws": "8.21.0" - }, - "peerDependencies": { - "mppx": ">=0.17.0", - "typescript": ">=5.0.4" - }, - "peerDependenciesMeta": { - "mppx": { - "optional": true - }, - "typescript": { - "optional": true - } - } - }, - "node_modules/viem/node_modules/@noble/curves": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", - "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/viem/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/viem/node_modules/abitype": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz", - "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/wevm" - }, - "peerDependencies": { - "typescript": ">=5.0.4", - "zod": "^3.22.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - }, - "zod": { - "optional": true - } - } - }, - "node_modules/viem/node_modules/ox": { - "version": "0.14.65", - "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.65.tgz", - "integrity": "sha512-K7oj+jvEP4Gf78ZOYuWAWzKEX/g5z7p6ukj84gdbFnezmFSt6SpprEp9tH5tymXsywSqRdeqk+8JL4+9o0Schw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/wevm" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "^1.11.0", - "@noble/ciphers": "^1.3.0", - "@noble/curves": "1.9.1", - "@noble/hashes": "^1.8.0", - "@scure/bip32": "^1.7.0", - "@scure/bip39": "^1.6.0", - "abitype": "^1.2.3", - "eventemitter3": "5.0.1" - }, - "peerDependencies": { - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/viem/node_modules/ws": { - "version": "8.21.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", - "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause" - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/which-module": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", - "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", - "license": "ISC" - }, - "node_modules/wrap-ansi": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", - "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/ws": { - "version": "8.22.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", - "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/y18n": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", - "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", - "license": "ISC" - }, - "node_modules/yargs": { - "version": "15.4.1", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", - "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", - "license": "MIT", - "dependencies": { - "cliui": "^6.0.0", - "decamelize": "^1.2.0", - "find-up": "^4.1.0", - "get-caller-file": "^2.0.1", - "require-directory": "^2.1.1", - "require-main-filename": "^2.0.0", - "set-blocking": "^2.0.0", - "string-width": "^4.2.0", - "which-module": "^2.0.0", - "y18n": "^4.0.0", - "yargs-parser": "^18.1.2" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs-parser": { - "version": "18.1.3", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", - "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", - "license": "ISC", - "dependencies": { - "camelcase": "^5.0.0", - "decamelize": "^1.2.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", - "license": "MIT", - "optional": true, - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/zustand": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.3.tgz", - "integrity": "sha512-14fwWQtU3pH4dE0dOpdMiWjddcH+QzKIgk1cl8epwSE7yag43k/AD/m4L6+K7DytAOr9gGBe3/EXj9g7cdostg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=12.20.0" - }, - "peerDependencies": { - "@types/react": ">=18.0.0", - "immer": ">=9.0.6", - "react": ">=18.0.0", - "use-sync-external-store": ">=1.2.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "immer": { - "optional": true - }, - "react": { - "optional": true - }, - "use-sync-external-store": { - "optional": true - } - } - } - } -} diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 2d7757765..0fde4711d 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -244,48 +244,55 @@ storage, and signed runtime audit scaffolding. An approval that expires before managed signing or external handoff completion fails closed instead of becoming a stale signing authority. -WalletConnect is a dedicated connector capsule (`wallet-walletconnect`). -`wallet-provider` owns proof verification, linked accounts, approval state, -receipts, and audit. The connector presents the account and approval controls; -trusted Home hosts the reviewed Reown EVM provider and bundled QR renderer. -Mode A connects external wallets to sign Runtime challenges and approved -requests. Mode B, where external dApps use ElastOS as a WalletConnect wallet, -requires its own security decision. Internal capsules enter the private typed -Wallet Bus through verified Runtime authority. - -Runtime keeps the SDK key/value store in private files selected by the verified -principal. Trusted Home combines its own authority with the carried connector -launch token to use storage and obtain a short-lived, single-use relay admission. -An opaque capsule cannot read pairing keys or publish encrypted signing requests. -Home accepts link actions, approval IDs, and disconnect actions; Runtime and -`wallet-provider` supply the exact proof or signing payload. Pairing carries -connection state. Each signing request retains its principal, requesting actor, -account, chain, payload hash, and expiry. Disconnect leaves linked accounts in -Wallet. Account or chain changes stop a request before the wallet sends it. -Home passes each returned transaction hash to Runtime once, including after a -connection or account change. A completion error keeps that hash visible so the -person can check the transaction before sending again. Unused signatures and -ownership proofs still stop when the account, chain, or request expiry changes. - -The opaque-frame SDK qualification test uses capsule-local -`walletconnect-storage.mjs` for browser Storage compatibility. Its non-protocol -memory supports UI preferences, such as wallet and network choice, and resets -on reload. -The Runtime adapter owns sessions, pairings and cryptographic keys. The memory -store raises `SecurityError` for WalletConnect protocol and keychain names. -The focused native-Storage comparison runs in Chromium and WebKit with -`node --test scripts/walletconnect-storage-smoke.mjs`; the source gateway test -`content_sandbox_browser_walletconnect_sdk` checks the same SDK under capsule -CSP and sandbox headers. This test uses a deterministic relay and key/value -adapter; a paired reconnect requires the separate real-relay journey. - -Inbox owns internet consent through the owner's passkey. Runtime connects only -to `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through -the existing local Exit. Runtime authenticates relay TLS, limits frame size and -sockets per principal, sends heartbeats, and expires idle connections. Turn Off -cancels handshakes and open sockets. Reopening the connector restores the SDK's -principal-scoped state and reconnects while consent and Home authority remain -valid. Hosted Carrier Exit selection remains a separate integration. +WalletConnect is a dedicated connector capsule (`wallet-walletconnect`). The +reviewed Reown SDK and its bundled QR renderer run only in that capsule's opaque +sandboxed frame. `wallet-provider` owns proof verification, linked accounts, +approval state and receipts. Runtime accepts the connector's own live launch +capability, bound to its principal, session and launch instance, for storage, +relay admission, linking and signing handoffs. Home owns window orchestration. + +Mode A connects a phone wallet to sign Runtime challenges and approved requests. +Mode B, where external dApps use ElastOS as a WalletConnect wallet, requires its +own security decision. The phone holds signing keys and confirms each request. +Isolation protects Home. A compromised SDK still holds its pairing session and +could ask the phone to sign a different request; the phone's confirmation is the +last guard. Signup and sign-in remain candidates for the separate first-run +authority decision. + +Runtime supplies the exact principal, requesting actor, account, chain, payload +hash and expiry. It checks pending state before handing off once, and checks the +approved request and hash before completion. A closed connector window leaves an +approved, unfinished transaction visible with "Check your phone wallet". Opening +it again supplies recovery instructions and keeps the send control disabled. +A returned transaction hash is passed to Runtime once even if the account, +network or expiry changed during the phone prompt. A completion error keeps the +hash visible for checking before another send. Unused signatures and ownership +proofs stop when their account, network or expiry changes. + +The capsule installs `walletconnect-storage.mjs` before importing the pinned SDK. +Browser Storage holds UI preferences in memory and resets on reload. Protocol +and keychain names raise `SecurityError` there. Runtime's private key/value store +holds pairings, sessions and cryptographic keys, selected by the verified +principal. The SDK uses the constant context `wallet-walletconnect`; Runtime's +principal boundary separates each person's files. This unmerged implementation +has no session migration. Disconnect clears session storage and frame memory +while linked accounts stay in Wallet. Revocation clears session files; linked +account removal and principal removal also clear the affected principal's file. + +Inbox owns internet consent through one request and the owner's passkey. Allow +returns focus to the connector; the same Inbox entry offers Turn Off. Runtime +admits only the opaque connector's single-use relay ticket, caps waiting sockets, +rechecks the launch and owner on each heartbeat and outbound frame, authenticates +relay TLS, and limits frames and sockets. It reaches only +`relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through +the local Exit. Turn Off cancels handshakes and open sockets. Hosted Carrier Exit +selection remains a separate integration. + +The native-Storage comparison and deterministic sandbox test cover Chromium and +WebKit. The opt-in real-relay test, selected with +`ELASTOS_WALLETCONNECT_PROJECT_FILE`, separately checks pairing, page reload and +a fresh source-gateway process restart. Installed desktop acceptance and a real +phone wallet require their own evidence. The connector is installed with Home and stays hidden and unroutable until `elastos.walletconnect.connector/v1` configuration and the matching hashed local diff --git a/elastos/CHANGELOG.md b/elastos/CHANGELOG.md index 817858f14..6f2d97b5b 100644 --- a/elastos/CHANGELOG.md +++ b/elastos/CHANGELOG.md @@ -8,6 +8,8 @@ release's Added, Changed, Fixed, Removed and Security bullets before you update; ### Fixed +- WalletConnect keeps its SDK in the connector capsule, uses capsule-scoped Runtime storage and relay access, and shows recovery instructions for interrupted transactions. + - Apps no longer open blank in Safari and other WebKit browsers. ## [2.0.1] - 2026-11-09 diff --git a/scripts/vendor-walletconnect-adapter.sh b/scripts/vendor-walletconnect-adapter.sh index 4d1c53607..5f12b5a70 100755 --- a/scripts/vendor-walletconnect-adapter.sh +++ b/scripts/vendor-walletconnect-adapter.sh @@ -12,10 +12,9 @@ mkdir -p "$(dirname "$OUT_FILE")" --inject:"$ROOT_DIR/scripts/walletconnect/runtime-websocket.mjs" --outfile="$OUT_FILE" node --input-type=module - "$ROOT_DIR" "$OUT_FILE" <<'JS' import { createHash } from 'node:crypto'; -import { readFileSync, writeFileSync, copyFileSync, readdirSync, lstatSync } from 'node:fs'; +import { readFileSync, writeFileSync, readdirSync, lstatSync } from 'node:fs'; import { dirname, join } from 'node:path'; const [root, output] = process.argv.slice(2); -copyFileSync(join(root, 'scripts/walletconnect/package-lock.json'), join(dirname(output), 'package-lock.json')); const sha = path => createHash('sha256').update(readFileSync(path)).digest('hex'); writeFileSync(join(dirname(output), 'adapter.json'), JSON.stringify({ sdk_package: '@walletconnect/ethereum-provider', sdk_version: '2.23.9', From 16124271231b6105b8b277b31fdc2f9249dde167 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:28:46 -0500 Subject: [PATCH 056/139] test(walletconnect): retain safe WebKit handshake errors and route refusals --- scripts/walletconnect-real-preflight-smoke.mjs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index 39391ceb1..9eafa8223 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -49,7 +49,14 @@ try { assert.equal(source.frame.url(), `${options.origin}/apps/wallet-walletconnect/wc-real.html`); return options; }); - await context.route('**/*', route => new URL(route.request().url()).origin === options.origin ? route.continue() : route.abort()); + run.blocked = {runtimeWebSocket:0,external:0}; + await context.route('**/*', route => { + const url = new URL(route.request().url()); + if (url.origin === options.origin) return route.continue(); + if (url.origin === options.origin.replace(/^http/,'ws')) run.blocked.runtimeWebSocket++; + else run.blocked.external++; + return route.abort(); + }); context.on('request', request => { const path = new URL(request.url()).pathname; if (path === '/api/apps/wallet-walletconnect/storage' && request.method() === 'POST') { @@ -84,7 +91,13 @@ try { socket.on('framesent', ({payload}) => observe(payload, 'sent')); socket.on('framereceived', ({payload}) => observe(payload, 'received')); socket.on('close', () => run.relay.closed++); - socket.on('socketerror', () => run.relay.errors++); + socket.on('socketerror', error => { + run.relay.errors++; + run.relay.errorText ??= []; + if (run.relay.errorText.length < 4) run.relay.errorText.push(String(error) + .split(options.projectId).join('[project]').split(options.connector).join('[launch]') + .replace(/([?&](?:auth|symKey|token)=)[^&\s"']+/g,'$1[redacted]').slice(0,384)); + }); }); run.phase = 'home'; assert.equal((await page.goto(`${options.origin}/apps/home/`, {timeout:10000})).status(), 200); From 65d7f27dbf842eb0f90d46ea8e5a54079a4205f9 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:31:17 -0500 Subject: [PATCH 057/139] test(walletconnect): use the layout smoke assertion helper for recovery --- scripts/wallet-connectors-uiux-layout-smoke.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/wallet-connectors-uiux-layout-smoke.mjs b/scripts/wallet-connectors-uiux-layout-smoke.mjs index e4ba16387..9c0cce702 100644 --- a/scripts/wallet-connectors-uiux-layout-smoke.mjs +++ b/scripts/wallet-connectors-uiux-layout-smoke.mjs @@ -534,7 +534,7 @@ async function run() { await recoveryPage.goto(`${server.baseUrl}/fixture?connector=${connector.id}&mode=recovery`); const recoveryFrame = await waitForConnectorFrame(recoveryPage); await recoveryFrame.getByText('Check your phone wallet.',{exact:false}).waitFor(); - assert.equal(await recoveryFrame.locator('[data-wallet-request-sign]').count(),0,'unfinished transaction offers recovery without another send'); + assert(await recoveryFrame.locator('[data-wallet-request-sign]').count() === 0,'unfinished transaction offers recovery without another send'); screenshots.push(await saveScreenshot(recoveryPage,`walletconnect-recovery-${width}.png`)); await recoveryPage.close(); } From 089fbb3e74ee880a37d3f012e8ce4db4c6bd91f3 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:52:31 -0500 Subject: [PATCH 058/139] fix(walletconnect): preserve typed requests and isolate SDK storage generations --- .../browser/wallet-walletconnect.js | 2 +- .../browser/walletconnect-client.mjs | 27 ++++++++++++++----- scripts/lib/walletconnect-capsule-fixture.mjs | 13 ++++----- scripts/walletconnect-capsule.test.mjs | 24 +++++++++++++++++ 4 files changed, 52 insertions(+), 14 deletions(-) diff --git a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js index 1fd5ee985..6c7de6c55 100644 --- a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js +++ b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js @@ -16,7 +16,7 @@ let hostEffectInFlight = false; const clearMemory = installWalletConnectStorage(window); const runtimeOrigin = new URL(import.meta.url).origin; const api = (resource, init={}) => fetchJson(resource.startsWith('/api/') ? runtimeOrigin+resource : `${runtimeOrigin}/api/apps/${CONNECTOR_ID}/${resource}`, { - ...init, headers:shellHeaders({'content-type':'application/json'}), + ...init, headers:shellHeaders({...init.headers,'content-type':'application/json'}), }); const connector = createWalletConnectClient({api,origin:runtimeOrigin,clearMemory}); window.addEventListener('focus',()=>refreshWalletState().catch(()=>{})); diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs index 3f87a1f38..de66fef37 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -1,6 +1,6 @@ // This module runs only in the connector's opaque frame. Runtime owns approval authority. -export function createWalletConnectClient({ api, origin, loadAdapter = () => import('./vendor/reown-appkit.js'), clearMemory = () => {} }) { - let provider, adapter, generation = 0; +export function createWalletConnectClient({ api, origin, loadAdapter = () => import(`./vendor/reown-appkit.js?instance=${crypto.randomUUID()}`), clearMemory = () => {} }) { + let provider, adapter, activeRevision, sessionApi, generation = 0; const address = async () => { const accounts = await provider.request({method:'eth_accounts'}); const value = accounts?.[0]; @@ -19,9 +19,17 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp const config = await api('wallet/config'); const permission = await api('internet'); if (permission.status !== 'granted') throw new Error('Allow WalletConnect internet access in Inbox, then connect again.'); + if (activeRevision !== undefined && activeRevision !== config.walletconnect.storage_revision) { + try { await adapter?.disconnectWalletConnectEvm({api:sessionApi}); } catch {} + provider = undefined; adapter = undefined; clearMemory(); + } + activeRevision = config.walletconnect.storage_revision; + const revision = activeRevision; + sessionApi = (resource, init={}) => api(resource, ['storage','relay-admission'].includes(resource) + ? {...init,headers:{...init.headers,'if-match':revision}} : init); adapter ??= await loadAdapter(); const current = await adapter.connectWalletConnectEvm({ - contextKey:'wallet-walletconnect', projectId:config.walletconnect.project_id, chains:[1,20,8453,11155111], api, + contextKey:'wallet-walletconnect', projectId:config.walletconnect.project_id, chains:[1,20,8453,11155111], api:sessionApi, runtimeUrl:`${origin}/api/apps/wallet-walletconnect`, relayUrl:`${origin.replace(/^http/,'ws')}/api/apps/wallet-walletconnect/relay`, metadata:{name:'ElastOS Home',description:'Runtime wallet approval',url:origin,icons:[]}, }); @@ -33,9 +41,9 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp }; const disconnect = async () => { generation++; - try { await adapter?.disconnectWalletConnectEvm({api}); } + try { await adapter?.disconnectWalletConnectEvm({api:sessionApi}); } finally { - provider = undefined; clearMemory(); + provider = undefined; adapter = undefined; activeRevision = undefined; clearMemory(); await api('storage',{method:'DELETE'}); } return {status:'disconnected'}; @@ -70,6 +78,10 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp if (!review || review.status !== 'pending' || !same(review.address,signer) || review.chain_namespace !== namespace) throw new Error('Select the requested account and network in your phone wallet, then review again.'); const ttl = review.expires_at - Math.ceil(Date.now()/1000); if (!Number.isSafeInteger(review.expires_at) || ttl <= 0 || review.intent === 'transaction_intent' && ttl < 300) throw new Error('Wallet request expires soon. Request a fresh review.'); + const supported = ['auth_challenge','browser_personal_sign','browser_typed_data_sign','capability_grant','credential','publish_envelope','transaction_intent','revocation']; + if (!supported.includes(review.intent)) throw new Error('This request type is unavailable in WalletConnect. Reject it in Wallet.'); + if (review.intent === 'browser_typed_data_sign' && !provider.session?.namespaces?.eip155?.methods?.includes('eth_signTypedData_v4')) + throw new Error('Typed data signing is unavailable in this pairing. Reject this request in Wallet or use another linked account.'); const {handoff,binding} = await api(`${path}/approve`,{method:'POST',body:'{}'}); if (!handoff || !binding || handoff.request_id !== action.approvalRequestId || handoff.payload_hash !== binding.payload_hash || !same(handoff.signer,signer) @@ -91,9 +103,10 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp return {status:'completed',effect:'transaction'}; } if (handoff.signature_type !== 'personal_sign' || typeof handoff.message !== 'string') throw new Error('Runtime returned an invalid signature request.'); - const signature = await provider.request({method:'personal_sign',params:[signData(handoff.message),signer]},expiry); + const method = handoff.intent === 'browser_typed_data_sign' ? 'eth_signTypedData_v4' : 'personal_sign'; + const signature = await provider.request({method,params:method === 'eth_signTypedData_v4' ? [signer,handoff.message] : [signData(handoff.message),signer]},expiry); await check(); - await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,signature,signature_type:'personal_sign'})}); + await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,signature,signature_type:method === 'eth_signTypedData_v4' ? 'eip712' : 'personal_sign'})}); return {status:'completed',effect:'signature'}; }}; } diff --git a/scripts/lib/walletconnect-capsule-fixture.mjs b/scripts/lib/walletconnect-capsule-fixture.mjs index a179f7dcb..5e98eebe8 100644 --- a/scripts/lib/walletconnect-capsule-fixture.mjs +++ b/scripts/lib/walletconnect-capsule-fixture.mjs @@ -3,30 +3,31 @@ import { createWalletConnectClient } from '../../capsules/wallet-walletconnect/b export const address = `0x${'12'.repeat(20)}`, payloadHash=`0x${'34'.repeat(32)}`, transactionHash=`0x${'56'.repeat(32)}`; export async function exerciseWalletConnect(scenario='valid') { const clock=Date.now, calls=[],routes=[],events=new Map(); let changed=false, memoryCleared=false; - const signatureIntent=scenario.startsWith('signature-'); + const signatureIntent=scenario.startsWith('signature-') || scenario.startsWith('typed') || scenario==='unsupported'; + const intent=scenario.startsWith('typed')?'browser_typed_data_sign':scenario==='unsupported'?'unavailable_intent':signatureIntent?'browser_personal_sign':'transaction_intent'; const kind=scenario.replace(/^signature-/,''); const lifetime=scenario==='signature-short'?180:scenario==='long-request'?1800:600; const signature=`0x${'ab'.repeat(65)}`; const message=scenario==='link-uppercase-hex'?'0X4142':scenario==='link-odd-hex'?'0x123':'Runtime ownership proof · fixture'; const change=()=>{changed=true;if(kind==='account-change-during-send')events.get('accountsChanged')?.([]); if(kind==='chain-change-during-send')events.get('chainChanged')?.('0x1');if(kind==='expired-during-send')Date.now=()=>clock()+601000;}; - const provider={connected:true,session:{expiry:clock()/1000+3600},signer:{client:{core:{relayer:{connected:true}}}}, + const provider={connected:true,session:{expiry:clock()/1000+3600,namespaces:{eip155:{methods:scenario==='typed-unavailable'?['personal_sign']:['personal_sign','eth_sendTransaction','eth_signTypedData_v4']}}},signer:{client:{core:{relayer:{connected:true}}}}, on:(name,fn)=>events.set(name,fn),async request(input,expiry){calls.push({...input,expiry}); if(input.method==='eth_accounts')return [scenario==='wrong-account'||changed&&kind==='account-change-during-send'?`0x${'ab'.repeat(20)}`:address]; if(input.method==='eth_chainId')return scenario==='wrong-chain'||changed&&kind==='chain-change-during-send'?'0x1':'0x14'; - if(input.method==='personal_sign'){if(signatureIntent)change();return signature;} + if(['personal_sign','eth_signTypedData_v4'].includes(input.method)){if(signatureIntent)change();return signature;} if(input.method==='eth_sendTransaction'){change();return scenario==='invalid-hash'?'Open a fake recovery website':transactionHash;} throw new Error('Unexpected wallet call'); }}; const api=async(path,input)=>{routes.push({path,input}); - if(path==='wallet/config')return {walletconnect:{project_id:'fixture-project'}}; + if(path==='wallet/config')return {walletconnect:{project_id:'fixture-project',storage_revision:'"0"'}}; if(path==='internet')return {status:'granted'}; if(path==='storage')return {}; if(path.endsWith('/challenge'))return {schema:'elastos.auth.challenge/v1',message,expires_at:Math.floor(clock()/1000)+600}; if(path.endsWith('/verify')){const body=JSON.parse(input.body);assert.equal(body.message,message);assert.equal(body.signature,signature);return {status:'linked'};} if(path==='wallet/approvals')return {approval_requests:[{request_id:'approval:fixture',status:scenario==='approved'?'approved':'pending',address, - intent:signatureIntent?'browser_personal_sign':'transaction_intent',chain_namespace:'eip155:20',expires_at:Math.floor(clock()/1000)+lifetime}]}; - if(path.endsWith('/approve'))return {handoff:{request_id:'approval:fixture',intent:signatureIntent?'browser_personal_sign':'transaction_intent', + intent,chain_namespace:'eip155:20',expires_at:Math.floor(clock()/1000)+lifetime}]}; + if(path.endsWith('/approve'))return {handoff:{request_id:'approval:fixture',intent, payload_hash:payloadHash,signer:address,signature_type:'personal_sign',message:'Runtime approval fixture', transaction:{from:address,to:`0x${'78'.repeat(20)}`,value:'0x1',data:'0x',gas:'0x5208',gasPrice:'0x1',nonce:'0x1',chainId:'0x14'}}, binding:{principal_id:'fixture',requested_by_actor:'documents',account_id:'fixture-account',chain_namespace:'eip155:20',payload_hash:payloadHash, diff --git a/scripts/walletconnect-capsule.test.mjs b/scripts/walletconnect-capsule.test.mjs index b084591c5..56183ed69 100644 --- a/scripts/walletconnect-capsule.test.mjs +++ b/scripts/walletconnect-capsule.test.mjs @@ -18,3 +18,27 @@ test('Home capsules contain no WalletConnect SDK import or signer',()=>{ const scan=path=>{for(const e of readdirSync(path,{withFileTypes:true})){const p=join(path,e.name);if(e.isDirectory())scan(p);else if(/\.[cm]?js$/.test(e.name))assert.doesNotMatch(readFileSync(p,'utf8'),/connectWalletConnectEvm|@walletconnect\/|import\s*\([^)]*reown-appkit/);}}; for(const e of readdirSync('capsules',{withFileTypes:true}))if(e.isDirectory()&&e.name.startsWith('home'))scan(join('capsules',e.name)); }); + +test('typed data uses EIP-712 and preserves the exact Runtime message',async()=>{const r=await exerciseWalletConnect('typed');assert.equal(r.error,undefined);const call=r.calls.find(c=>c.method==='eth_signTypedData_v4');assert.equal(call.params[1],'Runtime approval fixture');assert.equal(JSON.parse(completed(r)[0].input.body).signature_type,'eip712');}); +for(const scenario of ['typed-unavailable','unsupported']) test(`${scenario} remains pending instead of consuming an approval`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(typeof r.error,'string');assert.equal(r.routes.filter(c=>c.path.endsWith('/approve')).length,0);assert.equal(completed(r).length,0);}); +test('a reset creates a fresh SDK API while old SDK writes keep their stale revision',async()=>{ + const {createWalletConnectClient}=await import('../capsules/wallet-walletconnect/browser/walletconnect-client.mjs'); + let revision='"0"',loads=0,disconnects=0;const sessions=[]; + const signer=`0x${'12'.repeat(20)}`; + const provider={on(){},request:async({method})=>method==='eth_accounts'?[signer]:method==='eth_chainId'?'0x14':'fixture-signature'}; + const api=async(path,input)=>{ + if(path==='wallet/config')return {walletconnect:{project_id:'fixture-project',storage_revision:revision}}; + if(path==='internet')return {status:'granted'}; + if(path==='storage'){if(input.headers['if-match']!==revision)throw new Error('stale SDK');return {};} + if(path.endsWith('/challenge'))return {message:'fixture',expires_at:Date.now()/1000+600|0}; + if(path.endsWith('/verify'))return {}; + throw new Error('Unexpected resource'); + }; + const client=createWalletConnectClient({api,origin:'http://localhost',loadAdapter:async()=>{loads++;return { + connectWalletConnectEvm:async options=>{sessions.push(options.api);return provider;},disconnectWalletConnectEvm:async()=>{disconnects++;}, + };}}); + await client.effect({kind:'link'});revision='"1"';await client.effect({kind:'link'}); + assert.equal(loads,2);assert.equal(disconnects,1); + await assert.rejects(sessions[0]('storage',{method:'POST'}),/stale SDK/); + assert.deepEqual(await sessions[1]('storage',{method:'POST'}),{}); +}); From c7195ee6a97f2e486e4f45b92f425a810085c510 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:52:31 -0500 Subject: [PATCH 059/139] fix(walletconnect): reuse owner consent and fence sessions after cleanup --- docs/WALLET_PROVIDER.md | 5 +- .../api/gateway_tests/wallet/walletconnect.rs | 130 +++++++++++++++++- .../src/api/gateway_wallet_accounts.rs | 16 ++- .../src/api/gateway_wallet_connectors.rs | 15 +- .../src/api/gateway_walletconnect.rs | 87 ++++++++++-- elastos/crates/elastos-server/src/auth.rs | 8 +- 6 files changed, 237 insertions(+), 24 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 0fde4711d..2b61e1735 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -274,10 +274,11 @@ Browser Storage holds UI preferences in memory and resets on reload. Protocol and keychain names raise `SecurityError` there. Runtime's private key/value store holds pairings, sessions and cryptographic keys, selected by the verified principal. The SDK uses the constant context `wallet-walletconnect`; Runtime's -principal boundary separates each person's files. This unmerged implementation -has no session migration. Disconnect clears session storage and frame memory +principal boundary separates each person's files. The connector supplies no session migration. Disconnect clears session storage and the memory shim while linked accounts stay in Wallet. Revocation clears session files; linked account removal and principal removal also clear the affected principal's file. +A Runtime storage revision fences late writes and relay use from an old SDK +instance after cleanup. Reopening the connector starts a fresh instance. Inbox owns internet consent through one request and the owner's passkey. Allow returns focus to the connector; the same Inbox entry offers Turn Off. Runtime diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 1d3d4aa2a..13ae841b0 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -217,6 +217,17 @@ impl Fixture { body: Option, ) -> (StatusCode, Value) { let origin = "null"; + let revision = require_carried_home_launch_token( + self.data.path(), + token, + &[WALLET_WALLETCONNECT_CAPSULE_ID], + ) + .ok() + .and_then(|launch| { + gateway_walletconnect::storage_revision(self.data.path(), &launch.context.principal_id) + .ok() + }) + .unwrap_or_else(|| "\"0\"".into()); let response = self .app .clone() @@ -227,7 +238,7 @@ impl Fixture { .uri(path) .method(if body.is_some() { "POST" } else { "GET" }) .header("x-elastos-home-token", token) - .header("x-elastos-walletconnect-connector", token) + .header("if-match", revision) .header(CONTENT_TYPE, "application/json") .body(body.map_or_else(Body::empty, |v| Body::from(v.to_string()))) .unwrap(), @@ -1044,3 +1055,120 @@ async fn walletconnect_cleanup_refuses_linked_parent_and_preserves_other_files() "preserve" ); } + +#[tokio::test] +async fn walletconnect_guest_uses_an_existing_owner_grant_without_another_approval() { + let f = Fixture::new().await; + let guest = passkey_authority_with_name_role_credential( + f.data.path(), + Some("wc-guest"), + crate::auth::RuntimePrincipalRole::Guest, + "wc-guest-credential", + ); + let token = projection_launch_token_for_authority_context( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &guest, + ); + assert_ne!( + f.route(&token, INTERNET, Some(json!({"action":"request"}))) + .await + .0, + StatusCode::OK + ); + f.allow().await; + let (_, before) = f.route(&f.inbox, INTERNET, None).await; + let (status, after) = f + .route(&token, INTERNET, Some(json!({"action":"request"}))) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(before["request"]["id"], after["request"]["id"]); + assert_eq!( + f.route( + &token, + STORAGE, + Some(json!({"key":"session","value":"guest"})) + ) + .await + .0, + StatusCode::OK + ); +} + +#[tokio::test] +async fn walletconnect_cleanup_fences_old_storage_and_admission_and_removes_crash_temps() { + let f = Fixture::new().await; + f.allow().await; + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"session","value":"fixture"})) + ) + .await + .0, + StatusCode::OK + ); + let principal = runtime_wallet_authority_for_app_token( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &f.connector, + ) + .home_launch_context() + .principal_id; + let directory = f + .data + .path() + .join("ElastOS/SystemServices/WalletConnect/sessions"); + let name = format!("{}.json", hex::encode(Sha256::digest(principal.as_bytes()))); + std::fs::write( + directory.join(format!(".{name}.0123456789abcdef.tmp")), + "fixture-crash-keys", + ) + .unwrap(); + std::fs::write(directory.join("operator-note.txt"), "preserve").unwrap(); + let (_, grant) = f.route(&f.inbox, INTERNET, None).await; + f.answer(&grant, true).await; + assert!(!directory.join(&name).exists()); + assert!(!directory + .join(format!(".{name}.0123456789abcdef.tmp")) + .exists()); + assert_eq!( + std::fs::read_to_string(directory.join("operator-note.txt")).unwrap(), + "preserve" + ); + f.allow().await; + for (path, body) in [ + (STORAGE, json!({"key":"late","value":"old-sdk"})), + ("/api/apps/wallet-walletconnect/relay-admission", json!({})), + ] { + let response = f + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, &f.addr) + .header("origin", "null") + .header("x-elastos-home-token", &f.connector) + .header("if-match", "\"0\"") + .header(CONTENT_TYPE, "application/json") + .uri(path) + .method("POST") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_ne!(response.status(), StatusCode::OK, "stale SDK {path}"); + } + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"new","value":"fresh-sdk"})) + ) + .await + .0, + StatusCode::OK + ); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs index 6ca534179..5712be414 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs @@ -33,10 +33,14 @@ pub(in crate::api::gateway) async fn runtime_wallet_data( if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID && !data["account"]["revoked_at"].is_null() { - gateway_walletconnect::clear_principal_storage( + if gateway_walletconnect::clear_principal_storage( &state.data_dir, authority.verified_context().principal_id(), - )?; + ) + .is_err() + { + tracing::warn!("WalletConnect session cleanup requires operator retry after account removal"); + } } Ok(data) } @@ -63,10 +67,14 @@ pub(in crate::api::gateway) async fn runtime_wallet_data_with_request_id( if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID && !data["account"]["revoked_at"].is_null() { - gateway_walletconnect::clear_principal_storage( + if gateway_walletconnect::clear_principal_storage( &state.data_dir, authority.verified_context().principal_id(), - )?; + ) + .is_err() + { + tracing::warn!("WalletConnect session cleanup requires operator retry after account removal"); + } } Ok(data) } diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 034311f18..d5ac05b01 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -5,13 +5,14 @@ pub(in crate::api::gateway) async fn wallet_connector_config( Path(wallet_connector): Path, headers: HeaderMap, ) -> Response { - if let Err(err) = require_wallet_connector_launch_context( + let context = match require_wallet_connector_launch_context( &state.data_dir, &headers, wallet_connector.as_str(), ) { - return system_error_response(err); - } + Ok(context) => context, + Err(err) => return system_error_response(err), + }; let mut payload = serde_json::json!({ "schema": "elastos.wallet.connector.config/v1", @@ -25,8 +26,16 @@ pub(in crate::api::gateway) async fn wallet_connector_config( Ok(config) }) { Ok(config) => { + let revision = match gateway_walletconnect::storage_revision( + &state.data_dir, + &context.principal_id, + ) { + Ok(revision) => revision, + Err(err) => return system_error_response(err), + }; payload["walletconnect"] = serde_json::json!({ "project_id": config.project_id, + "storage_revision": revision, "sdk_package": config.sdk_package, "sdk_version": config.sdk_version, "sdk_asset_path": "/apps/wallet-walletconnect/vendor/reown-appkit.js", diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 149009676..1b8e9d4f0 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -60,6 +60,8 @@ struct Consent { principal: Option, proof: Option, capability: Option, + #[serde(default)] + cleanup_pending: bool, } fn root(data: &FsPath) -> PathBuf { @@ -211,6 +213,7 @@ pub(super) async fn answer( &request(&c)?, )?; c.status = if stopping { "revoked" } else { "granted" }.into(); + c.cleanup_pending = stopping; c.principal = Some(launch.context.principal_id.clone()); c.proof = launch.context.proof_binding_id.clone(); if !stopping { @@ -250,6 +253,8 @@ pub(super) async fn answer( } inner.sockets.clear(); clear_all_storage(&state.data_dir)?; + c.cleanup_pending = false; + save(&state.data_dir, &c)?; return Ok("WalletConnect connection turned off.".into()); } } @@ -272,7 +277,8 @@ pub(super) fn notification( .inner .try_lock() .ok() - .is_some_and(|inner| !inner.sockets.is_empty())); + .is_some_and(|inner| !inner.sockets.is_empty()) + || (c.status == "revoked" && c.cleanup_pending)); Some(HomeNotificationEntrySummary { id: "walletconnect-internet:permission".into(), source_app: WALLET_WALLETCONNECT_CAPSULE_ID.into(), @@ -287,6 +293,8 @@ pub(super) fn notification( CONSENT } else if c.status == "granted" { "WalletConnect can reach the wallet relay." + } else if c.cleanup_pending { + "WalletConnect is off. Select Turn Off again to finish clearing its saved session." } else { "WalletConnect relay access is off." } @@ -334,7 +342,6 @@ pub(super) async fn internet( input.action == "request", "Invalid WalletConnect internet action" ); - ensure_admin_context(&state.data_dir, &authority.home_launch_context()).map_err(|_| anyhow::anyhow!("Only this Home's owner can allow WalletConnect internet access. Ask the owner to review Inbox."))?; ensure_consent_request(&state, &authority.home_launch_context(), &inner)?; } Ok::<_, anyhow::Error>(public(load(&state.data_dir)?.as_ref())) @@ -352,10 +359,14 @@ fn ensure_consent_request( inner: &Inner, ) -> anyhow::Result<()> { let current = load(&state.data_dir)?; + anyhow::ensure!( + current.as_ref().is_none_or(|c| !c.cleanup_pending), + "Finish clearing the previous WalletConnect session in Inbox first." + ); if current.as_ref().is_none_or(|c| { c.status != "granted" && (c.status != "requested" || c.at + 1800 <= now_ts()) }) { - ensure_admin_context(&state.data_dir, context)?; + ensure_admin_context(&state.data_dir, context).map_err(|_| anyhow::anyhow!("Only this Home's owner can allow WalletConnect internet access. Ask the owner to review Inbox."))?; anyhow::ensure!( inner.sockets.values().all(|s| *s.done.borrow()), "Finish stopping WalletConnect first" @@ -369,6 +380,7 @@ fn ensure_consent_request( principal: None, proof: None, capability: None, + cleanup_pending: false, }, )?; } @@ -400,6 +412,16 @@ fn connector_authority( ); // The signed launch carries principal, live session and exact launch instance. // Retaining these headers binds relay tickets and recurring checks to that launch. + if headers + .get("if-match") + .and_then(|v| v.to_str().ok()) + .unwrap_or("\"0\"") + != storage_revision(&state.data_dir, &launch.context.principal_id)? + { + anyhow::bail!( + "WalletConnect session changed. Close this window and open WalletConnect again." + ); + } runtime_wallet_authority(&launch) } #[cfg(test)] @@ -476,7 +498,15 @@ pub(super) async fn storage( input: Result, axum::extract::rejection::JsonRejection>, ) -> Response { let result = async { - let authority = connector_authority(&state, &headers)?; + let authority = if method == axum::http::Method::DELETE { + require_runtime_wallet_authority( + &state.data_dir, + &headers, + &[WALLET_WALLETCONNECT_CAPSULE_ID], + )? + } else { + connector_authority(&state, &headers)? + }; let _guard = state.walletconnect.inner.lock().await; let path = storage_path( &state.data_dir, @@ -843,6 +873,7 @@ mod tests { pub(crate) fn clear_principal_storage(data: &FsPath, principal: &str) -> anyhow::Result<()> { let _files = session_files_lock()?; let path = storage_path(data, principal); + bump_storage_revision(data, path.file_name().unwrap())?; match std::fs::symlink_metadata(&path) { Ok(meta) => { anyhow::ensure!( @@ -868,16 +899,28 @@ fn clear_all_storage(data: &FsPath) -> anyhow::Result<()> { ); for entry in std::fs::read_dir(dir)? { let entry = entry?; + if !entry.file_type()?.is_file() { + continue; + } let name = entry.file_name(); - let name = name.to_str().unwrap_or_default(); - anyhow::ensure!( - name.strip_suffix(".json").is_some_and(|stem| stem.len() == 64 && stem.bytes().all(|b| b.is_ascii_hexdigit())), - "Invalid WalletConnect session file" - ); - anyhow::ensure!( - entry.file_type()?.is_file(), - "WalletConnect session requires a regular file" - ); + let text = name.to_str().unwrap_or_default(); + let stem = text.strip_suffix(".json").or_else(|| { + text.strip_prefix('.') + .and_then(|s| s.split_once(".json.")) + .and_then(|(stem, tail)| { + tail.strip_suffix(".tmp") + .filter(|suffix| { + suffix.len() == 16 && suffix.bytes().all(|b| b.is_ascii_hexdigit()) + }) + .map(|_| stem) + }) + }); + let Some(stem) = + stem.filter(|stem| stem.len() == 64 && stem.bytes().all(|b| b.is_ascii_hexdigit())) + else { + continue; + }; + bump_storage_revision(data, std::ffi::OsStr::new(&format!("{stem}.json")))?; let path = entry.path(); remove_session_file(data, &path, &std::fs::symlink_metadata(&path)?)?; } @@ -910,3 +953,21 @@ fn session_files_lock() -> anyhow::Result> { LOCK.lock() .map_err(|_| anyhow::anyhow!("WalletConnect session storage is unavailable")) } + +pub(super) fn storage_revision(data: &FsPath, principal: &str) -> anyhow::Result { + let path = storage_path(data, principal); + let value: u64 = read( + &root(data).join("revisions").join(path.file_name().unwrap()), + 128, + )? + .unwrap_or(0); + Ok(format!("\"{value}\"")) +} +fn bump_storage_revision(data: &FsPath, name: &std::ffi::OsStr) -> anyhow::Result<()> { + let path = root(data).join("revisions").join(name); + let previous: u64 = read(&path, 128)?.unwrap_or(0); + let next = previous + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("WalletConnect revision overflow"))?; + crate::auth::atomic_write(&path, &serde_json::to_vec(&next)?) +} diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index a1bb326e9..b26fbef8c 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -4546,7 +4546,13 @@ fn mutate_auth_state( save_auth_state(data_dir, &state, Some(&baseline))?; for principal in previous_principals { if !state.principals.iter().any(|p| p.principal_id == principal) { - crate::api::gateway::clear_walletconnect_principal_storage(data_dir, &principal)?; + if crate::api::gateway::clear_walletconnect_principal_storage(data_dir, &principal) + .is_err() + { + tracing::warn!( + "WalletConnect session cleanup requires operator retry after principal removal" + ); + } } } unlock_auth_state_file(lock)?; From da308d1a9cf389d490b3a96f59ec4026075194df Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:52:31 -0500 Subject: [PATCH 060/139] fix(walletconnect): sync the Object provider lock with Runtime relay dependencies --- capsules/object-provider/Cargo.lock | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/capsules/object-provider/Cargo.lock b/capsules/object-provider/Cargo.lock index b50f48cf4..aebbe2ed4 100644 --- a/capsules/object-provider/Cargo.lock +++ b/capsules/object-provider/Cargo.lock @@ -1650,6 +1650,7 @@ dependencies = [ "elastos-wallet-contract", "flate2", "futures-lite", + "futures-util", "getrandom 0.2.17", "hex", "hkdf", @@ -1674,12 +1675,14 @@ dependencies = [ "tar", "tempfile", "tokio", + "tokio-tungstenite", "toml", "tower-http 0.5.2", "tracing", "tracing-subscriber", "url", "wasmparser 0.236.1", + "webpki-roots 1.0.10", "x25519-dalek 2.0.1", "zeroize", "zip", @@ -2441,7 +2444,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots", + "webpki-roots 1.0.10", ] [[package]] @@ -2874,7 +2877,7 @@ dependencies = [ "tokio-websockets", "tracing", "url", - "webpki-roots", + "webpki-roots 1.0.10", "ws_stream_wasm", ] @@ -3341,7 +3344,7 @@ dependencies = [ "tokio", "tokio-rustls", "tracing", - "webpki-roots", + "webpki-roots 1.0.10", ] [[package]] @@ -4505,7 +4508,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots", + "webpki-roots 1.0.10", ] [[package]] @@ -5451,8 +5454,12 @@ checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" dependencies = [ "futures-util", "log", + "rustls", + "rustls-pki-types", "tokio", + "tokio-rustls", "tungstenite", + "webpki-roots 0.26.11", ] [[package]] @@ -5716,6 +5723,8 @@ dependencies = [ "httparse", "log", "rand 0.8.8", + "rustls", + "rustls-pki-types", "sha1", "thiserror 1.0.69", "utf-8", @@ -6334,6 +6343,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.10", +] + [[package]] name = "webpki-roots" version = "1.0.10" From b8251822049327cee867a0479d485a7f631bab9a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:58:05 -0500 Subject: [PATCH 061/139] fix(walletconnect): serialize cleanup across processes and keep retry visible --- .../api/gateway_tests/wallet/walletconnect.rs | 69 +++++++++++++++++++ .../src/api/gateway_walletconnect.rs | 46 +++++++++++-- elastos/crates/elastos-server/src/auth.rs | 31 +++++++++ 3 files changed, 139 insertions(+), 7 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 13ae841b0..ce8da8b4d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -1172,3 +1172,72 @@ async fn walletconnect_cleanup_fences_old_storage_and_admission_and_removes_cras StatusCode::OK ); } + +#[tokio::test] +async fn walletconnect_turn_off_keeps_cleanup_retry_in_its_inbox_entry() { + let f = Fixture::new().await; + f.allow().await; + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"session","value":"fixture"})) + ) + .await + .0, + StatusCode::OK + ); + let (_, grant) = f.route(&f.inbox, INTERNET, None).await; + let sessions = f + .data + .path() + .join("ElastOS/SystemServices/WalletConnect/sessions"); + let held = sessions.with_extension("held"); + std::fs::rename(&sessions, &held).unwrap(); + let other = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(other.path(), &sessions).unwrap(); + let token = gateway_passkey_step_up::issue_passkey_step_up_token_for_test( + f.data.path(), + &f.inbox, + INBOX_CAPSULE_ID, + gateway_walletconnect::REVOKE, + &grant["request"], + ) + .unwrap(); + let action = format!( + "walletconnect-internet-turn-off:{}", + grant["request"]["id"].as_str().unwrap() + ); + assert_ne!( + f.route( + &f.inbox, + "/api/apps/inbox/actions", + Some(json!({"action_id":action,"step_up_token":token})) + ) + .await + .0, + StatusCode::OK + ); + let context = runtime_wallet_authority_for_app_token(f.data.path(), INBOX_CAPSULE_ID, &f.inbox) + .home_launch_context(); + assert!(gateway_walletconnect::notification(&f.state, &context) + .unwrap() + .action_ref + .is_some()); + std::fs::rename(&sessions, sessions.with_extension("refused-link")).unwrap(); + std::fs::rename(&held, &sessions).unwrap(); + assert_eq!( + f.route( + &f.inbox, + "/api/apps/inbox/actions", + Some(json!({"action_id":action})) + ) + .await + .0, + StatusCode::OK + ); + assert!(gateway_walletconnect::notification(&f.state, &context) + .unwrap() + .action_ref + .is_none()); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 1b8e9d4f0..77d735e7f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -522,7 +522,7 @@ pub(super) async fn storage( if method == axum::http::Method::POST { check_owner(&state, false).await?; } - let _files = session_files_lock()?; + let _files = session_files_lock(&state.data_dir)?; // Removal and storage commits share this lock. Revalidate after acquiring // it so a write admitted before principal removal cannot recreate keys. connector_authority(&state, &headers)?; @@ -871,7 +871,7 @@ mod tests { // Runtime owns these exact, principal-derived session paths; UI never selects a path. pub(crate) fn clear_principal_storage(data: &FsPath, principal: &str) -> anyhow::Result<()> { - let _files = session_files_lock()?; + let _files = session_files_lock(data)?; let path = storage_path(data, principal); bump_storage_revision(data, path.file_name().unwrap())?; match std::fs::symlink_metadata(&path) { @@ -888,7 +888,7 @@ pub(crate) fn clear_principal_storage(data: &FsPath, principal: &str) -> anyhow: Ok(()) } fn clear_all_storage(data: &FsPath) -> anyhow::Result<()> { - let _files = session_files_lock()?; + let _files = session_files_lock(data)?; let dir = root(data).join("sessions"); if !dir.try_exists()? { return Ok(()); @@ -948,10 +948,42 @@ fn remove_session_file( } } -fn session_files_lock() -> anyhow::Result> { - static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - LOCK.lock() - .map_err(|_| anyhow::anyhow!("WalletConnect session storage is unavailable")) +fn session_files_lock(data: &FsPath) -> anyhow::Result { + let directory = root(data); + std::fs::create_dir_all(&directory)?; + let path = directory.join("session-storage.lock"); + let mut options = std::fs::OpenOptions::new(); + options.create(true).truncate(false).read(true).write(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC); + } + let file = options.open(&path)?; + let metadata = file.metadata()?; + anyhow::ensure!( + metadata.is_file(), + "WalletConnect storage lock requires a regular file" + ); + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let current = std::fs::symlink_metadata(&path)?; + anyhow::ensure!( + metadata.nlink() == 1 + && metadata.uid() == unsafe { libc::geteuid() } + && metadata.permissions().mode() & 0o077 == 0 + && current.dev() == metadata.dev() + && current.ino() == metadata.ino(), + "WalletConnect storage lock requires its owner-only file" + ); + } + Ok(crate::host_lock::FileLock::exclusive_within( + file, + Duration::from_secs(3), + )?) } pub(super) fn storage_revision(data: &FsPath, principal: &str) -> anyhow::Result { diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index b26fbef8c..7bb29e7a5 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -15814,6 +15814,37 @@ mod tests { assert_eq!(std::fs::read(other).unwrap(), b"preserve"); } + #[test] + fn walletconnect_principal_cleanup_failure_preserves_the_committed_auth_result() { + let data = tempfile::tempdir().unwrap(); + let principal = + upsert_principal_for_binding(data.path(), passkey_binding(1, 100, 100), 100).unwrap(); + let directory = data + .path() + .join("ElastOS/SystemServices/WalletConnect/sessions"); + std::fs::create_dir_all(directory.parent().unwrap()).unwrap(); + let other = tempfile::tempdir().unwrap(); + let name = format!( + "{}.json", + hex::encode(sha2::Sha256::digest(principal.principal_id.as_bytes())) + ); + std::fs::write(other.path().join(&name), b"preserve").unwrap(); + std::os::unix::fs::symlink(other.path(), &directory).unwrap(); + mutate_auth_state(data.path(), |state| { + state + .principals + .retain(|p| p.principal_id != principal.principal_id); + Ok(()) + }) + .unwrap(); + assert!(!load_auth_state(data.path()) + .unwrap() + .principals + .iter() + .any(|p| p.principal_id == principal.principal_id)); + assert_eq!(std::fs::read(other.path().join(name)).unwrap(), b"preserve"); + } + #[test] fn passkey_revoke_marks_binding_and_sessions_revoked() { let data_dir = tempfile::tempdir().unwrap(); From 8f8104a738d27b9b296bbcb28afefab84e76ea83 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 14:58:05 -0500 Subject: [PATCH 062/139] test(walletconnect): classify WebKit upgrade refusals without recording credentials --- .../wallet/walletconnect_real_relay.rs | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 79474931b..0e4b1cfe8 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -180,7 +180,26 @@ async fn walletconnect_gateway_process_worker() { .await .unwrap(); state.provider_registry = Some(registry); - let app = gateway_router_with_api_url(state, format!("http://{addr}")); + let expected_origin = format!("http://{addr}"); + let expected_host = addr.to_string(); + let refusal_path = data.join("relay-handshake-refusal.json"); + let app = gateway_router_with_api_url(state, expected_origin.clone()).layer(axum::middleware::from_fn( + move |request: axum::extract::Request, next: axum::middleware::Next| { + let refusal_path = refusal_path.clone(); + let relay = request.uri().path() == "/api/apps/wallet-walletconnect/relay"; + let origin_count = request.headers().get_all("origin").iter().count(); + let origin = request.headers().get("origin").and_then(|h|h.to_str().ok()); + let kind = match origin { None=>"missing",Some("null")=>"opaque",Some(value) if value==expected_origin=>"same-home",_=>"other" }; + let host_matches = request.headers().get("host").and_then(|h|h.to_str().ok()) == Some(expected_host.as_str()); + async move { + let response = next.run(request).await; + if relay && response.status()==StatusCode::FORBIDDEN { + crate::auth::atomic_write(&refusal_path, &serde_json::to_vec(&json!({"status":403,"origin_kind":kind,"origin_headers":origin_count,"host_matches":host_matches})).unwrap()).unwrap(); + } + response + } + } + )); let listener = TcpListener::bind(addr).await.unwrap(); println!("WC_GATEWAY_READY"); std::io::Write::flush(&mut std::io::stdout()).unwrap(); @@ -211,7 +230,7 @@ async fn start_gateway_process(f: &Fixture) -> tokio::process::Child { length > 0 && count <= 32768, "gateway worker failed before readiness" ); - if line.trim() == "WC_GATEWAY_READY" { + if line.trim().ends_with("WC_GATEWAY_READY") { break; } } @@ -312,6 +331,13 @@ async fn walletconnect_real_project_opaque_preflight() { gateway_process.kill().await.unwrap(); let output = result.expect("real relay paired recovery timeout"); println!("{}", String::from_utf8_lossy(&output.stdout)); + if let Some(bytes) = + gateway_walletconnect::read_bytes(&f.data.path().join("relay-handshake-refusal.json"), 1024) + .unwrap() + { + let record: Value = serde_json::from_slice(&bytes).unwrap(); + println!("{}", json!({"relay_handshake_refusal":record})); + } // The Node driver emits only bounded, value-free evidence. SDK diagnostics // can contain relay credentials, so stderr remains private to this process. assert!( From 6b616f575e22f9d3e5902fb0c7e10a900d8e84bc Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 15:06:18 -0500 Subject: [PATCH 063/139] fix(walletconnect): simplify cleanup conditions for the Rust lint gate --- .../src/api/gateway_wallet_accounts.rs | 20 +++++++++---------- .../src/api/gateway_walletconnect.rs | 14 ++++++------- elastos/crates/elastos-server/src/auth.rs | 13 ++++++------ 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs index 5712be414..c098a8ea3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs @@ -32,15 +32,15 @@ pub(in crate::api::gateway) async fn runtime_wallet_data( elastos_wallet_contract::WalletResultV2::Ok { data } => { if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID && !data["account"]["revoked_at"].is_null() - { - if gateway_walletconnect::clear_principal_storage( + && gateway_walletconnect::clear_principal_storage( &state.data_dir, authority.verified_context().principal_id(), ) .is_err() - { - tracing::warn!("WalletConnect session cleanup requires operator retry after account removal"); - } + { + tracing::warn!( + "WalletConnect session cleanup requires operator retry after account removal" + ); } Ok(data) } @@ -66,15 +66,15 @@ pub(in crate::api::gateway) async fn runtime_wallet_data_with_request_id( elastos_wallet_contract::WalletResultV2::Ok { data } => { if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID && !data["account"]["revoked_at"].is_null() - { - if gateway_walletconnect::clear_principal_storage( + && gateway_walletconnect::clear_principal_storage( &state.data_dir, authority.verified_context().principal_id(), ) .is_err() - { - tracing::warn!("WalletConnect session cleanup requires operator retry after account removal"); - } + { + tracing::warn!( + "WalletConnect session cleanup requires operator retry after account removal" + ); } Ok(data) } diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 77d735e7f..341e682df 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -272,13 +272,13 @@ pub(super) fn notification( let pending = c.status == "requested" && request(&c).is_ok(); let active = c.status == "granted" || (c.status == "revoked" - && state - .walletconnect - .inner - .try_lock() - .ok() - .is_some_and(|inner| !inner.sockets.is_empty()) - || (c.status == "revoked" && c.cleanup_pending)); + && (c.cleanup_pending + || state + .walletconnect + .inner + .try_lock() + .ok() + .is_some_and(|inner| !inner.sockets.is_empty()))); Some(HomeNotificationEntrySummary { id: "walletconnect-internet:permission".into(), source_app: WALLET_WALLETCONNECT_CAPSULE_ID.into(), diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index 7bb29e7a5..c05292624 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -4545,14 +4545,13 @@ fn mutate_auth_state( let value = mutation(&mut state)?; save_auth_state(data_dir, &state, Some(&baseline))?; for principal in previous_principals { - if !state.principals.iter().any(|p| p.principal_id == principal) { - if crate::api::gateway::clear_walletconnect_principal_storage(data_dir, &principal) + if !state.principals.iter().any(|p| p.principal_id == principal) + && crate::api::gateway::clear_walletconnect_principal_storage(data_dir, &principal) .is_err() - { - tracing::warn!( - "WalletConnect session cleanup requires operator retry after principal removal" - ); - } + { + tracing::warn!( + "WalletConnect session cleanup requires operator retry after principal removal" + ); } } unlock_auth_state_file(lock)?; From 2750cea8455280f9c308afa81ea30e9e6f7c66bd Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 15:09:13 -0500 Subject: [PATCH 064/139] fix(walletconnect): retain protected-content signing and bound session retirement --- .../browser/walletconnect-client.mjs | 15 +++++++++++--- docs/WALLET_PROVIDER.md | 9 ++++++--- elastos/CHANGELOG.md | 1 - scripts/lib/walletconnect-capsule-fixture.mjs | 6 +++--- scripts/walletconnect-capsule.test.mjs | 20 +++++++++++++++++++ 5 files changed, 41 insertions(+), 10 deletions(-) diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs index de66fef37..eb665544d 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -15,12 +15,21 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp const same = (a,b) => String(a).toLowerCase() === String(b).toLowerCase(); const signData = message => /^0[xX](?:[0-9a-fA-F]{2})*$/.test(message) ? '0x'+message.slice(2) : '0x'+[...new TextEncoder().encode(message)].map(b=>b.toString(16).padStart(2,'0')).join(''); + const retireAdapter = async () => { + let timer; + try { + await Promise.race([ + Promise.resolve().then(()=>adapter?.disconnectWalletConnectEvm({api:sessionApi})), + new Promise(resolve=>{timer=setTimeout(resolve,5000);}), + ]); + } catch {} finally { clearTimeout(timer); } + }; const connect = async () => { const config = await api('wallet/config'); const permission = await api('internet'); if (permission.status !== 'granted') throw new Error('Allow WalletConnect internet access in Inbox, then connect again.'); if (activeRevision !== undefined && activeRevision !== config.walletconnect.storage_revision) { - try { await adapter?.disconnectWalletConnectEvm({api:sessionApi}); } catch {} + await retireAdapter(); provider = undefined; adapter = undefined; clearMemory(); } activeRevision = config.walletconnect.storage_revision; @@ -41,7 +50,7 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp }; const disconnect = async () => { generation++; - try { await adapter?.disconnectWalletConnectEvm({api:sessionApi}); } + try { await retireAdapter(); } finally { provider = undefined; adapter = undefined; activeRevision = undefined; clearMemory(); await api('storage',{method:'DELETE'}); @@ -78,7 +87,7 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp if (!review || review.status !== 'pending' || !same(review.address,signer) || review.chain_namespace !== namespace) throw new Error('Select the requested account and network in your phone wallet, then review again.'); const ttl = review.expires_at - Math.ceil(Date.now()/1000); if (!Number.isSafeInteger(review.expires_at) || ttl <= 0 || review.intent === 'transaction_intent' && ttl < 300) throw new Error('Wallet request expires soon. Request a fresh review.'); - const supported = ['auth_challenge','browser_personal_sign','browser_typed_data_sign','capability_grant','credential','publish_envelope','transaction_intent','revocation']; + const supported = ['auth_challenge','browser_personal_sign','browser_typed_data_sign','capability_grant','credential','publish_envelope','protected_content_rights_signature','transaction_intent','revocation']; if (!supported.includes(review.intent)) throw new Error('This request type is unavailable in WalletConnect. Reject it in Wallet.'); if (review.intent === 'browser_typed_data_sign' && !provider.session?.namespaces?.eip155?.methods?.includes('eth_signTypedData_v4')) throw new Error('Typed data signing is unavailable in this pairing. Reject this request in Wallet or use another linked account.'); diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 2b61e1735..98969a4bb 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -274,10 +274,13 @@ Browser Storage holds UI preferences in memory and resets on reload. Protocol and keychain names raise `SecurityError` there. Runtime's private key/value store holds pairings, sessions and cryptographic keys, selected by the verified principal. The SDK uses the constant context `wallet-walletconnect`; Runtime's -principal boundary separates each person's files. The connector supplies no session migration. Disconnect clears session storage and the memory shim -while linked accounts stay in Wallet. Revocation clears session files; linked +principal boundary separates each person's files. The connector supplies no +session migration. Disconnect clears session storage and the memory shim while +linked accounts stay in Wallet. Revocation clears session files; linked account removal and principal removal also clear the affected principal's file. -A Runtime storage revision fences late writes and relay use from an old SDK +A cleanup failure after account or principal removal leaves that change saved +and records an operator-retry warning. Successful cleanup advances a Runtime +storage revision that fences late writes and relay use from an old SDK instance after cleanup. Reopening the connector starts a fresh instance. Inbox owns internet consent through one request and the owner's passkey. Allow diff --git a/elastos/CHANGELOG.md b/elastos/CHANGELOG.md index 6f2d97b5b..a89bfeaee 100644 --- a/elastos/CHANGELOG.md +++ b/elastos/CHANGELOG.md @@ -9,7 +9,6 @@ release's Added, Changed, Fixed, Removed and Security bullets before you update; ### Fixed - WalletConnect keeps its SDK in the connector capsule, uses capsule-scoped Runtime storage and relay access, and shows recovery instructions for interrupted transactions. - - Apps no longer open blank in Safari and other WebKit browsers. ## [2.0.1] - 2026-11-09 diff --git a/scripts/lib/walletconnect-capsule-fixture.mjs b/scripts/lib/walletconnect-capsule-fixture.mjs index 5e98eebe8..754417eaf 100644 --- a/scripts/lib/walletconnect-capsule-fixture.mjs +++ b/scripts/lib/walletconnect-capsule-fixture.mjs @@ -3,8 +3,8 @@ import { createWalletConnectClient } from '../../capsules/wallet-walletconnect/b export const address = `0x${'12'.repeat(20)}`, payloadHash=`0x${'34'.repeat(32)}`, transactionHash=`0x${'56'.repeat(32)}`; export async function exerciseWalletConnect(scenario='valid') { const clock=Date.now, calls=[],routes=[],events=new Map(); let changed=false, memoryCleared=false; - const signatureIntent=scenario.startsWith('signature-') || scenario.startsWith('typed') || scenario==='unsupported'; - const intent=scenario.startsWith('typed')?'browser_typed_data_sign':scenario==='unsupported'?'unavailable_intent':signatureIntent?'browser_personal_sign':'transaction_intent'; + const signatureIntent=scenario.startsWith('signature-') || scenario.startsWith('typed') || scenario==='unsupported' || scenario==='protected-content'; + const intent=scenario.startsWith('typed')?'browser_typed_data_sign':scenario==='unsupported'?'unavailable_intent':scenario==='protected-content'?'protected_content_rights_signature':signatureIntent?'browser_personal_sign':'transaction_intent'; const kind=scenario.replace(/^signature-/,''); const lifetime=scenario==='signature-short'?180:scenario==='long-request'?1800:600; const signature=`0x${'ab'.repeat(65)}`; @@ -28,7 +28,7 @@ export async function exerciseWalletConnect(scenario='valid') { if(path==='wallet/approvals')return {approval_requests:[{request_id:'approval:fixture',status:scenario==='approved'?'approved':'pending',address, intent,chain_namespace:'eip155:20',expires_at:Math.floor(clock()/1000)+lifetime}]}; if(path.endsWith('/approve'))return {handoff:{request_id:'approval:fixture',intent, - payload_hash:payloadHash,signer:address,signature_type:'personal_sign',message:'Runtime approval fixture', + payload_hash:payloadHash,signer:address,signature_type:'personal_sign',message:scenario==='protected-content'?'0x414243':'Runtime approval fixture', transaction:{from:address,to:`0x${'78'.repeat(20)}`,value:'0x1',data:'0x',gas:'0x5208',gasPrice:'0x1',nonce:'0x1',chainId:'0x14'}}, binding:{principal_id:'fixture',requested_by_actor:'documents',account_id:'fixture-account',chain_namespace:'eip155:20',payload_hash:payloadHash, expires_at:scenario==='expired'?1:Math.floor(clock()/1000)+lifetime}}; diff --git a/scripts/walletconnect-capsule.test.mjs b/scripts/walletconnect-capsule.test.mjs index 56183ed69..d50c29af8 100644 --- a/scripts/walletconnect-capsule.test.mjs +++ b/scripts/walletconnect-capsule.test.mjs @@ -42,3 +42,23 @@ test('a reset creates a fresh SDK API while old SDK writes keep their stale revi await assert.rejects(sessions[0]('storage',{method:'POST'}),/stale SDK/); assert.deepEqual(await sessions[1]('storage',{method:'POST'}),{}); }); + +test('protected-content rights signs the exact Runtime hex handoff with personal_sign',async()=>{ + const r=await exerciseWalletConnect('protected-content');assert.equal(r.error,undefined); + assert.deepEqual(r.calls.find(c=>c.method==='personal_sign').params.slice(0,1),['0x414243']); + assert.equal(JSON.parse(completed(r)[0].input.body).signature_type,'personal_sign'); +}); +test('a stalled old SDK disconnect cannot block a new storage generation',async t=>{ + t.mock.timers.enable({apis:['setTimeout']}); + const {createWalletConnectClient}=await import('../capsules/wallet-walletconnect/browser/walletconnect-client.mjs'); + let revision='"0"',loads=0;const signer=`0x${'12'.repeat(20)}`; + const provider={on(){},request:async({method})=>method==='eth_accounts'?[signer]:method==='eth_chainId'?'0x14':'fixture'}; + const api=async path=>path==='wallet/config'?{walletconnect:{project_id:'fixture',storage_revision:revision}}: + path==='internet'?{status:'granted'}:path.endsWith('/challenge')?{message:'fixture',expires_at:Date.now()/1000+600|0}:{}; + const client=createWalletConnectClient({api,origin:'http://localhost',loadAdapter:async()=>{loads++;return { + connectWalletConnectEvm:async()=>provider,disconnectWalletConnectEvm:()=>new Promise(()=>{}), + };}}); + await client.effect({kind:'link'});revision='"1"';const pending=client.effect({kind:'link'}); + for(let i=0;i<10;i++)await Promise.resolve();assert.equal(loads,1); + t.mock.timers.tick(5000);assert.deepEqual(await pending,{status:'linked'});assert.equal(loads,2); +}); From 7adcd6271349d0f35d6d8efdca3e86e3183a176c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 15:22:17 -0500 Subject: [PATCH 065/139] fix(walletconnect): place lifecycle unit tests after production items --- .../src/api/gateway_walletconnect.rs | 56 +++++++++---------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 341e682df..43165e6b5 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -841,34 +841,6 @@ async fn transport( anyhow::bail!("The local Exit transport is unavailable on this platform") } -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn walletconnect_socket_completion_survives_task_unwind() { - let (done, finished) = watch::channel(false); - let completion = SocketCompletion(done); - let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { - let _completion = completion; - panic!("fixture task failure"); - })); - assert!(panic.is_err()); - assert!(*finished.borrow()); - } - #[test] - fn walletconnect_heartbeat_and_idle_have_independent_deadlines() { - assert!(check_liveness(Duration::from_secs(44), Duration::from_secs(299)).is_ok()); - assert!(check_liveness(Duration::from_secs(45), Duration::ZERO) - .unwrap_err() - .to_string() - .contains("heartbeat")); - assert!(check_liveness(Duration::ZERO, Duration::from_secs(300)) - .unwrap_err() - .to_string() - .contains("idle")); - } -} - // Runtime owns these exact, principal-derived session paths; UI never selects a path. pub(crate) fn clear_principal_storage(data: &FsPath, principal: &str) -> anyhow::Result<()> { let _files = session_files_lock(data)?; @@ -1003,3 +975,31 @@ fn bump_storage_revision(data: &FsPath, name: &std::ffi::OsStr) -> anyhow::Resul .ok_or_else(|| anyhow::anyhow!("WalletConnect revision overflow"))?; crate::auth::atomic_write(&path, &serde_json::to_vec(&next)?) } + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn walletconnect_socket_completion_survives_task_unwind() { + let (done, finished) = watch::channel(false); + let completion = SocketCompletion(done); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _completion = completion; + panic!("fixture task failure"); + })); + assert!(panic.is_err()); + assert!(*finished.borrow()); + } + #[test] + fn walletconnect_heartbeat_and_idle_have_independent_deadlines() { + assert!(check_liveness(Duration::from_secs(44), Duration::from_secs(299)).is_ok()); + assert!(check_liveness(Duration::from_secs(45), Duration::ZERO) + .unwrap_err() + .to_string() + .contains("heartbeat")); + assert!(check_liveness(Duration::ZERO, Duration::from_secs(300)) + .unwrap_err() + .to_string() + .contains("idle")); + } +} From fc42aec4f790b69e4f10c01c79fa1c16f904ac1a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:19:41 -0500 Subject: [PATCH 066/139] fix(walletconnect): validate shared Exit config and preserve Browser routes --- capsules/exit-provider/src/lib.rs | 624 ++++++++++++++++++ capsules/exit-provider/src/main.rs | 619 +---------------- capsules/object-provider/Cargo.lock | 47 +- elastos/Cargo.lock | 11 + elastos/crates/elastos-server/Cargo.toml | 1 + .../crates/elastos-server/src/server_infra.rs | 12 +- .../src/setup/browser_config.rs | 41 ++ .../elastos-server/src/setup/walletconnect.rs | 77 ++- scripts/browser-source-home-config.mjs | 10 + 9 files changed, 792 insertions(+), 650 deletions(-) create mode 100644 capsules/exit-provider/src/lib.rs diff --git a/capsules/exit-provider/src/lib.rs b/capsules/exit-provider/src/lib.rs new file mode 100644 index 000000000..b72a16c52 --- /dev/null +++ b/capsules/exit-provider/src/lib.rs @@ -0,0 +1,624 @@ +//! Exit configuration parser shared by the provider and Runtime startup. +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::net::IpAddr; +use url::Url; + +pub const DEFAULT_REMOTE_CARRIER_EXIT_SERVICE: &str = "elastos://exit/open_stream"; +const MAX_CARRIER_CONNECT_TICKET_BYTES: usize = 8192; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExitConfig { + #[serde(default)] + pub backends: Vec, + #[serde(default)] + pub remote_carrier_exits: Vec, + #[serde(default = "default_timeout_secs")] + pub timeout_secs: u64, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExitBackendConfig { + pub id: String, + pub kind: ExitBackendKind, + pub allowed_hosts: Vec, + #[serde(default)] + pub allowed_schemes: Vec, + #[serde(default)] + pub allowed_ports: Vec, + #[serde(default)] + pub allow_private_targets: bool, + #[serde(default)] + pub allowed_private_targets: Vec, + #[serde(default = "default_max_body_bytes")] + pub max_body_bytes: usize, + #[serde(default)] + pub adapter_ipc: Option, + #[serde(default)] + pub relay_ipc: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct PrivateTargetConfig { + pub host: String, + pub ports: Vec, + #[serde(default)] + pub schemes: Vec, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct RemoteCarrierExitConfig { + pub id: String, + pub grant_id: String, + pub peer_did: String, + #[serde(default = "default_remote_carrier_service")] + pub carrier_service: String, + pub allowed_principals: Vec, + pub allowed_hosts: Vec, + #[serde(default)] + pub allowed_schemes: Vec, + #[serde(default)] + pub allowed_ports: Vec, + #[serde(default = "default_max_active_remote_streams")] + pub max_active_streams: u64, + #[serde(default)] + pub max_active_streams_per_principal: Option, + #[serde(default)] + pub expires_at: Option, + #[serde(default)] + pub connect_ticket: Option, +} + +impl RemoteCarrierExitConfig { + pub fn allows_target(&self, target: &Url) -> bool { + let Some(host) = target.host_str() else { + return false; + }; + let host = host.trim_matches(['[', ']']).to_ascii_lowercase(); + let host_allowed = self.allowed_hosts.iter().any(|allowed| { + let allowed = allowed.to_ascii_lowercase(); + if allowed == "*" { + return true; + } + if let Some(suffix) = allowed.strip_prefix("*.") { + host.ends_with(&format!(".{suffix}")) + } else { + host == allowed + } + }); + host_allowed + && self.allows_scheme(target.scheme()) + && self.allows_port(target.port_or_known_default()) + } + + pub fn allows_scheme(&self, scheme: &str) -> bool { + if self.allowed_schemes.is_empty() { + return matches!(scheme, "tcp" | "tls"); + } + self.allowed_schemes.iter().any(|allowed| allowed == scheme) + } + + pub fn allows_port(&self, port: Option) -> bool { + let Some(port) = port else { + return false; + }; + self.allowed_ports.is_empty() || self.allowed_ports.contains(&port) + } + + pub fn allows_principal(&self, principal_id: Option<&str>) -> bool { + let Some(principal_id) = principal_id else { + return false; + }; + self.allowed_principals + .iter() + .any(|allowed| allowed == "*" || allowed == principal_id) + } + + pub fn is_expired(&self, now: u64) -> bool { + self.expires_at + .map(|expires_at| expires_at <= now) + .unwrap_or(false) + } + + pub fn state(&self, now: u64) -> &'static str { + if self.is_expired(now) { + "expired" + } else { + "active" + } + } + + pub fn max_active_streams_per_principal(&self) -> u64 { + self.max_active_streams_per_principal + .unwrap_or(self.max_active_streams) + } +} + +impl ExitBackendConfig { + pub fn allows_target(&self, target: &Url) -> bool { + if self.allows_private_target(target) { + return true; + } + let Some(host) = target.host_str() else { + return false; + }; + let host = host.trim_matches(['[', ']']).to_ascii_lowercase(); + let host_allowed = self.allowed_hosts.iter().any(|allowed| { + let allowed = allowed.to_ascii_lowercase(); + if allowed == "*" { + return true; + } + if let Some(suffix) = allowed.strip_prefix("*.") { + host.ends_with(&format!(".{suffix}")) + } else { + host == allowed + } + }); + host_allowed + && self.allows_scheme(target.scheme()) + && self.allows_port(target.port_or_known_default()) + } + + pub fn allows_scheme(&self, scheme: &str) -> bool { + if self.allowed_schemes.is_empty() { + return match self.kind { + ExitBackendKind::StreamRelay => matches!(scheme, "tcp" | "tls"), + ExitBackendKind::HttpFetch => matches!(scheme, "http" | "https"), + }; + } + self.allowed_schemes.iter().any(|allowed| allowed == scheme) + } + + pub fn allows_port(&self, port: Option) -> bool { + let Some(port) = port else { + return false; + }; + self.allowed_ports.is_empty() || self.allowed_ports.contains(&port) + } + + pub fn allows_private_target(&self, target: &Url) -> bool { + let Some(host) = target.host_str() else { + return false; + }; + let Some(port) = target.port_or_known_default() else { + return false; + }; + let host = host.trim_matches(['[', ']']).to_ascii_lowercase(); + self.allowed_private_targets.iter().any(|private| { + private + .host + .trim_matches(['[', ']']) + .eq_ignore_ascii_case(&host) + && private.ports.contains(&port) + && (private.schemes.is_empty() + || private + .schemes + .iter() + .any(|scheme| scheme == target.scheme())) + }) + } +} + +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ExitBackendKind { + HttpFetch, + StreamRelay, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AdapterIpcConfig { + pub kind: AdapterIpcKind, + pub path: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RelayIpcConfig { + pub kind: RelayIpcKind, + pub path: String, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum AdapterIpcKind { + UnixSocket, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum RelayIpcKind { + UnixSocket, +} + +pub fn parse_config(config: Value) -> Result { + let mut config = match config.get("extra") { + Some(extra) if extra.is_null() => json!({}), + Some(extra) => extra.clone(), + None if looks_like_bridge_provider_config(&config) => json!({}), + None => config, + }; + // Services previously stamped the local relay schema on provider config. + // Accept that exact released mistake only for a remote-grant config; all + // remaining fields still pass the strict provider parser. + if config.get("schema").and_then(Value::as_str) == Some("elastos.browser.local-exit.config/v1") + && config + .get("remote_carrier_exits") + .is_some_and(Value::is_array) + { + config + .as_object_mut() + .expect("config with fields is an object") + .remove("schema"); + } + let config = serde_json::from_value::(config).map_err(|err| err.to_string())?; + if config.timeout_secs == 0 || config.timeout_secs > 60 { + return Err("exit-provider timeout_secs must be between 1 and 60".to_string()); + } + for backend in &config.backends { + validate_backend(backend)?; + } + let mut ids = std::collections::BTreeSet::new(); + let mut grants = std::collections::BTreeSet::new(); + for exit in &config.remote_carrier_exits { + validate_remote_carrier_exit(exit)?; + if !ids.insert(&exit.id) || !grants.insert(&exit.grant_id) { + return Err("remote Carrier Exit ids and grant ids must be unique".to_string()); + } + } + Ok(config) +} + +pub fn looks_like_bridge_provider_config(config: &Value) -> bool { + config.get("base_path").is_some() + || config.get("allowed_paths").is_some() + || config.get("read_only").is_some() + || config.get("encryption_key").is_some() +} + +pub fn validate_backend(backend: &ExitBackendConfig) -> Result<(), String> { + if !is_safe_id(&backend.id) { + return Err("exit backend id must be a safe identifier".to_string()); + } + if backend.allowed_hosts.is_empty() { + return Err(format!( + "exit backend '{}' must declare at least one allowed host", + backend.id + )); + } + if backend.max_body_bytes == 0 || backend.max_body_bytes > 1024 * 1024 { + return Err(format!( + "exit backend '{}' max_body_bytes must be between 1 and 1048576", + backend.id + )); + } + if let Some(adapter_ipc) = &backend.adapter_ipc { + if backend.kind != ExitBackendKind::StreamRelay { + return Err(format!( + "exit backend '{}' adapter_ipc is only valid for stream_relay backends", + backend.id + )); + } + validate_adapter_ipc(adapter_ipc)?; + } + if let Some(relay_ipc) = &backend.relay_ipc { + if backend.kind != ExitBackendKind::StreamRelay { + return Err(format!( + "exit backend '{}' relay_ipc is only valid for stream_relay backends", + backend.id + )); + } + if backend.adapter_ipc.is_none() { + return Err(format!( + "exit backend '{}' relay_ipc requires adapter_ipc", + backend.id + )); + } + validate_relay_ipc(relay_ipc)?; + } + if let (Some(adapter_ipc), Some(relay_ipc)) = (&backend.adapter_ipc, &backend.relay_ipc) { + if adapter_ipc.path == relay_ipc.path { + return Err(format!( + "exit backend '{}' adapter_ipc and relay_ipc paths must differ", + backend.id + )); + } + } + for host in &backend.allowed_hosts { + validate_allowed_host(host)?; + } + for scheme in &backend.allowed_schemes { + validate_allowed_scheme(backend.kind, scheme)?; + } + for port in &backend.allowed_ports { + if *port == 0 { + return Err(format!( + "exit backend '{}' allowed_ports must contain TCP ports between 1 and 65535", + backend.id + )); + } + } + for target in &backend.allowed_private_targets { + validate_private_target(&backend.id, backend.kind, target)?; + } + Ok(()) +} + +pub fn validate_private_target( + backend_id: &str, + backend_kind: ExitBackendKind, + target: &PrivateTargetConfig, +) -> Result<(), String> { + let host = target.host.trim(); + if host.is_empty() || host == "*" || host.starts_with("*.") { + return Err(format!( + "exit backend '{backend_id}' allowed_private_targets host must be an exact host" + )); + } + validate_host_shape(host)?; + if target.ports.is_empty() { + return Err(format!( + "exit backend '{backend_id}' allowed_private_targets ports must not be empty" + )); + } + for port in &target.ports { + if *port == 0 { + return Err(format!( + "exit backend '{backend_id}' allowed_private_targets ports must contain TCP ports between 1 and 65535" + )); + } + } + for scheme in &target.schemes { + validate_allowed_scheme(backend_kind, scheme)?; + } + Ok(()) +} + +pub fn validate_remote_carrier_exit(exit: &RemoteCarrierExitConfig) -> Result<(), String> { + if !is_safe_id(&exit.id) { + return Err("remote Carrier Exit id must be a safe identifier".to_string()); + } + if !is_safe_id(&exit.grant_id) { + return Err("remote Carrier Exit grant_id must be a safe identifier".to_string()); + } + validate_plain_token("remote Carrier Exit peer_did", &exit.peer_did)?; + validate_carrier_service(&exit.carrier_service)?; + if exit.allowed_principals.is_empty() { + return Err(format!( + "remote Carrier Exit '{}' must declare at least one allowed principal", + exit.id + )); + } + for principal in &exit.allowed_principals { + if principal != "*" { + validate_plain_token("remote Carrier Exit allowed_principals", principal)?; + } + } + if exit.allowed_hosts.is_empty() { + return Err(format!( + "remote Carrier Exit '{}' must declare at least one allowed host", + exit.id + )); + } + for host in &exit.allowed_hosts { + validate_allowed_host(host)?; + } + for scheme in &exit.allowed_schemes { + validate_allowed_scheme(ExitBackendKind::StreamRelay, scheme)?; + } + for port in &exit.allowed_ports { + if *port == 0 { + return Err(format!( + "remote Carrier Exit '{}' allowed_ports must contain TCP ports between 1 and 65535", + exit.id + )); + } + } + if exit.max_active_streams == 0 || exit.max_active_streams > 1024 { + return Err(format!( + "remote Carrier Exit '{}' max_active_streams must be between 1 and 1024", + exit.id + )); + } + let max_active_streams_per_principal = exit.max_active_streams_per_principal(); + if max_active_streams_per_principal == 0 + || max_active_streams_per_principal > exit.max_active_streams + { + return Err(format!( + "remote Carrier Exit '{}' max_active_streams_per_principal must be between 1 and max_active_streams", + exit.id + )); + } + if exit.expires_at == Some(0) { + return Err(format!( + "remote Carrier Exit '{}' expires_at must be a positive Unix timestamp", + exit.id + )); + } + let Some(connect_ticket) = &exit.connect_ticket else { + return Err(format!( + "remote Carrier Exit '{}' must declare connect_ticket for Browser Carrier stream dial", + exit.id + )); + }; + validate_carrier_connect_ticket(connect_ticket)?; + Ok(()) +} + +pub fn validate_allowed_scheme(kind: ExitBackendKind, scheme: &str) -> Result<(), String> { + let valid = match kind { + ExitBackendKind::StreamRelay => matches!(scheme, "tcp" | "tls"), + ExitBackendKind::HttpFetch => matches!(scheme, "http" | "https"), + }; + if valid { + Ok(()) + } else { + Err(format!( + "{kind:?} backend allowed_schemes may not contain '{scheme}'" + )) + } +} + +pub fn validate_plain_token(label: &str, value: &str) -> Result<(), String> { + if value.trim().is_empty() || value.trim() != value { + return Err(format!("{label} must not be empty or padded")); + } + if value + .bytes() + .any(|byte| byte.is_ascii_whitespace() || byte == b'\0') + { + return Err(format!("{label} must not contain whitespace or NUL")); + } + Ok(()) +} + +pub fn validate_carrier_service(service: &str) -> Result<(), String> { + validate_plain_token("remote Carrier Exit carrier_service", service)?; + if !service.starts_with("elastos://") { + return Err("remote Carrier Exit carrier_service must use elastos://".to_string()); + } + Ok(()) +} + +pub fn validate_carrier_connect_ticket(ticket: &str) -> Result<(), String> { + validate_plain_token("remote Carrier Exit connect_ticket", ticket)?; + if ticket.len() > MAX_CARRIER_CONNECT_TICKET_BYTES { + return Err(format!( + "remote Carrier Exit connect_ticket must be at most {MAX_CARRIER_CONNECT_TICKET_BYTES} bytes" + )); + } + Ok(()) +} + +pub fn validate_remote_exit_selection(value: Option<&str>) -> Result, String> { + let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else { + return Ok(None); + }; + if value.len() > 128 || !is_safe_id(value) { + return Err("remote_exit_id must be a safe identifier up to 128 bytes".to_string()); + } + Ok(Some(value)) +} + +pub fn validate_adapter_ipc(adapter_ipc: &AdapterIpcConfig) -> Result<(), String> { + validate_ipc_path("adapter_ipc", &adapter_ipc.path) +} + +pub fn validate_relay_ipc(relay_ipc: &RelayIpcConfig) -> Result<(), String> { + validate_ipc_path("relay_ipc", &relay_ipc.path) +} + +pub fn validate_ipc_path(label: &str, path: &str) -> Result<(), String> { + if path.is_empty() { + return Err(format!("{label} path must not be empty")); + } + if !path.starts_with('/') { + return Err(format!("{label} path must be absolute")); + } + if path + .bytes() + .any(|byte| byte.is_ascii_whitespace() || byte == b'\0') + { + return Err(format!("{label} path must not contain whitespace or NUL")); + } + Ok(()) +} + +pub fn validate_allowed_host(host: &str) -> Result<(), String> { + let host = host.trim(); + if host.is_empty() { + return Err("allowed host must not be empty".to_string()); + } + if host == "*" { + return Ok(()); + } + let host = host.strip_prefix("*.").unwrap_or(host); + validate_public_host_shape(host) +} + +pub fn validate_public_host(host: &str) -> Result<(), String> { + let host = host.trim().trim_matches(['[', ']']); + validate_public_host_shape(host)?; + if let Ok(ip) = host.parse::() { + return validate_public_ip(ip).map_err(|_| format!("private IP blocked: {host}")); + } + Ok(()) +} + +pub fn validate_public_host_shape(host: &str) -> Result<(), String> { + validate_host_shape(host)?; + let lower = host.to_ascii_lowercase(); + if lower == "localhost" || lower.ends_with(".localhost") || lower.ends_with(".local") { + return Err(format!("private host blocked: {host}")); + } + Ok(()) +} + +pub fn validate_host_shape(host: &str) -> Result<(), String> { + if host.is_empty() { + return Err("host must not be empty".to_string()); + } + if host + .bytes() + .any(|byte| byte.is_ascii_whitespace() || matches!(byte, b'/' | b'\\' | b'\0')) + { + return Err(format!("invalid host: {host}")); + } + Ok(()) +} + +pub fn validate_public_ip(ip: IpAddr) -> Result<(), ()> { + match ip { + IpAddr::V4(ip) => { + if ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_unspecified() + || ip.is_broadcast() + { + Err(()) + } else { + Ok(()) + } + } + IpAddr::V6(ip) => { + if ip.is_loopback() + || ip.is_unspecified() + || ip.is_unique_local() + || ip.is_unicast_link_local() + { + Err(()) + } else { + Ok(()) + } + } + } +} + +pub fn is_safe_id(value: &str) -> bool { + !value.is_empty() + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b':' | b'-' | b'_')) +} + +pub fn default_timeout_secs() -> u64 { + 10 +} + +pub fn default_max_body_bytes() -> usize { + 64 * 1024 +} + +pub fn default_max_active_remote_streams() -> u64 { + 8 +} + +pub fn default_remote_carrier_service() -> String { + DEFAULT_REMOTE_CARRIER_EXIT_SERVICE.to_string() +} diff --git a/capsules/exit-provider/src/main.rs b/capsules/exit-provider/src/main.rs index 65b3eb12a..fb944a7f3 100644 --- a/capsules/exit-provider/src/main.rs +++ b/capsules/exit-provider/src/main.rs @@ -5,6 +5,7 @@ //! an operator configures a real local, Carrier-routed, privacy, paid, or //! enterprise exit backend. +use exit_provider::*; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -13,8 +14,6 @@ use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use url::Url; -const DEFAULT_REMOTE_CARRIER_EXIT_SERVICE: &str = "elastos://exit/open_stream"; -const MAX_CARRIER_CONNECT_TICKET_BYTES: usize = 8192; const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); #[derive(Debug, Deserialize)] @@ -920,143 +919,12 @@ impl ExitProvider { } } -#[derive(Debug, Deserialize)] -#[serde(deny_unknown_fields)] -struct ExitConfig { - #[serde(default)] - backends: Vec, - #[serde(default)] - remote_carrier_exits: Vec, - #[serde(default = "default_timeout_secs")] - timeout_secs: u64, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -struct ExitBackendConfig { - id: String, - kind: ExitBackendKind, - allowed_hosts: Vec, - #[serde(default)] - allowed_schemes: Vec, - #[serde(default)] - allowed_ports: Vec, - #[serde(default)] - allow_private_targets: bool, - #[serde(default)] - allowed_private_targets: Vec, - #[serde(default = "default_max_body_bytes")] - max_body_bytes: usize, - #[serde(default)] - adapter_ipc: Option, - #[serde(default)] - relay_ipc: Option, -} - -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct PrivateTargetConfig { - host: String, - ports: Vec, - #[serde(default)] - schemes: Vec, -} - -#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] -#[serde(deny_unknown_fields)] -struct RemoteCarrierExitConfig { - id: String, - grant_id: String, - peer_did: String, - #[serde(default = "default_remote_carrier_service")] - carrier_service: String, - allowed_principals: Vec, - allowed_hosts: Vec, - #[serde(default)] - allowed_schemes: Vec, - #[serde(default)] - allowed_ports: Vec, - #[serde(default = "default_max_active_remote_streams")] - max_active_streams: u64, - #[serde(default)] - max_active_streams_per_principal: Option, - #[serde(default)] - expires_at: Option, - #[serde(default)] - connect_ticket: Option, -} - #[derive(Debug, Clone)] struct RemoteActiveStream { exit_id: String, principal_id: String, } -impl RemoteCarrierExitConfig { - fn allows_target(&self, target: &Url) -> bool { - let Some(host) = target.host_str() else { - return false; - }; - let host = host.trim_matches(['[', ']']).to_ascii_lowercase(); - let host_allowed = self.allowed_hosts.iter().any(|allowed| { - let allowed = allowed.to_ascii_lowercase(); - if allowed == "*" { - return true; - } - if let Some(suffix) = allowed.strip_prefix("*.") { - host.ends_with(&format!(".{suffix}")) - } else { - host == allowed - } - }); - host_allowed - && self.allows_scheme(target.scheme()) - && self.allows_port(target.port_or_known_default()) - } - - fn allows_scheme(&self, scheme: &str) -> bool { - if self.allowed_schemes.is_empty() { - return matches!(scheme, "tcp" | "tls"); - } - self.allowed_schemes.iter().any(|allowed| allowed == scheme) - } - - fn allows_port(&self, port: Option) -> bool { - let Some(port) = port else { - return false; - }; - self.allowed_ports.is_empty() || self.allowed_ports.contains(&port) - } - - fn allows_principal(&self, principal_id: Option<&str>) -> bool { - let Some(principal_id) = principal_id else { - return false; - }; - self.allowed_principals - .iter() - .any(|allowed| allowed == "*" || allowed == principal_id) - } - - fn is_expired(&self, now: u64) -> bool { - self.expires_at - .map(|expires_at| expires_at <= now) - .unwrap_or(false) - } - - fn state(&self, now: u64) -> &'static str { - if self.is_expired(now) { - "expired" - } else { - "active" - } - } - - fn max_active_streams_per_principal(&self) -> u64 { - self.max_active_streams_per_principal - .unwrap_or(self.max_active_streams) - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum RemoteExitReject { NoPolicyMatch, @@ -1065,409 +933,6 @@ enum RemoteExitReject { Expired, } -impl ExitBackendConfig { - fn allows_target(&self, target: &Url) -> bool { - if self.allows_private_target(target) { - return true; - } - let Some(host) = target.host_str() else { - return false; - }; - let host = host.trim_matches(['[', ']']).to_ascii_lowercase(); - let host_allowed = self.allowed_hosts.iter().any(|allowed| { - let allowed = allowed.to_ascii_lowercase(); - if allowed == "*" { - return true; - } - if let Some(suffix) = allowed.strip_prefix("*.") { - host.ends_with(&format!(".{suffix}")) - } else { - host == allowed - } - }); - host_allowed - && self.allows_scheme(target.scheme()) - && self.allows_port(target.port_or_known_default()) - } - - fn allows_scheme(&self, scheme: &str) -> bool { - if self.allowed_schemes.is_empty() { - return match self.kind { - ExitBackendKind::StreamRelay => matches!(scheme, "tcp" | "tls"), - ExitBackendKind::HttpFetch => matches!(scheme, "http" | "https"), - }; - } - self.allowed_schemes.iter().any(|allowed| allowed == scheme) - } - - fn allows_port(&self, port: Option) -> bool { - let Some(port) = port else { - return false; - }; - self.allowed_ports.is_empty() || self.allowed_ports.contains(&port) - } - - fn allows_private_target(&self, target: &Url) -> bool { - let Some(host) = target.host_str() else { - return false; - }; - let Some(port) = target.port_or_known_default() else { - return false; - }; - let host = host.trim_matches(['[', ']']).to_ascii_lowercase(); - self.allowed_private_targets.iter().any(|private| { - private - .host - .trim_matches(['[', ']']) - .eq_ignore_ascii_case(&host) - && private.ports.contains(&port) - && (private.schemes.is_empty() - || private - .schemes - .iter() - .any(|scheme| scheme == target.scheme())) - }) - } -} - -#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum ExitBackendKind { - HttpFetch, - StreamRelay, -} - -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct AdapterIpcConfig { - kind: AdapterIpcKind, - path: String, -} - -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -struct RelayIpcConfig { - kind: RelayIpcKind, - path: String, -} - -#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum AdapterIpcKind { - UnixSocket, -} - -#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -enum RelayIpcKind { - UnixSocket, -} - -fn parse_config(config: Value) -> Result { - let mut config = match config.get("extra") { - Some(extra) if extra.is_null() => json!({}), - Some(extra) => extra.clone(), - None if looks_like_bridge_provider_config(&config) => json!({}), - None => config, - }; - // Services previously stamped the local relay schema on provider config. - // Accept that exact released mistake only for a remote-grant config; all - // remaining fields still pass the strict provider parser. - if config.get("schema").and_then(Value::as_str) == Some("elastos.browser.local-exit.config/v1") - && config - .get("remote_carrier_exits") - .is_some_and(Value::is_array) - { - config - .as_object_mut() - .expect("config with fields is an object") - .remove("schema"); - } - let config = serde_json::from_value::(config).map_err(|err| err.to_string())?; - if config.timeout_secs == 0 || config.timeout_secs > 60 { - return Err("exit-provider timeout_secs must be between 1 and 60".to_string()); - } - for backend in &config.backends { - validate_backend(backend)?; - } - let mut ids = std::collections::BTreeSet::new(); - let mut grants = std::collections::BTreeSet::new(); - for exit in &config.remote_carrier_exits { - validate_remote_carrier_exit(exit)?; - if !ids.insert(&exit.id) || !grants.insert(&exit.grant_id) { - return Err("remote Carrier Exit ids and grant ids must be unique".to_string()); - } - } - Ok(config) -} - -fn looks_like_bridge_provider_config(config: &Value) -> bool { - config.get("base_path").is_some() - || config.get("allowed_paths").is_some() - || config.get("read_only").is_some() - || config.get("encryption_key").is_some() -} - -fn validate_backend(backend: &ExitBackendConfig) -> Result<(), String> { - if !is_safe_id(&backend.id) { - return Err("exit backend id must be a safe identifier".to_string()); - } - if backend.allowed_hosts.is_empty() { - return Err(format!( - "exit backend '{}' must declare at least one allowed host", - backend.id - )); - } - if backend.max_body_bytes == 0 || backend.max_body_bytes > 1024 * 1024 { - return Err(format!( - "exit backend '{}' max_body_bytes must be between 1 and 1048576", - backend.id - )); - } - if let Some(adapter_ipc) = &backend.adapter_ipc { - if backend.kind != ExitBackendKind::StreamRelay { - return Err(format!( - "exit backend '{}' adapter_ipc is only valid for stream_relay backends", - backend.id - )); - } - validate_adapter_ipc(adapter_ipc)?; - } - if let Some(relay_ipc) = &backend.relay_ipc { - if backend.kind != ExitBackendKind::StreamRelay { - return Err(format!( - "exit backend '{}' relay_ipc is only valid for stream_relay backends", - backend.id - )); - } - if backend.adapter_ipc.is_none() { - return Err(format!( - "exit backend '{}' relay_ipc requires adapter_ipc", - backend.id - )); - } - validate_relay_ipc(relay_ipc)?; - } - if let (Some(adapter_ipc), Some(relay_ipc)) = (&backend.adapter_ipc, &backend.relay_ipc) { - if adapter_ipc.path == relay_ipc.path { - return Err(format!( - "exit backend '{}' adapter_ipc and relay_ipc paths must differ", - backend.id - )); - } - } - for host in &backend.allowed_hosts { - validate_allowed_host(host)?; - } - for scheme in &backend.allowed_schemes { - validate_allowed_scheme(backend.kind, scheme)?; - } - for port in &backend.allowed_ports { - if *port == 0 { - return Err(format!( - "exit backend '{}' allowed_ports must contain TCP ports between 1 and 65535", - backend.id - )); - } - } - for target in &backend.allowed_private_targets { - validate_private_target(&backend.id, backend.kind, target)?; - } - Ok(()) -} - -fn validate_private_target( - backend_id: &str, - backend_kind: ExitBackendKind, - target: &PrivateTargetConfig, -) -> Result<(), String> { - let host = target.host.trim(); - if host.is_empty() || host == "*" || host.starts_with("*.") { - return Err(format!( - "exit backend '{backend_id}' allowed_private_targets host must be an exact host" - )); - } - validate_host_shape(host)?; - if target.ports.is_empty() { - return Err(format!( - "exit backend '{backend_id}' allowed_private_targets ports must not be empty" - )); - } - for port in &target.ports { - if *port == 0 { - return Err(format!( - "exit backend '{backend_id}' allowed_private_targets ports must contain TCP ports between 1 and 65535" - )); - } - } - for scheme in &target.schemes { - validate_allowed_scheme(backend_kind, scheme)?; - } - Ok(()) -} - -fn validate_remote_carrier_exit(exit: &RemoteCarrierExitConfig) -> Result<(), String> { - if !is_safe_id(&exit.id) { - return Err("remote Carrier Exit id must be a safe identifier".to_string()); - } - if !is_safe_id(&exit.grant_id) { - return Err("remote Carrier Exit grant_id must be a safe identifier".to_string()); - } - validate_plain_token("remote Carrier Exit peer_did", &exit.peer_did)?; - validate_carrier_service(&exit.carrier_service)?; - if exit.allowed_principals.is_empty() { - return Err(format!( - "remote Carrier Exit '{}' must declare at least one allowed principal", - exit.id - )); - } - for principal in &exit.allowed_principals { - if principal != "*" { - validate_plain_token("remote Carrier Exit allowed_principals", principal)?; - } - } - if exit.allowed_hosts.is_empty() { - return Err(format!( - "remote Carrier Exit '{}' must declare at least one allowed host", - exit.id - )); - } - for host in &exit.allowed_hosts { - validate_allowed_host(host)?; - } - for scheme in &exit.allowed_schemes { - validate_allowed_scheme(ExitBackendKind::StreamRelay, scheme)?; - } - for port in &exit.allowed_ports { - if *port == 0 { - return Err(format!( - "remote Carrier Exit '{}' allowed_ports must contain TCP ports between 1 and 65535", - exit.id - )); - } - } - if exit.max_active_streams == 0 || exit.max_active_streams > 1024 { - return Err(format!( - "remote Carrier Exit '{}' max_active_streams must be between 1 and 1024", - exit.id - )); - } - let max_active_streams_per_principal = exit.max_active_streams_per_principal(); - if max_active_streams_per_principal == 0 - || max_active_streams_per_principal > exit.max_active_streams - { - return Err(format!( - "remote Carrier Exit '{}' max_active_streams_per_principal must be between 1 and max_active_streams", - exit.id - )); - } - if exit.expires_at == Some(0) { - return Err(format!( - "remote Carrier Exit '{}' expires_at must be a positive Unix timestamp", - exit.id - )); - } - let Some(connect_ticket) = &exit.connect_ticket else { - return Err(format!( - "remote Carrier Exit '{}' must declare connect_ticket for Browser Carrier stream dial", - exit.id - )); - }; - validate_carrier_connect_ticket(connect_ticket)?; - Ok(()) -} - -fn validate_allowed_scheme(kind: ExitBackendKind, scheme: &str) -> Result<(), String> { - let valid = match kind { - ExitBackendKind::StreamRelay => matches!(scheme, "tcp" | "tls"), - ExitBackendKind::HttpFetch => matches!(scheme, "http" | "https"), - }; - if valid { - Ok(()) - } else { - Err(format!( - "{kind:?} backend allowed_schemes may not contain '{scheme}'" - )) - } -} - -fn validate_plain_token(label: &str, value: &str) -> Result<(), String> { - if value.trim().is_empty() || value.trim() != value { - return Err(format!("{label} must not be empty or padded")); - } - if value - .bytes() - .any(|byte| byte.is_ascii_whitespace() || byte == b'\0') - { - return Err(format!("{label} must not contain whitespace or NUL")); - } - Ok(()) -} - -fn validate_carrier_service(service: &str) -> Result<(), String> { - validate_plain_token("remote Carrier Exit carrier_service", service)?; - if !service.starts_with("elastos://") { - return Err("remote Carrier Exit carrier_service must use elastos://".to_string()); - } - Ok(()) -} - -fn validate_carrier_connect_ticket(ticket: &str) -> Result<(), String> { - validate_plain_token("remote Carrier Exit connect_ticket", ticket)?; - if ticket.len() > MAX_CARRIER_CONNECT_TICKET_BYTES { - return Err(format!( - "remote Carrier Exit connect_ticket must be at most {MAX_CARRIER_CONNECT_TICKET_BYTES} bytes" - )); - } - Ok(()) -} - -fn validate_remote_exit_selection(value: Option<&str>) -> Result, String> { - let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else { - return Ok(None); - }; - if value.len() > 128 || !is_safe_id(value) { - return Err("remote_exit_id must be a safe identifier up to 128 bytes".to_string()); - } - Ok(Some(value)) -} - -fn validate_adapter_ipc(adapter_ipc: &AdapterIpcConfig) -> Result<(), String> { - validate_ipc_path("adapter_ipc", &adapter_ipc.path) -} - -fn validate_relay_ipc(relay_ipc: &RelayIpcConfig) -> Result<(), String> { - validate_ipc_path("relay_ipc", &relay_ipc.path) -} - -fn validate_ipc_path(label: &str, path: &str) -> Result<(), String> { - if path.is_empty() { - return Err(format!("{label} path must not be empty")); - } - if !path.starts_with('/') { - return Err(format!("{label} path must be absolute")); - } - if path - .bytes() - .any(|byte| byte.is_ascii_whitespace() || byte == b'\0') - { - return Err(format!("{label} path must not contain whitespace or NUL")); - } - Ok(()) -} - -fn validate_allowed_host(host: &str) -> Result<(), String> { - let host = host.trim(); - if host.is_empty() { - return Err("allowed host must not be empty".to_string()); - } - if host == "*" { - return Ok(()); - } - let host = host.strip_prefix("*.").unwrap_or(host); - validate_public_host_shape(host) -} - fn validate_target(raw: &str) -> Result { let parsed = Url::parse(raw).map_err(|err| err.to_string())?; if !matches!(parsed.scheme(), "tcp" | "tls" | "http" | "https") { @@ -1494,72 +959,6 @@ fn validate_http_fetch_url(raw: &str) -> Result { Ok(parsed) } -fn validate_public_host(host: &str) -> Result<(), String> { - let host = host.trim().trim_matches(['[', ']']); - validate_public_host_shape(host)?; - if let Ok(ip) = host.parse::() { - return validate_public_ip(ip).map_err(|_| format!("private IP blocked: {host}")); - } - Ok(()) -} - -fn validate_public_host_shape(host: &str) -> Result<(), String> { - validate_host_shape(host)?; - let lower = host.to_ascii_lowercase(); - if lower == "localhost" || lower.ends_with(".localhost") || lower.ends_with(".local") { - return Err(format!("private host blocked: {host}")); - } - Ok(()) -} - -fn validate_host_shape(host: &str) -> Result<(), String> { - if host.is_empty() { - return Err("host must not be empty".to_string()); - } - if host - .bytes() - .any(|byte| byte.is_ascii_whitespace() || matches!(byte, b'/' | b'\\' | b'\0')) - { - return Err(format!("invalid host: {host}")); - } - Ok(()) -} - -fn validate_public_ip(ip: IpAddr) -> Result<(), ()> { - match ip { - IpAddr::V4(ip) => { - if ip.is_private() - || ip.is_loopback() - || ip.is_link_local() - || ip.is_unspecified() - || ip.is_broadcast() - { - Err(()) - } else { - Ok(()) - } - } - IpAddr::V6(ip) => { - if ip.is_loopback() - || ip.is_unspecified() - || ip.is_unique_local() - || ip.is_unicast_link_local() - { - Err(()) - } else { - Ok(()) - } - } - } -} - -fn is_safe_id(value: &str) -> bool { - !value.is_empty() - && value - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b':' | b'-' | b'_')) -} - fn validate_stream_nonce(value: Option<&str>) -> Result, &'static str> { let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else { return Ok(None); @@ -1591,22 +990,6 @@ fn default_method() -> String { "GET".to_string() } -fn default_timeout_secs() -> u64 { - 10 -} - -fn default_max_body_bytes() -> usize { - 64 * 1024 -} - -fn default_max_active_remote_streams() -> u64 { - 8 -} - -fn default_remote_carrier_service() -> String { - DEFAULT_REMOTE_CARRIER_EXIT_SERVICE.to_string() -} - fn current_unix_seconds() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) diff --git a/capsules/object-provider/Cargo.lock b/capsules/object-provider/Cargo.lock index aebbe2ed4..cae2aec87 100644 --- a/capsules/object-provider/Cargo.lock +++ b/capsules/object-provider/Cargo.lock @@ -129,7 +129,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -140,7 +140,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1648,6 +1648,7 @@ dependencies = [ "elastos-storage", "elastos-tls", "elastos-wallet-contract", + "exit-provider", "flate2", "futures-lite", "futures-util", @@ -1827,7 +1828,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", +] + +[[package]] +name = "exit-provider" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "ureq", + "url", ] [[package]] @@ -3647,7 +3658,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4274,7 +4285,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4612,7 +4623,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4671,7 +4682,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5083,7 +5094,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5279,7 +5290,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5800,6 +5811,22 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64", + "flate2", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + [[package]] name = "url" version = "2.5.8" @@ -6389,7 +6416,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index 9b8cfe4b1..b4b987f46 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -1686,6 +1686,7 @@ dependencies = [ "elastos-storage", "elastos-tls", "elastos-wallet-contract", + "exit-provider", "flate2", "futures-lite", "futures-util", @@ -1905,6 +1906,16 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "exit-provider" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "ureq", + "url", +] + [[package]] name = "fallible-iterator" version = "0.3.0" diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index 045861d18..b91ef37a4 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -10,6 +10,7 @@ name = "elastos" path = "src/main.rs" [dependencies] +exit-provider = { path = "../../../capsules/exit-provider" } elastos-runtime = { path = "../elastos-runtime" } elastos-common = { path = "../elastos-common" } elastos-storage = { path = "../elastos-storage" } diff --git a/elastos/crates/elastos-server/src/server_infra.rs b/elastos/crates/elastos-server/src/server_infra.rs index 2410dba72..0e25cafe1 100644 --- a/elastos/crates/elastos-server/src/server_infra.rs +++ b/elastos/crates/elastos-server/src/server_infra.rs @@ -1241,16 +1241,10 @@ async fn setup_server_infrastructure_impl( Ok(Some(path)) => { let existing_exit = exit_provider_config_from_env(&data_dir).unwrap_or(serde_json::Value::Null); - let extra = match elastos_server::setup::walletconnect::merge_exit_config( - existing_exit.clone(), + let extra = elastos_server::setup::walletconnect::exit_config( + existing_exit, walletconnect_exit.as_ref().map(|(_, provider)| provider), - ) { - Ok(config) => config, - Err(error) => { - tracing::warn!(%error, "Exit configuration needs repair"); - existing_exit - } - }; + ); let exit_config = provider::BridgeProviderConfig { extra, ..Default::default() diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index 3f66b14a7..d3f81d2d9 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -5,6 +5,47 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; const GENERATOR: &str = include_str!("../../../../../scripts/browser-source-home-config.mjs"); +/// WalletConnect uses Browser's stable, short IPC names without selecting an Engine. +pub(super) fn walletconnect_socket_paths( + data: &Path, + platform: &str, +) -> anyhow::Result { + let mut child = Command::new("node") + .env_clear() + .args([ + "--input-type=module", + "-", + "--walletconnect-socket-paths", + "--data-dir", + ]) + .arg(data) + .args(["--platform", platform]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn()?; + child + .stdin + .take() + .unwrap() + .write_all(GENERATOR.as_bytes())?; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while child.try_wait()?.is_none() { + if std::time::Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + anyhow::bail!("WalletConnect IPC configuration timed out"); + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let output = child.wait_with_output()?; + anyhow::ensure!( + output.status.success(), + "WalletConnect IPC configuration failed" + ); + Ok(serde_json::from_slice(&output.stdout)?) +} + const CONFIG_FILES: [&str; 4] = [ "exit-provider.json", "browser-local-exit.json", diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs index f2657f9e0..827c80f62 100644 --- a/elastos/crates/elastos-server/src/setup/walletconnect.rs +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -6,7 +6,9 @@ pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, ser if !matches!(platform, "darwin-arm64" | "linux-amd64" | "linux-arm64") { return None; } - let socket = data.join("walletconnect-exit.sock"); + let sockets = super::browser_config::walletconnect_socket_paths(data, platform).ok()?; + let adapter = sockets["adapter"].as_str()?; + let socket = sockets["relay"].as_str()?; let hosts = ["relay.walletconnect.org", "relay.walletconnect.com"]; let helper = serde_json::json!({ "schema":"elastos.browser.local-exit.config/v1", "relay_ipc_path":socket, @@ -16,7 +18,7 @@ pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, ser let provider = serde_json::json!({"backends":[{ "id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":hosts, "allowed_schemes":["tls"], "allowed_ports":[443], - "adapter_ipc":{"kind":"unix_socket","path":socket}, + "adapter_ipc":{"kind":"unix_socket","path":adapter}, "relay_ipc":{"kind":"unix_socket","path":socket}, }]}); Some((helper, provider)) @@ -48,11 +50,28 @@ pub fn merge_exit_config( "WalletConnect Exit backend has a conflicting route" ); } else { - backends.insert(0, managed.clone()); + // Exit matches local backends in list order. Browser keeps first match; + // WalletConnect supplies a route only when earlier backends do not match. + backends.push(managed.clone()); } + exit_provider::parse_config(existing.clone()).map_err(anyhow::Error::msg)?; Ok(existing) } +/// A refused WalletConnect addition leaves the owner's Exit selection intact. +pub fn exit_config( + existing: serde_json::Value, + walletconnect: Option<&serde_json::Value>, +) -> serde_json::Value { + match merge_exit_config(existing.clone(), walletconnect) { + Ok(config) => config, + Err(_) => { + tracing::warn!("WalletConnect Exit configuration was refused; starting the existing Exit configuration"); + existing + } + } +} + #[cfg(all(test, unix))] mod tests { use super::*; @@ -60,7 +79,10 @@ mod tests { #[test] fn walletconnect_local_exit_needs_pinned_config_and_uses_relay_hosts_only() { - let data = tempfile::tempdir().unwrap(); + let data = tempfile::Builder::new() + .prefix("Application Support ") + .tempdir() + .unwrap(); assert!(local_exit(data.path(), "darwin-arm64").is_none()); let sdk = data .path() @@ -97,25 +119,54 @@ mod tests { provider["backends"][0]["allowed_schemes"], serde_json::json!(["tls"]) ); + let parsed = exit_provider::parse_config(provider.clone()).unwrap(); + assert_ne!( + parsed.backends[0].adapter_ipc.as_ref().unwrap().path, + parsed.backends[0].relay_ipc.as_ref().unwrap().path + ); + assert!(helper["relay_ipc_path"].as_str().unwrap().len() < 104); std::fs::write(sdk, "tampered").unwrap(); assert!(local_exit(data.path(), "darwin-arm64").is_none()); } #[test] fn walletconnect_keeps_existing_remote_and_local_exit_configuration() { - let remote = - serde_json::json!({"backends":[], "remote_carrier_exits":[{"id":"owner-remote"}]}); - let wc = serde_json::json!({"backends":[{"id":"walletconnect-local-exit"}]}); + let remote = serde_json::json!({"backends":[], "timeout_secs":12}); + let wc = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"]}]}); let merged = merge_exit_config(remote.clone(), Some(&wc)).unwrap(); - assert_eq!( - merged["remote_carrier_exits"], - remote["remote_carrier_exits"] - ); + assert_eq!(merged["timeout_secs"], remote["timeout_secs"]); assert_eq!(merged["backends"], wc["backends"]); - let local = serde_json::json!({"backends":[{"id":"owner-local"}]}); + let local = serde_json::json!({"backends":[{"id":"owner-local", "kind":"stream_relay", "allowed_hosts":["*"]}]}); let merged = merge_exit_config(local.clone(), Some(&wc)).unwrap(); - assert_eq!(merged["backends"][1], local["backends"][0]); + assert_eq!(merged["backends"][0], local["backends"][0]); assert_eq!(merge_exit_config(remote.clone(), None).unwrap(), remote); assert!(merge_exit_config(serde_json::json!({"backends":false}), Some(&wc)).is_err()); } + #[test] + fn walletconnect_refused_merge_preserves_browser_exit_and_matching_order() { + let browser = serde_json::json!({"backends":[{"id":"browser", "kind":"stream_relay", "allowed_hosts":["*"]}]}); + let bad = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"], + "adapter_ipc":{"kind":"unix_socket","path":"/tmp/same.sock"}, "relay_ipc":{"kind":"unix_socket","path":"/tmp/same.sock"}}]}); + assert!(merge_exit_config(browser.clone(), Some(&bad)).is_err()); + assert_eq!(exit_config(browser.clone(), Some(&bad)), browser); + let good = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"]}]}); + let merged = exit_config(browser, Some(&good)); + let parsed = exit_provider::parse_config(merged).unwrap(); + for host in [ + "relay.walletconnect.org", + "relay.walletconnect.com", + "example.org", + ] { + let target = url::Url::parse(&format!("tls://{host}:443")).unwrap(); + assert_eq!( + parsed + .backends + .iter() + .find(|b| b.allows_target(&target)) + .unwrap() + .id, + "browser" + ); + } + } } diff --git a/scripts/browser-source-home-config.mjs b/scripts/browser-source-home-config.mjs index 625c57ef8..b3976c005 100755 --- a/scripts/browser-source-home-config.mjs +++ b/scripts/browser-source-home-config.mjs @@ -79,6 +79,9 @@ function parseArgs(argv) { return argv[i]; }; switch (arg) { + case "--walletconnect-socket-paths": + args.walletconnectSocketPaths = true; + break; case "--help": case "-h": console.log(usage()); @@ -708,6 +711,13 @@ function main() { throw new Error("--platform must be linux-amd64, linux-arm64, or darwin-arm64"); } validateAbsolute("--data-dir", args.dataDir); + if (args.walletconnectSocketPaths) { + console.log(JSON.stringify({ + adapter: runtimeSocketPath(args, "wc-adapter"), + relay: runtimeSocketPath(args, "wc-relay"), + })); + return; + } const outDir = args.outDir || path.join(args.dataDir, "config"); validateAbsolute("--out-dir", outDir); if (args.platform === "linux-amd64") { From 0a00a76efc73b2f4434830c6b26898b7ff6000de Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:20:18 -0500 Subject: [PATCH 067/139] fix(walletconnect): admit the exact opaque WebKit relay handshake --- .../elastos-server/src/api/gateway_site.rs | 15 +++ .../api/gateway_tests/wallet/walletconnect.rs | 93 +++++++++++++++++++ .../wallet/walletconnect_real_relay.rs | 8 ++ 3 files changed, 116 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_site.rs b/elastos/crates/elastos-server/src/api/gateway_site.rs index e39b83ec6..50f2a57d3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_site.rs +++ b/elastos/crates/elastos-server/src/api/gateway_site.rs @@ -326,12 +326,27 @@ pub(super) async fn refuse_content_api_resources( || headers .get("sec-fetch-mode") .is_some_and(|value| value == "navigate"); + // This connection redeems a single-use ticket after upgrade. WebKit marks + // opaque WebSockets as a cross-site websocket destination, rather than empty. + let walletconnect_websocket = request.uri().path() == "/api/apps/wallet-walletconnect/relay" + && request.method() == axum::http::Method::GET + && headers.get("origin").is_some_and(|value| value == "null") + && headers + .get("upgrade") + .is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"websocket")) + && headers + .get("sec-fetch-mode") + .is_none_or(|value| value == "websocket") + && headers + .get("sec-fetch-dest") + .is_some_and(|value| value == "websocket" || value == "empty"); // Content can use forms and links, but API documents and resource loads // cross the opaque boundary. App fetches and ticketed streams retain their // own capability checks; untrusted content's CSP blocks those connections. if request.uri().path().starts_with("/api/apps/") && opaque_or_cross_site && resource_or_navigation + && !walletconnect_websocket { return ( StatusCode::FORBIDDEN, diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index ce8da8b4d..261c730b5 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -441,6 +441,99 @@ async fn walletconnect_websocket_upgrade_requires_opaque_origin_and_first_frame_ assert_eq!(f.calls.load(Ordering::SeqCst), 0); } +#[tokio::test] +async fn walletconnect_webkit_fetch_metadata_upgrades_only_the_exact_ticketed_socket() { + let f = Fixture::new().await; + for dest in ["websocket", "empty", "document", "iframe", "script"] { + for origin in ["null", "https://other.example"] { + let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) + .into_client_request() + .unwrap(); + for (name, value) in [ + ("origin", origin), + ("sec-fetch-site", "cross-site"), + ("sec-fetch-mode", "websocket"), + ("sec-fetch-dest", dest), + ] { + request.headers_mut().insert(name, value.parse().unwrap()); + } + let result = connect_async(request).await; + if origin == "null" && matches!(dest, "websocket" | "empty") { + let (mut socket, response) = result.expect("WebKit connection upgrades"); + assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS); + socket + .send(Message::Text( + json!({"token":"refused","url":RELAY}).to_string(), + )) + .await + .unwrap(); + assert!(matches!( + socket.next().await, + Some(Ok(Message::Close(_))) | None + )); + } else { + assert!( + matches!(result, Err(tokio_tungstenite::tungstenite::Error::Http(ref response)) if response.status() == StatusCode::FORBIDDEN), + "resource/origin boundary: {dest} {origin}" + ); + } + } + } + let client = reqwest::Client::new(); + for (method, path, mode, upgrade) in [ + ( + "GET", + "/api/apps/wallet-walletconnect/relay", + "navigate", + "websocket", + ), + ( + "POST", + "/api/apps/wallet-walletconnect/relay", + "websocket", + "websocket", + ), + ( + "GET", + "/api/apps/wallet-walletconnect/relay", + "websocket", + "h2c", + ), + ( + "GET", + "/api/apps/wallet-walletconnect/storage", + "websocket", + "websocket", + ), + ( + "GET", + "/api/apps/wallet-walletconnect/relay/extra", + "websocket", + "websocket", + ), + ] { + let response = client + .request( + method.parse::().unwrap(), + format!("http://{}{path}", f.addr), + ) + .header("origin", "null") + .header("sec-fetch-site", "cross-site") + .header("sec-fetch-mode", mode) + .header("sec-fetch-dest", "websocket") + .header("upgrade", upgrade) + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "{method} {path} {mode} {upgrade}" + ); + } + assert_eq!(f.calls.load(Ordering::SeqCst), 0); +} + #[tokio::test] async fn walletconnect_real_relay_requires_consent_allowlist_and_connector() { let f = Fixture::new().await; diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 0e4b1cfe8..7ba7106b2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -191,7 +191,15 @@ async fn walletconnect_gateway_process_worker() { let origin = request.headers().get("origin").and_then(|h|h.to_str().ok()); let kind = match origin { None=>"missing",Some("null")=>"opaque",Some(value) if value==expected_origin=>"same-home",_=>"other" }; let host_matches = request.headers().get("host").and_then(|h|h.to_str().ok()) == Some(expected_host.as_str()); + let fetch_metadata = json!({ + "site":request.headers().get("sec-fetch-site").and_then(|v|v.to_str().ok()), + "mode":request.headers().get("sec-fetch-mode").and_then(|v|v.to_str().ok()), + "dest":request.headers().get("sec-fetch-dest").and_then(|v|v.to_str().ok()), + }); async move { + if relay { + crate::auth::atomic_write(&refusal_path.with_file_name("relay-fetch-metadata.json"), &serde_json::to_vec(&fetch_metadata).unwrap()).unwrap(); + } let response = next.run(request).await; if relay && response.status()==StatusCode::FORBIDDEN { crate::auth::atomic_write(&refusal_path, &serde_json::to_vec(&json!({"status":403,"origin_kind":kind,"origin_headers":origin_count,"host_matches":host_matches})).unwrap()).unwrap(); From f244c52c6d788360af6de8912b8061dd33cde656 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:22:48 -0500 Subject: [PATCH 068/139] fix(walletconnect): retain sent hashes and bind connector effects to their launch --- capsules/wallet-provider/src/storage.rs | 18 ++++-- .../src/tests/approvals/transactions.rs | 18 ++++++ .../browser/walletconnect-client.mjs | 6 +- .../elastos-server/src/api/auth_gateway.rs | 9 +-- .../api/gateway_tests/wallet/connectors.rs | 18 +++++- .../api/gateway_tests/wallet/walletconnect.rs | 53 +++++++++++++++++ .../src/api/gateway_wallet_connectors.rs | 22 +++++-- .../src/api/gateway_walletconnect.rs | 58 ++++++++++++++----- scripts/lib/walletconnect-capsule-fixture.mjs | 2 +- scripts/walletconnect-capsule.test.mjs | 3 +- 10 files changed, 169 insertions(+), 38 deletions(-) diff --git a/capsules/wallet-provider/src/storage.rs b/capsules/wallet-provider/src/storage.rs index e8f4ea8f3..53844c091 100644 --- a/capsules/wallet-provider/src/storage.rs +++ b/capsules/wallet-provider/src/storage.rs @@ -230,11 +230,20 @@ pub(super) fn prune_store(mut store: WalletStore, now: u64) -> WalletStore { store } +// A phone may finish sending after expiry. Preserve this approved receipt until +// its single completion; pending requests and signature handoffs still expire. +fn awaiting_external_transaction(request: &WalletApprovalRequest) -> bool { + request.status == ApprovalStatus::Approved + && request.intent == "transaction_intent" + && request.connector_id.is_some() +} + pub(super) fn approval_authority_is_active(request: &WalletApprovalRequest, now: u64) -> bool { - if matches!( - request.status, - ApprovalStatus::Pending | ApprovalStatus::Approved - ) && request.expires_at > now + if awaiting_external_transaction(request) + || matches!( + request.status, + ApprovalStatus::Pending | ApprovalStatus::Approved + ) && request.expires_at > now { return true; } @@ -278,6 +287,7 @@ pub(super) fn expire_approval_if_elapsed(request: &mut WalletApprovalRequest, no request.status, ApprovalStatus::Pending | ApprovalStatus::Approved ) && request.expires_at <= now + && !awaiting_external_transaction(request) { request.status = ApprovalStatus::Expired; request.resolved_at = Some(now); diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 94a963b9e..2c5665b0a 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -349,6 +349,24 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { }; assert_eq!(transaction["from"], external_address); assert_eq!(transaction["chainId"], "0x14"); + let request = provider + .store + .approval_requests + .iter_mut() + .find(|r| r.request_id == request_id) + .unwrap(); + request.expires_at = now_ts() - 1; + provider.store = prune_store(std::mem::take(&mut provider.store), now_ts()); + assert_eq!( + provider + .store + .approval_requests + .iter() + .find(|r| r.request_id == request_id) + .unwrap() + .status, + ApprovalStatus::Approved + ); let transaction_hash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; let context = wallet_context(principal_id, "wallet-metamask"); let invalid_completion = wallet_request( diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs index eb665544d..77b2dd52d 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -89,8 +89,8 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp if (!Number.isSafeInteger(review.expires_at) || ttl <= 0 || review.intent === 'transaction_intent' && ttl < 300) throw new Error('Wallet request expires soon. Request a fresh review.'); const supported = ['auth_challenge','browser_personal_sign','browser_typed_data_sign','capability_grant','credential','publish_envelope','protected_content_rights_signature','transaction_intent','revocation']; if (!supported.includes(review.intent)) throw new Error('This request type is unavailable in WalletConnect. Reject it in Wallet.'); - if (review.intent === 'browser_typed_data_sign' && !provider.session?.namespaces?.eip155?.methods?.includes('eth_signTypedData_v4')) - throw new Error('Typed data signing is unavailable in this pairing. Reject this request in Wallet or use another linked account.'); + if (review.intent === 'browser_typed_data_sign') + throw new Error('Typed data signing is unavailable in this connector. Reject this request in Wallet or use another linked account.'); const {handoff,binding} = await api(`${path}/approve`,{method:'POST',body:'{}'}); if (!handoff || !binding || handoff.request_id !== action.approvalRequestId || handoff.payload_hash !== binding.payload_hash || !same(handoff.signer,signer) @@ -112,7 +112,7 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp return {status:'completed',effect:'transaction'}; } if (handoff.signature_type !== 'personal_sign' || typeof handoff.message !== 'string') throw new Error('Runtime returned an invalid signature request.'); - const method = handoff.intent === 'browser_typed_data_sign' ? 'eth_signTypedData_v4' : 'personal_sign'; + const method = 'personal_sign'; const signature = await provider.request({method,params:method === 'eth_signTypedData_v4' ? [signer,handoff.message] : [signData(handoff.message),signer]},expiry); await check(); await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,signature,signature_type:method === 'eth_signTypedData_v4' ? 'eip712' : 'personal_sign'})}); diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index c7e58c453..ac487f4bc 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -3615,12 +3615,9 @@ fn require_wallet_link_context( state: &GatewayState, headers: &HeaderMap, ) -> anyhow::Result { - let authority = super::gateway::require_runtime_wallet_authority( - &state.data_dir, - headers, - &[WALLET_WALLETCONNECT_CAPSULE_ID], - ) - .map_err(|_| anyhow::Error::new(WalletConnectorBridgeRequired))?; + let authority = + super::gateway::gateway_walletconnect::connector_launch_authority(&state.data_dir, headers) + .map_err(|_| anyhow::Error::new(WalletConnectorBridgeRequired))?; verified_wallet_link_context(state, WALLET_WALLETCONNECT_CAPSULE_ID, authority) } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 24a25e9b6..f518efc24 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1357,8 +1357,8 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding .header("x-elastos-home-token", &connector).header(CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())).unwrap()).await.unwrap(); let operations = provider.recorded_v2_operation_kinds().await; - if case == "valid" { - assert_eq!(response.status(), StatusCode::OK); + if matches!(case, "valid" | "expired") { + assert_eq!(response.status(), StatusCode::OK, "{case}"); assert!(operations.contains(&WalletOperationKind::CompleteConnectorHandoff)); let requests = provider.requests.lock().await; let forwarded = requests @@ -1396,6 +1396,18 @@ async fn test_walletconnect_capsule_config_link_and_effect_authority_matrix() { WALLET_WALLETCONNECT_CAPSULE_ID, &owner, ); + let wrong_selection = issue_home_projection_launch_token_with_context( + dir.path(), + WALLET_CAPSULE_ID, + WALLET_WALLETCONNECT_CAPSULE_ID, + &runtime_wallet_authority_for_app_token( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &token, + ) + .home_launch_context(), + ) + .unwrap(); let inbox = app_token_for_authority(dir.path(), INBOX_CAPSULE_ID, &owner); let context = runtime_wallet_authority_for_app_token(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &token) @@ -1466,7 +1478,7 @@ async fn test_walletconnect_capsule_config_link_and_effect_authority_matrix() { let mut index = 0; while index < calls.len() { let (path, body) = calls[index].clone(); - for invalid in [&owner.home_token, &inbox, &expired] { + for invalid in [&owner.home_token, &inbox, &expired, &wrong_selection] { assert_ne!( call(&app, &owner.home_token, invalid, path, body.clone()) .await diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 261c730b5..34d04d9f5 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -47,6 +47,11 @@ impl Provider for Exit { Err(ProviderError::Provider("raw fixture".into())) } async fn send_raw(&self, request: &Value) -> Result { + if request["op"] == "close_stream" { + assert_eq!(request["stream_id"], "stream:wc-fixture"); + assert!(request["principal_id"].as_str().is_some()); + return Ok(json!({"status":"ok"})); + } self.calls.fetch_add(1, Ordering::SeqCst); assert_eq!(request["target"], "tls://relay.walletconnect.org:443"); assert!(request["principal_id"].as_str().is_some()); @@ -441,6 +446,54 @@ async fn walletconnect_websocket_upgrade_requires_opaque_origin_and_first_frame_ assert_eq!(f.calls.load(Ordering::SeqCst), 0); } +#[tokio::test] +async fn walletconnect_refused_remote_exit_closes_its_reservation() { + struct RemoteExit(Arc); + #[async_trait::async_trait] + impl Provider for RemoteExit { + fn name(&self) -> &'static str { + "reserved-remote-exit" + } + fn schemes(&self) -> Vec<&'static str> { + vec!["exit"] + } + async fn handle(&self, _: ResourceRequest) -> Result { + Err(ProviderError::Provider("raw fixture".into())) + } + async fn send_raw(&self, request: &Value) -> Result { + if request["op"] == "close_stream" { + assert_eq!(request["stream_id"], "stream:remote-reservation"); + assert!(request["principal_id"].as_str().is_some()); + self.0.notify_one(); + return Ok(json!({"status":"ok"})); + } + assert_eq!(request["op"], "open_stream"); + Ok(json!({"status":"ok","data":{ + "schema":"elastos.exit.stream-session/v1", "target":request["target"], + "principal_id":request["principal_id"],"stream_id":"stream:remote-reservation", + "byte_transport":"carrier_stream" + }})) + } + } + let f = Fixture::new().await; + let closed = Arc::new(tokio::sync::Notify::new()); + let registry = f.state.provider_registry.as_ref().unwrap(); + registry.unregister_sub_provider("exit").await.unwrap(); + registry + .register_sub_provider("exit", Arc::new(RemoteExit(closed.clone()))) + .await + .unwrap(); + f.allow().await; + let mut socket = f.connect(&f.connector, RELAY).await; + assert!(matches!( + socket.next().await, + Some(Ok(Message::Close(_))) | None + )); + tokio::time::timeout(Duration::from_secs(2), closed.notified()) + .await + .expect("refused remote reservation was closed"); +} + #[tokio::test] async fn walletconnect_webkit_fetch_metadata_upgrades_only_the_exact_ticketed_socket() { let f = Fixture::new().await; diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index d5ac05b01..d78b54e60 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -255,7 +255,14 @@ pub(in crate::api::gateway) fn require_wallet_connector_launch_context( anyhow::bail!("unknown wallet connector capsule"); } ensure_wallet_connector_configured(data_dir, connector_id)?; - require_home_launch_token_context(data_dir, headers, connector_id) + if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + Ok( + gateway_walletconnect::connector_launch_authority(data_dir, headers)? + .home_launch_context(), + ) + } else { + require_home_launch_token_context(data_dir, headers, connector_id) + } } pub(in crate::api::gateway) fn require_wallet_connector_launch_authority( @@ -267,7 +274,11 @@ pub(in crate::api::gateway) fn require_wallet_connector_launch_authority( anyhow::bail!("unknown wallet connector capsule"); } ensure_wallet_connector_configured(data_dir, connector_id)?; - require_runtime_wallet_authority(data_dir, headers, &[connector_id]) + if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { + gateway_walletconnect::connector_launch_authority(data_dir, headers) + } else { + require_runtime_wallet_authority(data_dir, headers, &[connector_id]) + } } pub(in crate::api::gateway) fn require_wallet_app_launch_authority( @@ -378,9 +389,10 @@ async fn walletconnect_request_binding( request["principal_id"].as_str() == Some(authority.verified_context().principal_id()) && request["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID && request["status"] == status - && request["expires_at"] - .as_u64() - .is_some_and(|expiry| expiry > now_ts()) + && (request["expires_at"].as_u64().is_some_and(|expiry| expiry > now_ts()) + // The phone can return a sent transaction after the approval TTL. + // Approved state still binds its one completion to the same payload. + || status == "approved" && request["intent"] == "transaction_intent") && request["payload_hash"] .as_str() .is_some_and(walletconnect_hash), diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 43165e6b5..4098c264e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -396,33 +396,38 @@ async fn verify_sdk(state: &GatewayState) -> anyhow::Result<()> { Ok(()) } -fn connector_authority( - state: &GatewayState, +pub(in crate::api) fn connector_launch_authority( + data: &FsPath, headers: &HeaderMap, ) -> anyhow::Result { - let launch = require_home_launch_token_binding( - &state.data_dir, - headers, - &[WALLET_WALLETCONNECT_CAPSULE_ID], - )?; + let launch = + require_home_launch_token_binding(data, headers, &[WALLET_WALLETCONNECT_CAPSULE_ID])?; anyhow::ensure!( launch.launch_context.selected_resource == WALLET_WALLETCONNECT_CAPSULE_ID && launch.context.proof_binding_id.is_some(), "WalletConnect requires its own proof-bound capsule launch" ); + runtime_wallet_authority(&launch) +} + +fn connector_authority( + state: &GatewayState, + headers: &HeaderMap, +) -> anyhow::Result { + let authority = connector_launch_authority(&state.data_dir, headers)?; // The signed launch carries principal, live session and exact launch instance. // Retaining these headers binds relay tickets and recurring checks to that launch. if headers .get("if-match") .and_then(|v| v.to_str().ok()) .unwrap_or("\"0\"") - != storage_revision(&state.data_dir, &launch.context.principal_id)? + != storage_revision(&state.data_dir, authority.verified_context().principal_id())? { anyhow::bail!( "WalletConnect session changed. Close this window and open WalletConnect again." ); } - runtime_wallet_authority(&launch) + Ok(authority) } #[cfg(test)] pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayState) { @@ -499,11 +504,8 @@ pub(super) async fn storage( ) -> Response { let result = async { let authority = if method == axum::http::Method::DELETE { - require_runtime_wallet_authority( - &state.data_dir, - &headers, - &[WALLET_WALLETCONNECT_CAPSULE_ID], - )? + // Cleanup retries keep launch/proof checks but can use the old storage revision. + connector_launch_authority(&state.data_dir, &headers)? } else { connector_authority(&state, &headers)? }; @@ -698,6 +700,26 @@ async fn relay_connection( result } +#[cfg(unix)] +struct ExitReservation { + registry: Arc, + stream_id: String, + principal: String, +} +#[cfg(unix)] +impl Drop for ExitReservation { + fn drop(&mut self) { + let registry = self.registry.clone(); + let request = + json!({"op":"close_stream","stream_id":self.stream_id,"principal_id":self.principal}); + tokio::spawn(async move { + let _ = + tokio::time::timeout(Duration::from_secs(5), registry.send_raw("exit", &request)) + .await; + }); + } +} + #[cfg(unix)] async fn transport( state: &GatewayState, @@ -724,6 +746,14 @@ async fn transport( }))).await??; let receipt = provider_response_data(&response) .ok_or_else(|| anyhow::anyhow!("Exit admission failed"))?; + let _reservation = ExitReservation { + registry: registry.clone(), + stream_id: receipt["stream_id"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("Exit stream id is missing"))? + .to_owned(), + principal: principal.clone(), + }; anyhow::ensure!( receipt["schema"] == "elastos.exit.stream-session/v1" && receipt["target"] == target diff --git a/scripts/lib/walletconnect-capsule-fixture.mjs b/scripts/lib/walletconnect-capsule-fixture.mjs index 754417eaf..93c475e58 100644 --- a/scripts/lib/walletconnect-capsule-fixture.mjs +++ b/scripts/lib/walletconnect-capsule-fixture.mjs @@ -28,7 +28,7 @@ export async function exerciseWalletConnect(scenario='valid') { if(path==='wallet/approvals')return {approval_requests:[{request_id:'approval:fixture',status:scenario==='approved'?'approved':'pending',address, intent,chain_namespace:'eip155:20',expires_at:Math.floor(clock()/1000)+lifetime}]}; if(path.endsWith('/approve'))return {handoff:{request_id:'approval:fixture',intent, - payload_hash:payloadHash,signer:address,signature_type:'personal_sign',message:scenario==='protected-content'?'0x414243':'Runtime approval fixture', + payload_hash:payloadHash,signer:address,signature_type:scenario.startsWith('typed')?'eip712':'personal_sign',message:scenario==='protected-content'?'0x414243':'Runtime approval fixture', transaction:{from:address,to:`0x${'78'.repeat(20)}`,value:'0x1',data:'0x',gas:'0x5208',gasPrice:'0x1',nonce:'0x1',chainId:'0x14'}}, binding:{principal_id:'fixture',requested_by_actor:'documents',account_id:'fixture-account',chain_namespace:'eip155:20',payload_hash:payloadHash, expires_at:scenario==='expired'?1:Math.floor(clock()/1000)+lifetime}}; diff --git a/scripts/walletconnect-capsule.test.mjs b/scripts/walletconnect-capsule.test.mjs index d50c29af8..03642cd48 100644 --- a/scripts/walletconnect-capsule.test.mjs +++ b/scripts/walletconnect-capsule.test.mjs @@ -19,8 +19,7 @@ test('Home capsules contain no WalletConnect SDK import or signer',()=>{ for(const e of readdirSync('capsules',{withFileTypes:true}))if(e.isDirectory()&&e.name.startsWith('home'))scan(join('capsules',e.name)); }); -test('typed data uses EIP-712 and preserves the exact Runtime message',async()=>{const r=await exerciseWalletConnect('typed');assert.equal(r.error,undefined);const call=r.calls.find(c=>c.method==='eth_signTypedData_v4');assert.equal(call.params[1],'Runtime approval fixture');assert.equal(JSON.parse(completed(r)[0].input.body).signature_type,'eip712');}); -for(const scenario of ['typed-unavailable','unsupported']) test(`${scenario} remains pending instead of consuming an approval`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(typeof r.error,'string');assert.equal(r.routes.filter(c=>c.path.endsWith('/approve')).length,0);assert.equal(completed(r).length,0);}); +for(const scenario of ['typed','typed-unavailable','unsupported']) test(`${scenario} remains pending instead of consuming an approval`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(typeof r.error,'string');assert.equal(r.routes.filter(c=>c.path.endsWith('/approve')).length,0);assert.equal(completed(r).length,0);assert.equal(r.calls.filter(c=>c.method==='eth_signTypedData_v4').length,0);}); test('a reset creates a fresh SDK API while old SDK writes keep their stale revision',async()=>{ const {createWalletConnectClient}=await import('../capsules/wallet-walletconnect/browser/walletconnect-client.mjs'); let revision='"0"',loads=0,disconnects=0;const sessions=[]; From 69c41141983571e4be85c928821b0df85d1fd8b4 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:24:18 -0500 Subject: [PATCH 069/139] fix(walletconnect): retire only the last removed accounts owner pairing --- capsules/wallet-provider/src/account.rs | 15 ++++- .../wallet-provider/src/tests/accounts.rs | 44 ++++++++++++ .../api/gateway_tests/support_providers.rs | 8 ++- .../api/gateway_tests/wallet/connectors.rs | 23 +++++-- .../src/api/gateway_wallet_accounts.rs | 67 ++++++++++++++----- 5 files changed, 134 insertions(+), 23 deletions(-) diff --git a/capsules/wallet-provider/src/account.rs b/capsules/wallet-provider/src/account.rs index 9fb337d00..ed5b59631 100644 --- a/capsules/wallet-provider/src/account.rs +++ b/capsules/wallet-provider/src/account.rs @@ -467,7 +467,20 @@ impl WalletProvider { if let Err(err) = self.save() { return Response::error("storage_error", err); } - Response::ok(json!({ "account": account })) + // Runtime can retire the owner's pairing after its last connector account. + let connector_accounts_remaining = self + .store + .accounts + .iter() + .filter(|candidate| { + candidate.principal_id == account.principal_id + && candidate.connector_id == account.connector_id + && candidate.revoked_at.is_none() + }) + .count(); + Response::ok( + json!({ "account": account, "connector_accounts_remaining": connector_accounts_remaining }), + ) } pub(super) fn rename_account( diff --git a/capsules/wallet-provider/src/tests/accounts.rs b/capsules/wallet-provider/src/tests/accounts.rs index 386aa68bb..da6ca81cf 100644 --- a/capsules/wallet-provider/src/tests/accounts.rs +++ b/capsules/wallet-provider/src/tests/accounts.rs @@ -1460,3 +1460,47 @@ fn managed_recovery_set_save_failure_rolls_back_and_leaves_lifecycle_retryable() 1 ); } + +#[test] +fn walletconnect_revocation_counts_only_the_owners_remaining_connector_accounts() { + let dir = tempfile::tempdir().unwrap(); + let mut provider = init_provider(dir.path()); + for (principal, chain, connector) in [ + ("person:owner", "eip155:1", "wallet-walletconnect"), + ("person:owner", "eip155:20", "wallet-walletconnect"), + ("person:other", "eip155:1", "wallet-walletconnect"), + ("person:owner", "eip155:8453", "wallet-metamask"), + ] { + assert!(matches!( + invoke_wallet( + &mut provider, + principal, + connector, + WalletProviderOperationV2::LinkVerifiedAccount { + proof_binding_id: "proof:fixture".into(), + chain_namespace: chain.into(), + address: "0xabc".into(), + proof_type: "siwe".into(), + label: None, + } + ), + Response::Ok { .. } + )); + } + for (chain, remaining) in [("eip155:1", 1), ("eip155:20", 0)] { + match invoke_wallet( + &mut provider, + "person:owner", + "wallet", + WalletProviderOperationV2::RevokeAccount { + account_id: format!("wallet:{chain}:0xabc"), + }, + ) { + Response::Ok { data: Some(data) } => { + assert_eq!(data["account"]["principal_id"], "person:owner"); + assert_eq!(data["connector_accounts_remaining"], remaining); + } + other => panic!("expected revocation, got {other:?}"), + } + } +} diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs index 68f18c138..05de4f977 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs @@ -5737,9 +5737,15 @@ impl MockWalletProvider { })); }; account["revoked_at"] = json!(crate::auth::now_ts()); + let account = account.clone(); + let remaining = accounts.iter().filter(|candidate| { + candidate["principal_id"] == account["principal_id"] + && candidate["connector_id"] == account["connector_id"] + && candidate["revoked_at"].is_null() + }).count(); Ok(json!({ "status": "ok", - "data": { "account": account.clone() } + "data": { "account": account, "connector_accounts_remaining":remaining } })) } Some("rename_account") => { diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index f518efc24..c9de18107 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1565,7 +1565,11 @@ async fn test_walletconnect_unfinished_transaction_is_visible_without_another_ha #[tokio::test] async fn test_walletconnect_account_removal_clears_its_store_through_wallet_route() { - for connector_id in [WALLET_WALLETCONNECT_CAPSULE_ID, WALLET_METAMASK_CAPSULE_ID] { + for (connector_id, keep_another) in [ + (WALLET_WALLETCONNECT_CAPSULE_ID, false), + (WALLET_WALLETCONNECT_CAPSULE_ID, true), + (WALLET_METAMASK_CAPSULE_ID, false), + ] { let dir = tempfile::tempdir().unwrap(); let owner = passkey_authority(dir.path()); let token = app_token_for_authority(dir.path(), WALLET_CAPSULE_ID, &owner); @@ -1579,12 +1583,21 @@ async fn test_walletconnect_account_removal_clears_its_store_through_wallet_rout hex::encode(Sha256::digest(principal.as_bytes())) )); std::fs::write(&store, b"{}").unwrap(); - let provider = MockWalletProvider { - accounts: TokioMutex::new(vec![json!({ + let mut accounts = vec![json!({ + "account_id":"fixture-other","principal_id":principal,"proof_binding_id":"fixture-proof", + "chain_namespace":"eip155:20","address":format!("0x{}","12".repeat(20)),"proof_type":"siwe", + "connector_id":connector_id,"linked_at":now_ts(), + })]; + if !keep_another { + accounts.clear(); + } + accounts.push(json!({ "account_id":"fixture-account","principal_id":principal,"proof_binding_id":"fixture-proof", "chain_namespace":"eip155:1","address":format!("0x{}","12".repeat(20)),"proof_type":"siwe", "connector_id":connector_id,"linked_at":now_ts(), - })]), + })); + let provider = MockWalletProvider { + accounts: TokioMutex::new(accounts), ..Default::default() }; let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); @@ -1610,7 +1623,7 @@ async fn test_walletconnect_account_removal_clears_its_store_through_wallet_rout assert_eq!(response.status(), StatusCode::OK); assert_eq!( store.exists(), - connector_id != WALLET_WALLETCONNECT_CAPSULE_ID + connector_id != WALLET_WALLETCONNECT_CAPSULE_ID || keep_another ); } } diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs index c098a8ea3..cd33662bf 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs @@ -15,6 +15,23 @@ pub(in crate::api::gateway) async fn system_wallet_accounts_summary( wallet_accounts_summary_from_response(response) } +fn cleanup_removed_walletconnect_account( + data_dir: &FsPath, + data: &serde_json::Value, +) -> anyhow::Result<()> { + let account = &data["account"]; + if account["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID + && !account["revoked_at"].is_null() + && data["connector_accounts_remaining"] == 0 + { + let owner = account["principal_id"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("Removed account owner is missing"))?; + gateway_walletconnect::clear_principal_storage(data_dir, owner)?; + } + Ok(()) +} + pub(in crate::api::gateway) async fn runtime_wallet_data( state: &GatewayState, authority: &RuntimeWalletAuthority, @@ -30,14 +47,7 @@ pub(in crate::api::gateway) async fn runtime_wallet_data( .result { elastos_wallet_contract::WalletResultV2::Ok { data } => { - if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID - && !data["account"]["revoked_at"].is_null() - && gateway_walletconnect::clear_principal_storage( - &state.data_dir, - authority.verified_context().principal_id(), - ) - .is_err() - { + if cleanup_removed_walletconnect_account(&state.data_dir, &data).is_err() { tracing::warn!( "WalletConnect session cleanup requires operator retry after account removal" ); @@ -64,14 +74,7 @@ pub(in crate::api::gateway) async fn runtime_wallet_data_with_request_id( .result { elastos_wallet_contract::WalletResultV2::Ok { data } => { - if data["account"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID - && !data["account"]["revoked_at"].is_null() - && gateway_walletconnect::clear_principal_storage( - &state.data_dir, - authority.verified_context().principal_id(), - ) - .is_err() - { + if cleanup_removed_walletconnect_account(&state.data_dir, &data).is_err() { tracing::warn!( "WalletConnect session cleanup requires operator retry after account removal" ); @@ -343,3 +346,35 @@ fn wallet_approval_methods_summary(data_dir: &FsPath) -> serde_json::Value { }, }) } + +#[cfg(test)] +mod walletconnect_cleanup_tests { + use super::*; + #[test] + fn walletconnect_account_cleanup_uses_owner_and_keeps_other_accounts_pairing() { + let data = tempfile::tempdir().unwrap(); + for principal in ["owner", "caller"] { + assert_eq!( + gateway_walletconnect::storage_revision(data.path(), principal).unwrap(), + "\"0\"" + ); + } + let mut response = serde_json::json!({"account":{"connector_id":WALLET_WALLETCONNECT_CAPSULE_ID, + "principal_id":"owner","revoked_at":1},"connector_accounts_remaining":1}); + cleanup_removed_walletconnect_account(data.path(), &response).unwrap(); + assert_eq!( + gateway_walletconnect::storage_revision(data.path(), "owner").unwrap(), + "\"0\"" + ); + response["connector_accounts_remaining"] = serde_json::json!(0); + cleanup_removed_walletconnect_account(data.path(), &response).unwrap(); + assert_eq!( + gateway_walletconnect::storage_revision(data.path(), "owner").unwrap(), + "\"1\"" + ); + assert_eq!( + gateway_walletconnect::storage_revision(data.path(), "caller").unwrap(), + "\"0\"" + ); + } +} From 6e98ed0cdaee7ae255a9bc0802b6021ba8eeb266 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:24:55 -0500 Subject: [PATCH 070/139] fix(walletconnect): scope release project input to a private file --- .github/workflows/release-package.yml | 20 ++++++++++++++++++-- docs/WALLET_PROVIDER.md | 22 +++++++++++++++++----- scripts/stage-walletconnect-release.mjs | 12 ++++++++---- scripts/walletconnect-runtime.test.mjs | 21 ++++++++++++++++++++- 4 files changed, 63 insertions(+), 12 deletions(-) diff --git a/.github/workflows/release-package.yml b/.github/workflows/release-package.yml index 84f59fbc5..72efa3e06 100644 --- a/.github/workflows/release-package.yml +++ b/.github/workflows/release-package.yml @@ -111,7 +111,6 @@ jobs: working-directory: source env: SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} - ELASTOS_WALLETCONNECT_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} RELEASE_PLATFORM: aarch64-darwin # Cargo and its C dependencies target macOS 11.0, not the runner SDK. MACOSX_DEPLOYMENT_TARGET: "11.0" @@ -156,9 +155,18 @@ jobs: retention-days: 7 - name: build N, then N+1 with N's support, each in fresh Cargo directories timeout-minutes: 240 + env: + REOWN_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} run: | set -euo pipefail umask 077 + if [[ -n "${REOWN_PROJECT_ID:-}" ]]; then + export ELASTOS_WALLETCONNECT_PROJECT_FILE + ELASTOS_WALLETCONNECT_PROJECT_FILE=$(mktemp "$RUNNER_TEMP/wc-project.XXXXXX") + trap 'rm -f -- "$ELASTOS_WALLETCONNECT_PROJECT_FILE"' EXIT + python3 -I -S -c 'import os; p=os.environ["ELASTOS_WALLETCONNECT_PROJECT_FILE"]; f=open(p,"w"); os.fchmod(f.fileno(),0o600); f.write(os.environ["REOWN_PROJECT_ID"]); f.close()' + fi + unset REOWN_PROJECT_ID export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" inputs="$RELEASE_ROOT/inputs" # Fresh Cargo directories for each version; removed after each build. @@ -389,7 +397,6 @@ jobs: working-directory: source env: SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} - ELASTOS_WALLETCONNECT_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} RELEASE_PLATFORM: ${{ matrix.platform }} RELEASE_ARCH: ${{ matrix.arch }} CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER: musl-gcc @@ -430,9 +437,18 @@ jobs: path: ${{ runner.temp }}/llama-arm64-bundle - name: build N, then N+1 with N's support, each in fresh Cargo directories timeout-minutes: 240 + env: + REOWN_PROJECT_ID: ${{ secrets.REOWN_PROJECT_ID }} run: | set -euo pipefail umask 077 + if [[ -n "${REOWN_PROJECT_ID:-}" ]]; then + export ELASTOS_WALLETCONNECT_PROJECT_FILE + ELASTOS_WALLETCONNECT_PROJECT_FILE=$(mktemp "$RUNNER_TEMP/wc-project.XXXXXX") + trap 'rm -f -- "$ELASTOS_WALLETCONNECT_PROJECT_FILE"' EXIT + python3 -I -S -c 'import os; p=os.environ["ELASTOS_WALLETCONNECT_PROJECT_FILE"]; f=open(p,"w"); os.fchmod(f.fileno(),0o600); f.write(os.environ["REOWN_PROJECT_ID"]); f.close()' + fi + unset REOWN_PROJECT_ID export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" export ELASTOS_LLAMA_AMD64_BUNDLE="$RUNNER_TEMP/llama-amd64-bundle/llama-b10516-bin-ubuntu22.04-amd64-cpu.tar.gz" export ELASTOS_LLAMA_ARM64_BUNDLE="$RUNNER_TEMP/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz" diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 98969a4bb..1d49b3880 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -249,7 +249,11 @@ reviewed Reown SDK and its bundled QR renderer run only in that capsule's opaque sandboxed frame. `wallet-provider` owns proof verification, linked accounts, approval state and receipts. Runtime accepts the connector's own live launch capability, bound to its principal, session and launch instance, for storage, -relay admission, linking and signing handoffs. Home owns window orchestration. +relay admission, linking and signing handoffs. Each route checks the selected +connector resource and proof binding. Config reads and storage deletion retain +these launch checks while accepting an older storage revision, so a connector can +load the current revision or retry cleanup. Relay use and storage writes require +the current revision. Home owns window orchestration. Mode A connects a phone wallet to sign Runtime challenges and approved requests. Mode B, where external dApps use ElastOS as a WalletConnect wallet, requires its @@ -265,9 +269,12 @@ approved request and hash before completion. A closed connector window leaves an approved, unfinished transaction visible with "Check your phone wallet". Opening it again supplies recovery instructions and keeps the send control disabled. A returned transaction hash is passed to Runtime once even if the account, -network or expiry changed during the phone prompt. A completion error keeps the +network or expiry changed during the phone prompt. Runtime checks the returned +transaction hash's format only. The phone wallet confirms the transaction; +the hash alone does not prove that it matches the approved payload. A completion error keeps the hash visible for checking before another send. Unused signatures and ownership -proofs stop when their account, network or expiry changes. +proofs stop when their account, network or expiry changes. Typed-data requests +stay pending because this connector's reviewed bundle does not support that method. The capsule installs `walletconnect-storage.mjs` before importing the pinned SDK. Browser Storage holds UI preferences in memory and resets on reload. Protocol @@ -277,7 +284,9 @@ principal. The SDK uses the constant context `wallet-walletconnect`; Runtime's principal boundary separates each person's files. The connector supplies no session migration. Disconnect clears session storage and the memory shim while linked accounts stay in Wallet. Revocation clears session files; linked -account removal and principal removal also clear the affected principal's file. +account removal clears the account owner's file after the last active WalletConnect +account is removed. Other linked accounts keep their pairing. Principal removal +clears that principal's file. A cleanup failure after account or principal removal leaves that change saved and records an operator-retry warning. Successful cleanup advances a Runtime storage revision that fences late writes and relay use from an old SDK @@ -289,7 +298,10 @@ admits only the opaque connector's single-use relay ticket, caps waiting sockets rechecks the launch and owner on each heartbeat and outbound frame, authenticates relay TLS, and limits frames and sockets. It reaches only `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through -the local Exit. Turn Off cancels handshakes and open sockets. Hosted Carrier Exit +a local Exit backend and its separate adapter and relay sockets. Existing Browser +backends keep first match. Runtime validates the merged configuration with +exit-provider's parser and keeps the existing Exit configuration if the addition +is refused. Turn Off cancels handshakes and open sockets. Hosted Carrier Exit selection remains a separate integration. The native-Storage comparison and deterministic sandbox test cover Chromium and diff --git a/scripts/stage-walletconnect-release.mjs b/scripts/stage-walletconnect-release.mjs index fd3687d94..771006e59 100644 --- a/scripts/stage-walletconnect-release.mjs +++ b/scripts/stage-walletconnect-release.mjs @@ -1,13 +1,13 @@ // Run against the private release stage or source-home install, before hashing // its capsule. An operator supplies the project ID through a provisioned file. -import { readFile, writeFile } from "node:fs/promises"; +import { readFile, writeFile, chmod } from "node:fs/promises"; import { createHash } from "node:crypto"; import { resolve } from "node:path"; const capsule = resolve(process.argv[2]); const operator = process.env.ELASTOS_WALLETCONNECT_PROJECT_FILE; -if (operator || process.env.ELASTOS_WALLETCONNECT_PROJECT_ID) { - const projectId = (operator ? await readFile(operator, "utf8") : process.env.ELASTOS_WALLETCONNECT_PROJECT_ID).trim(); +if (operator) { + const projectId = (await readFile(operator, "utf8")).trim(); if (!/^[A-Za-z0-9_-]{8,128}$/.test(projectId)) throw new Error("Invalid WalletConnect operator project file"); const manifest = JSON.parse(await readFile(resolve(capsule, "vendor/adapter.json"), "utf8")); const sdk = await readFile(resolve(capsule, "vendor/reown-appkit.js")); @@ -16,8 +16,12 @@ if (operator || process.env.ELASTOS_WALLETCONNECT_PROJECT_ID) { || manifest.sdk_sha256 !== createHash("sha256").update(sdk).digest("hex")) { throw new Error("WalletConnect reviewed adapter hash mismatch"); } - await writeFile(resolve(capsule, "vendor/connector.json"), JSON.stringify({ + const configPath = resolve(capsule, "vendor/connector.json"); + // Reused staging trees can contain a config with older permissions. + await chmod(configPath, 0o600).catch(error => { if (error.code !== "ENOENT") throw error; }); + await writeFile(configPath, JSON.stringify({ schema: "elastos.walletconnect.connector/v1", project_id: projectId, sdk_package: manifest.sdk_package, sdk_version: manifest.sdk_version, sdk_sha256: manifest.sdk_sha256, }, null, 2) + "\n", { mode: 0o600 }); + await chmod(configPath, 0o600); } diff --git a/scripts/walletconnect-runtime.test.mjs b/scripts/walletconnect-runtime.test.mjs index 82ed1ac3d..bede02d45 100644 --- a/scripts/walletconnect-runtime.test.mjs +++ b/scripts/walletconnect-runtime.test.mjs @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { readFile, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { readFile, mkdtemp, mkdir, writeFile, rm, chmod, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { execFileSync } from "node:child_process"; @@ -119,6 +119,7 @@ test("release stage installs config automatically only from the operator file an })); const script = resolve("scripts/stage-walletconnect-release.mjs"); const env = { ...process.env }; delete env.ELASTOS_WALLETCONNECT_PROJECT_FILE; delete env.ELASTOS_WALLETCONNECT_PROJECT_ID; + env.ELASTOS_WALLETCONNECT_PROJECT_ID = "refused-env-only-project"; execFileSync(process.execPath, [script, dir], { env }); await assert.rejects(readFile(join(vendor, "connector.json")), /ENOENT/); const project = join(dir, "operator-project"); await writeFile(project, "fixture-project-id"); @@ -127,7 +128,25 @@ test("release stage installs config automatically only from the operator file an const config = JSON.parse(await readFile(join(vendor, "connector.json"))); assert.equal(config.schema, "elastos.walletconnect.connector/v1"); assert.equal(config.project_id, "fixture-project-id"); + await chmod(join(vendor, "connector.json"), 0o644); + execFileSync(process.execPath, [script, dir], { env }); + assert.equal((await stat(join(vendor, "connector.json"))).mode & 0o777, 0o600); await writeFile(join(vendor, "reown-appkit.js"), "tampered"); assert.throws(() => execFileSync(process.execPath, [script, dir], { env, stdio: "pipe" }), /failed/); } finally { await rm(dir, { recursive: true, force: true }); } }); + +test("release project secret is scoped to the build step and passed only by file", async () => { + const workflow = await readFile(resolve(".github/workflows/release-package.yml"), "utf8"); + assert.doesNotMatch(workflow, /ELASTOS_WALLETCONNECT_PROJECT_ID/); + const steps = workflow.split(" - name:"); + const secretSteps = steps.filter(step => step.includes("secrets.REOWN_PROJECT_ID")); + assert.equal(secretSteps.length, 2); + for (const step of secretSteps) { + assert.match(step, /^ build N, then N\+1/); + assert.match(step, /os.fchmod\(f.fileno\(\),0o600\)/); + assert.match(step, /ELASTOS_WALLETCONNECT_PROJECT_FILE/); + assert.match(step, /unset REOWN_PROJECT_ID/); + assert.match(step, /trap .*EXIT/); + } +}); From ff35e835f6e2bddb007f2b8da2352464ad00ab2a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:28:31 -0500 Subject: [PATCH 071/139] test(walletconnect): exercise native Exit and the real Inbox return handler --- capsules/home/browser/home-shell-host.js | 10 +- .../api/gateway_tests/wallet/walletconnect.rs | 32 ++-- .../wallet/walletconnect_real_relay.rs | 138 ++++++++++++------ scripts/home-shell-bridge-smoke.mjs | 19 ++- 4 files changed, 140 insertions(+), 59 deletions(-) diff --git a/capsules/home/browser/home-shell-host.js b/capsules/home/browser/home-shell-host.js index 37b808225..d3bda812d 100644 --- a/capsules/home/browser/home-shell-host.js +++ b/capsules/home/browser/home-shell-host.js @@ -208,7 +208,7 @@ async function switchToHomeGuiAndOpenTarget(context, target, options = {}) { async function launchWalletConnectorFromTrustedSource(context, target) { if ( context.kind !== "app-frame" || - context.targetId !== "wallet" || + !(context.targetId === "wallet" || context.targetId === "inbox" && target === "wallet-walletconnect") || !WALLET_CONNECTOR_TARGETS.has(target) ) { throw new Error("Home denied the Wallet connector launch"); @@ -2204,10 +2204,12 @@ window.addEventListener("message", (event) => { !marketplaceAssistantHandoffQuery(data.query))) return; if ( context.kind === "app-frame" && - context.targetId === "wallet" && + (context.targetId === "wallet" || context.targetId === "inbox" && target === "wallet-walletconnect") && WALLET_CONNECTOR_TARGETS.has(target) ) { - if (!hasExactMessageKeys(data, ["type", "target", "homeToken"])) { + const inboxReturn = context.targetId === "inbox"; + if (!hasExactMessageKeys(data, inboxReturn ? ["type", "target", "homeToken", "query"] : ["type", "target", "homeToken"]) + || inboxReturn && (!data.query || typeof data.query !== "object" || Array.isArray(data.query) || Object.keys(data.query).length !== 0)) { console.warn("home ignored malformed Wallet connector launch", target); return; } @@ -2454,6 +2456,8 @@ function canOpenTargetFromHomeMessage(context, target) { if (context.kind === "home") { return true; } + // Inbox returns the user to the connector after its internet consent step. + if (context.kind === "app-frame" && context.targetId === "inbox" && target === "wallet-walletconnect") return true; const policy = SHELL_MESSAGE_OPEN_TARGET_SOURCES[context.targetId]; if (!policy) { return false; diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 34d04d9f5..36f23934c 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -839,16 +839,30 @@ async fn walletconnect_refuses_malformed_writes_and_home_authority() { } let (_, stored) = f.route(&f.connector, STORAGE, None).await; assert_eq!(stored, json!({})); - for path in [ - STORAGE, - "/api/apps/wallet-walletconnect/relay-admission", - "/api/apps/wallet-walletconnect/host-config", + for (method, path) in [ + (reqwest::Method::GET, STORAGE), + ( + reqwest::Method::POST, + "/api/apps/wallet-walletconnect/relay-admission", + ), + ( + reqwest::Method::GET, + "/api/apps/wallet-walletconnect/wallet/config", + ), ] { - let (status, _) = f.route(&f.home, path, None).await; - assert_ne!( - status, - StatusCode::OK, - "Home owns no WalletConnect authority" + let response = reqwest::Client::new() + .request(method, format!("http://{}{path}", f.addr)) + .header("origin", format!("http://{}", f.addr)) + .header("x-elastos-home-token", &f.home) + .header("content-type", "application/json") + .body("{}") + .send() + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::FORBIDDEN, + "Home's valid origin reaches the connector authority guard: {path}" ); } assert_eq!( diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index 7ba7106b2..bbbe9a336 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -2,8 +2,8 @@ use super::*; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use ed25519_dalek::{Signer, SigningKey}; +use elastos_runtime::provider::{BridgeProviderConfig, CapsuleProvider, ProviderBridge}; use std::io::Read; -use tokio::net::TcpStream; fn operator_project() -> String { let file = std::env::var_os("ELASTOS_WALLETCONNECT_PROJECT_FILE") @@ -31,59 +31,102 @@ fn operator_project() -> String { project.to_owned() } -async fn real_fixture(project: &str) -> Fixture { +struct RealFixture { + fixture: Fixture, + helper: std::process::Child, +} +impl std::ops::Deref for RealFixture { + type Target = Fixture; + fn deref(&self) -> &Fixture { + &self.fixture + } +} +impl std::ops::DerefMut for RealFixture { + fn deref_mut(&mut self) -> &mut Fixture { + &mut self.fixture + } +} +impl Drop for RealFixture { + fn drop(&mut self) { + // Parent EOF lets the helper release its exact socket and owned children. + drop(self.helper.stdin.take()); + let deadline = std::time::Instant::now() + Duration::from_secs(3); + while self.helper.try_wait().ok().flatten().is_none() { + if std::time::Instant::now() >= deadline { + let _ = self.helper.kill(); + let _ = self.helper.wait(); + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + } +} + +async fn production_exit(data: &std::path::Path) -> Arc { + let binary = std::env::var_os("ELASTOS_WALLETCONNECT_TEST_EXIT_PROVIDER") + .expect("set the real exit-provider binary path"); + let platform = crate::setup::detect_platform(); + let (_, config) = crate::setup::walletconnect::local_exit(data, &platform).unwrap(); + let bridge = ProviderBridge::spawn( + std::path::Path::new(&binary), + BridgeProviderConfig { + extra: crate::setup::walletconnect::exit_config(Value::Null, Some(&config)), + ..Default::default() + }, + ) + .await + .expect("real exit-provider accepts the generated config"); + Arc::new(CapsuleProvider::with_scheme(Arc::new(bridge), "exit")) +} + +async fn real_fixture(project: &str) -> RealFixture { let mut f = Fixture::new().await; assert!(!f.addr.ends_with(":8090")); let config_path = f.data.path().join(WALLETCONNECT_CONFIG_PATH); let mut config: Value = serde_json::from_slice(&std::fs::read(&config_path).unwrap()).unwrap(); config["project_id"] = json!(project); crate::auth::atomic_write(&config_path, &serde_json::to_vec(&config).unwrap()).unwrap(); - // Use the production root store. This Exit harness forwards raw TLS bytes; - // Runtime retains relay authentication and the HTTP/WebSocket handshake. *f.state.walletconnect.tls.lock().unwrap() = None; - let path = f.data.path().join("real-relay.sock"); - let listener = UnixListener::bind(&path).unwrap(); f.relay.abort(); - f.relay = tokio::spawn(async move { - let mut connections = tokio::task::JoinSet::new(); + let _ = (&mut f.relay).await; + let (helper_config, _) = + crate::setup::walletconnect::local_exit(f.data.path(), &crate::setup::detect_platform()) + .unwrap(); + let helper_binary = std::env::var_os("ELASTOS_WALLETCONNECT_TEST_LOCAL_EXIT") + .expect("set the real browser-local-exit binary path"); + let mut helper = std::process::Command::new(helper_binary) + .env( + "ELASTOS_BROWSER_LOCAL_EXIT_CONFIG", + helper_config.to_string(), + ) + .env("ELASTOS_BROWSER_LOCAL_EXIT_PARENT_EOF", "1") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + let ready = tokio::time::timeout(Duration::from_secs(5), async { loop { - tokio::select! { - accepted = listener.accept() => { - let (mut stream, _) = accepted.unwrap(); - connections.spawn(async move { - let mut line = Vec::new(); - loop { - let Ok(byte) = stream.read_u8().await else { return; }; - if byte == b'\n' { break; } - line.push(byte); - assert!(line.len() < 16384); - } - let open: Value = serde_json::from_slice(&line).unwrap(); - assert_eq!(open["schema"], "elastos.exit.relay-open/v1"); - assert_eq!(open["target"], "tls://relay.walletconnect.org:443"); - let Ok(Ok(mut remote)) = tokio::time::timeout( - Duration::from_secs(10), TcpStream::connect(("relay.walletconnect.org", 443)) - ).await else { return; }; - let _ = tokio::io::copy_bidirectional(&mut stream, &mut remote).await; - }); - } - result = connections.join_next(), if !connections.is_empty() => { result.unwrap().unwrap(); } + assert!( + helper.try_wait().unwrap().is_none(), + "local Exit exited before readiness" + ); + if std::fs::symlink_metadata(helper_config["relay_ipc_path"].as_str().unwrap()).is_ok() + { + break; } + tokio::time::sleep(Duration::from_millis(20)).await; } - }); + }) + .await; + ready.expect("real local Exit socket readiness"); let registry = f.state.provider_registry.as_ref().unwrap(); registry.unregister_sub_provider("exit").await.unwrap(); registry - .register_sub_provider( - "exit", - Arc::new(Exit { - path, - calls: f.calls.clone(), - }), - ) + .register_sub_provider("exit", production_exit(f.data.path()).await) .await .unwrap(); - f + RealFixture { fixture: f, helper } } // Matches @walletconnect/relay-auth's locked signJWT/encodeIss implementation. @@ -140,7 +183,7 @@ async fn walletconnect_real_project_opens_through_runtime_and_exit() { "real relay subscription failed" ); socket.close(None).await.unwrap(); - println!("PASS: Runtime -> Exit harness -> authenticated Reown WSS upgrade and subscription; project file set; ephemeral localhost port; no 401/403"); + println!("PASS: Runtime -> real exit-provider -> real browser-local-exit -> authenticated Reown WSS upgrade and subscription; project file set; ephemeral localhost port; no 401/403"); } // A separate process makes restart discard every gateway socket and global. @@ -170,13 +213,7 @@ async fn walletconnect_gateway_process_worker() { }; let registry = Arc::new(ProviderRegistry::new()); registry - .register_sub_provider( - "exit", - Arc::new(Exit { - path: data.join("real-relay.sock"), - calls: Arc::new(AtomicUsize::new(0)), - }), - ) + .register_sub_provider("exit", production_exit(data).await) .await .unwrap(); state.provider_registry = Some(registry); @@ -346,6 +383,15 @@ async fn walletconnect_real_project_opaque_preflight() { let record: Value = serde_json::from_slice(&bytes).unwrap(); println!("{}", json!({"relay_handshake_refusal":record})); } + if let Some(bytes) = + gateway_walletconnect::read_bytes(&f.data.path().join("relay-fetch-metadata.json"), 1024) + .unwrap() + { + println!( + "{}", + json!({"relay_fetch_metadata":serde_json::from_slice::(&bytes).unwrap()}) + ); + } // The Node driver emits only bounded, value-free evidence. SDK diagnostics // can contain relay credentials, so stderr remains private to this process. assert!( diff --git a/scripts/home-shell-bridge-smoke.mjs b/scripts/home-shell-bridge-smoke.mjs index 2de31ebc0..359eb1fea 100644 --- a/scripts/home-shell-bridge-smoke.mjs +++ b/scripts/home-shell-bridge-smoke.mjs @@ -562,7 +562,7 @@ globalThis.fetch = async (url, init = {}) => { title: "System", }); } - if (["assistant", "home-agent", "marketplace", "inbox"].includes(body?.target)) { + if (["assistant", "home-agent", "marketplace", "inbox", "wallet-walletconnect"].includes(body?.target)) { return jsonResponse({ attach_kind: "iframe", target: body.target, route: `/apps/${body.target}/?home_origin=http%3A%2F%2Flocalhost%3A61180#home_token=${body.target}-token` }); } @@ -2453,6 +2453,23 @@ sendChildMessage("null", browserFrameWindow, { assert(focus().length===before,"Only exact trusted Inbox focus is accepted"); sendChildMessage("null",source,intent); assert(focus().length===before+1,"Inbox focus reaches GUI without opening a new window"); + const attachments=()=>shellMessages.filter(m=>m.payload?.command==="attach-authorized-target" && m.payload?.descriptor?.target==="wallet-walletconnect"); + const countBefore=attachments().length; + const reopen={type:"home:open-target",homeToken:"inbox-token",target:"wallet-walletconnect",query:{}}; + for (const [origin,sender,message] of [ + ["null",source,{...reopen,query:{injected:true}}], + ["null",source,{...reopen,target:"wallet-metamask"}], + ["null",source,{...reopen,extra:true}], + ["https://evil.invalid",source,reopen], + ["null",{},reopen], + ]) sendChildMessage(origin,sender,message); + await new Promise(r=>setTimeout(r,0)); + assert(attachments().length===countBefore,"Inbox connector return rejects unrelated effects"); + sendChildMessage("null",source,reopen); + for(let i=0;i<50 && attachments().length===countBefore;i++) await new Promise(r=>setTimeout(r,0)); + assert(attachments().length===countBefore+1,"Inbox Allow returns through real Home to the WalletConnect window"); + assert(attachments().at(-1).payload.descriptor.route.includes("/apps/wallet-walletconnect/"),"Home supplies the connector attachment"); + } const connectorLaunchesBeforeBrowserRequest = requests.filter( (request) => From fa9644a8ed08ccb796f90b9684f88fc895b9f64e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:29:28 -0500 Subject: [PATCH 072/139] fix(walletconnect): expose launch checks through the gateway boundary --- capsules/exit-provider/src/lib.rs | 6 +++--- elastos/crates/elastos-server/src/api/auth_gateway.rs | 2 +- elastos/crates/elastos-server/src/api/gateway.rs | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/capsules/exit-provider/src/lib.rs b/capsules/exit-provider/src/lib.rs index b72a16c52..c5ed35df8 100644 --- a/capsules/exit-provider/src/lib.rs +++ b/capsules/exit-provider/src/lib.rs @@ -572,7 +572,7 @@ pub fn validate_host_shape(host: &str) -> Result<(), String> { Ok(()) } -pub fn validate_public_ip(ip: IpAddr) -> Result<(), ()> { +pub fn validate_public_ip(ip: IpAddr) -> Result<(), &'static str> { match ip { IpAddr::V4(ip) => { if ip.is_private() @@ -581,7 +581,7 @@ pub fn validate_public_ip(ip: IpAddr) -> Result<(), ()> { || ip.is_unspecified() || ip.is_broadcast() { - Err(()) + Err("private IP blocked") } else { Ok(()) } @@ -592,7 +592,7 @@ pub fn validate_public_ip(ip: IpAddr) -> Result<(), ()> { || ip.is_unique_local() || ip.is_unicast_link_local() { - Err(()) + Err("private IP blocked") } else { Ok(()) } diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index ac487f4bc..7cd4e9589 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -3616,7 +3616,7 @@ fn require_wallet_link_context( headers: &HeaderMap, ) -> anyhow::Result { let authority = - super::gateway::gateway_walletconnect::connector_launch_authority(&state.data_dir, headers) + super::gateway::walletconnect_connector_launch_authority(&state.data_dir, headers) .map_err(|_| anyhow::Error::new(WalletConnectorBridgeRequired))?; verified_wallet_link_context(state, WALLET_WALLETCONNECT_CAPSULE_ID, authority) } diff --git a/elastos/crates/elastos-server/src/api/gateway.rs b/elastos/crates/elastos-server/src/api/gateway.rs index d93e519c4..89e8ff35d 100644 --- a/elastos/crates/elastos-server/src/api/gateway.rs +++ b/elastos/crates/elastos-server/src/api/gateway.rs @@ -129,6 +129,7 @@ pub(crate) use gateway_home_runtime::is_wallet_connector_capsule_id; use gateway_home_runtime::*; use gateway_home_shared_content::*; pub(crate) use gateway_walletconnect::clear_principal_storage as clear_walletconnect_principal_storage; +pub(super) use gateway_walletconnect::connector_launch_authority as walletconnect_connector_launch_authority; pub(crate) fn principal_root_protected_object_inventory( localhost_root: &str, From 4ee7401b8a38b70d9935f4f6a2887c669542cd8e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:34:44 -0500 Subject: [PATCH 073/139] fix(walletconnect): share native Browser socket naming without a Node startup dependency --- .../src/setup/browser_config.rs | 95 +++++++++++-------- .../elastos-server/src/setup/walletconnect.rs | 5 +- scripts/browser-source-home-config.mjs | 12 ++- 3 files changed, 70 insertions(+), 42 deletions(-) diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index d3f81d2d9..9b62d42cd 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -5,45 +5,25 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; const GENERATOR: &str = include_str!("../../../../../scripts/browser-source-home-config.mjs"); -/// WalletConnect uses Browser's stable, short IPC names without selecting an Engine. -pub(super) fn walletconnect_socket_paths( - data: &Path, - platform: &str, -) -> anyhow::Result { - let mut child = Command::new("node") - .env_clear() - .args([ - "--input-type=module", - "-", - "--walletconnect-socket-paths", - "--data-dir", - ]) - .arg(data) - .args(["--platform", platform]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn()?; - child - .stdin - .take() - .unwrap() - .write_all(GENERATOR.as_bytes())?; - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while child.try_wait()?.is_none() { - if std::time::Instant::now() >= deadline { - let _ = child.kill(); - let _ = child.wait(); - anyhow::bail!("WalletConnect IPC configuration timed out"); +/// Browser and WalletConnect share the short IPC names used by the source-home generator. +pub(super) fn runtime_socket_path(data: &Path, platform: &str, role: &str) -> PathBuf { + use sha2::{Digest, Sha256}; + // Match path.resolve in the generator: normalize lexical components, preserving symlinks. + let mut absolute = PathBuf::new(); + for component in data.components() { + match component { + std::path::Component::ParentDir => { + absolute.pop(); + } + std::path::Component::CurDir => {} + component => absolute.push(component.as_os_str()), } - std::thread::sleep(std::time::Duration::from_millis(10)); } - let output = child.wait_with_output()?; - anyhow::ensure!( - output.status.success(), - "WalletConnect IPC configuration failed" - ); - Ok(serde_json::from_slice(&output.stdout)?) + let scope = hex::encode(Sha256::digest(absolute.to_string_lossy().as_bytes())); + PathBuf::from(format!( + "/tmp/elastos-browser-{platform}-{}-{role}.sock", + &scope[..16] + )) } const CONFIG_FILES: [&str; 4] = [ @@ -717,6 +697,12 @@ fn generate_with_migration( .arg(data) .args(["--platform", platform, "--out-dir"]) .arg(staged.path()) + .arg("--vm-control-socket") + .arg(runtime_socket_path(data, platform, "vm-control")) + .arg("--exit-adapter-socket") + .arg(runtime_socket_path(data, platform, "exit-adapter")) + .arg("--exit-relay-socket") + .arg(runtime_socket_path(data, platform, "exit-relay")) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::piped()); @@ -756,6 +742,41 @@ mod tests { use serde_json::Value; use sha2::Digest; + #[test] + fn walletconnect_and_browser_native_socket_names_match_the_existing_generator() { + for platform in ["darwin-arm64", "linux-amd64", "linux-arm64"] { + let data = Path::new("/tmp/Application Support/long folder/../elastos"); + let mut child = Command::new("node") + .args([ + "--input-type=module", + "-", + "--walletconnect-socket-paths", + "--data-dir", + ]) + .arg(data) + .args(["--platform", platform]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(GENERATOR.as_bytes()) + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + let names: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + for (field, role) in [("adapter", "wc-adapter"), ("relay", "wc-relay")] { + assert_eq!( + names[field].as_str().unwrap(), + runtime_socket_path(data, platform, role).to_str().unwrap() + ); + } + } + } + #[test] fn native_host_probe_requires_its_contract_and_has_a_deadline() { use std::os::unix::fs::PermissionsExt; diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs index 827c80f62..1fbf9e3cf 100644 --- a/elastos/crates/elastos-server/src/setup/walletconnect.rs +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -6,9 +6,8 @@ pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, ser if !matches!(platform, "darwin-arm64" | "linux-amd64" | "linux-arm64") { return None; } - let sockets = super::browser_config::walletconnect_socket_paths(data, platform).ok()?; - let adapter = sockets["adapter"].as_str()?; - let socket = sockets["relay"].as_str()?; + let adapter = super::browser_config::runtime_socket_path(data, platform, "wc-adapter"); + let socket = super::browser_config::runtime_socket_path(data, platform, "wc-relay"); let hosts = ["relay.walletconnect.org", "relay.walletconnect.com"]; let helper = serde_json::json!({ "schema":"elastos.browser.local-exit.config/v1", "relay_ipc_path":socket, diff --git a/scripts/browser-source-home-config.mjs b/scripts/browser-source-home-config.mjs index b3976c005..9a5c034c0 100755 --- a/scripts/browser-source-home-config.mjs +++ b/scripts/browser-source-home-config.mjs @@ -98,6 +98,14 @@ function parseArgs(argv) { case "--vm-supervisor": args.vmSupervisor = next(); break; + case "--exit-adapter-socket": + args.exitAdapterSocket = next(); + validateAbsolute(arg, args.exitAdapterSocket); + break; + case "--exit-relay-socket": + args.exitRelaySocket = next(); + validateAbsolute(arg, args.exitRelaySocket); + break; case "--vm-control-socket": args.vmControlSocket = next(); break; @@ -734,8 +742,8 @@ function main() { files: ["browser-engine-adapter.json", "browser-viewer-ingress.json"] })); return; } - const adapterSocket = runtimeSocketPath(args, "exit-adapter"); - const relaySocket = runtimeSocketPath(args, "exit-relay"); + const adapterSocket = args.exitAdapterSocket || runtimeSocketPath(args, "exit-adapter"); + const relaySocket = args.exitRelaySocket || runtimeSocketPath(args, "exit-relay"); const sourceEnv = runtimeTurnEnv(args); const selectedControlLauncher = args.vmControlLauncher || From c43bc4e58ff161a4f0976024a3a839b6dc4c5b54 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:35:59 -0500 Subject: [PATCH 074/139] test(walletconnect): prove malformed writes reach their intended guards --- .../api/gateway_tests/wallet/walletconnect.rs | 48 +++++++++++++++++-- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 36f23934c..66863c274 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -830,12 +830,50 @@ async fn walletconnect_reconnects_after_runtime_service_restart_with_saved_princ #[tokio::test] async fn walletconnect_refuses_malformed_writes_and_home_authority() { let f = Fixture::new().await; - for body in [ - json!({"key":"session","value":"x","unknown":true}), - json!({"key":"session","value":"x".repeat(2 * 1024 * 1024)}), + f.allow().await; + let (status, _) = f + .route( + &f.connector, + STORAGE, + Some(json!({"key":"control","value":"valid"})), + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "consent and launch reach the storage write path" + ); + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"control","value":null})) + ) + .await + .0, + StatusCode::OK + ); + for (body, reason) in [ + ( + json!({"key":"session","value":"x","unknown":true}), + "request body is invalid", + ), + ( + json!({"key":"session","value":"x".repeat(2 * 1024 * 1024)}), + "request body is invalid", + ), + ( + json!({"key":"","value":"x"}), + "Invalid WalletConnect storage key", + ), + ( + json!({"key":"session","value":"x".repeat(1024 * 1024)}), + "session storage quota exceeded", + ), ] { - let (status, _) = f.route(&f.connector, STORAGE, Some(body)).await; - assert_ne!(status, StatusCode::OK); + let (status, error) = f.route(&f.connector, STORAGE, Some(body)).await; + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert!(error["text"].as_str().unwrap().contains(reason), "{error}"); } let (_, stored) = f.route(&f.connector, STORAGE, None).await; assert_eq!(stored, json!({})); From 3c5174eb37c40a6ec61d6c29fbc94357c84bd2cd Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:36:52 -0500 Subject: [PATCH 075/139] test(walletconnect): bind storage cleanup and verify stale revision retry --- .../api/gateway_tests/wallet/walletconnect.rs | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 66863c274..c69373271 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -1075,6 +1075,92 @@ async fn walletconnect_capsule_owns_storage_and_admission() { assert_eq!(f.calls.load(Ordering::SeqCst), 0); } +#[tokio::test] +async fn walletconnect_delete_storage_checks_selected_launch_before_cleanup_and_allows_revision_retry( +) { + let f = Fixture::new().await; + f.allow().await; + assert_eq!( + f.route( + &f.connector, + STORAGE, + Some(json!({"key":"pairing","value":"keep"})) + ) + .await + .0, + StatusCode::OK + ); + let context = runtime_wallet_authority_for_app_token( + f.data.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &f.connector, + ) + .home_launch_context(); + let wrong = issue_home_projection_launch_token_with_context( + f.data.path(), + WALLET_CAPSULE_ID, + WALLET_WALLETCONNECT_CAPSULE_ID, + &context, + ) + .unwrap(); + for token in [&f.home, &f.inbox, &wrong] { + let origin = if token == &f.home { + format!("http://{}", f.addr) + } else { + "null".into() + }; + let response = f + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, &f.addr) + .header("origin", origin) + .header("x-elastos-home-token", token) + .uri(STORAGE) + .method("DELETE") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 8192) + .await + .unwrap(); + if token == &wrong { + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert!(String::from_utf8_lossy(&bytes).contains("own proof-bound capsule launch")); + } else { + assert_eq!(status, StatusCode::FORBIDDEN); + } + assert_eq!( + f.route(&f.connector, STORAGE, None).await.1["pairing"], + "keep" + ); + } + for _ in 0..2 { + let response = f + .app + .clone() + .oneshot( + Request::builder() + .header(HOST, &f.addr) + .header("origin", "null") + .header("x-elastos-home-token", &f.connector) + .header("if-match", "\"stale\"") + .uri(STORAGE) + .method("DELETE") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + } + assert_eq!(f.route(&f.connector, STORAGE, None).await.1, json!({})); +} + #[tokio::test] async fn walletconnect_opaque_relay_redeems_once_and_rechecks_launch() { let f = Fixture::new().await; From dd19937179e436f9c0da13684721150061250018 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:37:37 -0500 Subject: [PATCH 076/139] test(walletconnect): use proof-bound launches in positive config fixtures --- .../api/gateway_tests/wallet/connectors.rs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index c9de18107..471902497 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -554,10 +554,12 @@ fn test_marketplace_lists_walletconnect_only_once_its_config_is_pinned() { async fn test_walletconnect_connector_accepts_pinned_config() { let dir = tempfile::tempdir().unwrap(); seed_walletconnect_connector_config(dir.path()); - let context = local_home_launch_token_context(dir.path()).unwrap(); - let token = - issue_home_launch_token_with_context(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &context) - .unwrap(); + let authority = passkey_authority(dir.path()); + let token = projection_launch_token_for_authority_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &authority, + ); let provider = MockWalletProvider::default(); let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); @@ -584,10 +586,12 @@ async fn test_walletconnect_connector_accepts_pinned_config() { async fn test_walletconnect_connector_config_returns_pinned_sdk_contract() { let dir = tempfile::tempdir().unwrap(); seed_walletconnect_connector_config(dir.path()); - let context = local_home_launch_token_context(dir.path()).unwrap(); - let token = - issue_home_launch_token_with_context(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID, &context) - .unwrap(); + let authority = passkey_authority(dir.path()); + let token = projection_launch_token_for_authority_context( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + &authority, + ); let provider = MockWalletProvider::default(); let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); From 1b806b9e8bc14b618a12b636368bba460e2f5c25 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:39:23 -0500 Subject: [PATCH 077/139] fix(walletconnect): bound late send completion and expire abandoned prompts --- capsules/wallet-provider/src/storage.rs | 14 ++-- .../src/tests/approvals/transactions.rs | 69 ++++++++++++++----- .../browser/walletconnect-client.mjs | 4 +- docs/WALLET_PROVIDER.md | 12 ++-- .../api/gateway_tests/wallet/connectors.rs | 3 +- .../src/api/gateway_wallet_connectors.rs | 3 +- .../crates/elastos-wallet-contract/src/lib.rs | 4 ++ 7 files changed, 80 insertions(+), 29 deletions(-) diff --git a/capsules/wallet-provider/src/storage.rs b/capsules/wallet-provider/src/storage.rs index 53844c091..910edf591 100644 --- a/capsules/wallet-provider/src/storage.rs +++ b/capsules/wallet-provider/src/storage.rs @@ -231,15 +231,19 @@ pub(super) fn prune_store(mut store: WalletStore, now: u64) -> WalletStore { } // A phone may finish sending after expiry. Preserve this approved receipt until -// its single completion; pending requests and signature handoffs still expire. -fn awaiting_external_transaction(request: &WalletApprovalRequest) -> bool { +// its single completion within the grace period. Abandoned prompts then expire; +// other connectors, pending requests and signature handoffs keep their normal TTL. +fn awaiting_external_transaction(request: &WalletApprovalRequest, now: u64) -> bool { request.status == ApprovalStatus::Approved && request.intent == "transaction_intent" - && request.connector_id.is_some() + && request.connector_id.as_deref() == Some("wallet-walletconnect") + && request.expires_at.saturating_add( + elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS, + ) > now } pub(super) fn approval_authority_is_active(request: &WalletApprovalRequest, now: u64) -> bool { - if awaiting_external_transaction(request) + if awaiting_external_transaction(request, now) || matches!( request.status, ApprovalStatus::Pending | ApprovalStatus::Approved @@ -287,7 +291,7 @@ pub(super) fn expire_approval_if_elapsed(request: &mut WalletApprovalRequest, no request.status, ApprovalStatus::Pending | ApprovalStatus::Approved ) && request.expires_at <= now - && !awaiting_external_transaction(request) + && !awaiting_external_transaction(request, now) { request.status = ApprovalStatus::Expired; request.resolved_at = Some(now); diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 2c5665b0a..7b9213500 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -233,6 +233,12 @@ fn validated_chain_outcome_projection_is_exact_and_idempotent() { #[test] fn transaction_intent_validates_payload_and_allows_external_handoff() { + for connector in ["wallet-metamask", "wallet-walletconnect"] { + external_transaction_handoff_with_expiry(connector); + } +} + +fn external_transaction_handoff_with_expiry(connector: &str) { let dir = tempfile::tempdir().unwrap(); let mut provider = init_provider(dir.path()); let principal_id = "person:local:alice"; @@ -283,7 +289,7 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { invoke_wallet( &mut provider, principal_id, - "wallet-metamask", + connector, WalletProviderOperationV2::LinkVerifiedAccount { proof_binding_id: format!("proof:eip155:20:{external_address}"), chain_namespace: "eip155:20".into(), @@ -314,7 +320,7 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { ) { Response::Ok { data: Some(data) } => { assert_eq!(data["approval_request"]["intent"], "transaction_intent"); - assert_eq!(data["approval_request"]["connector_id"], "wallet-metamask"); + assert_eq!(data["approval_request"]["connector_id"], connector); assert_eq!( data["approval_request"]["payload"]["schema"], "elastos.chain.unsigned_transaction_intent/v1" @@ -335,7 +341,7 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { let transaction = match invoke_wallet( &mut provider, principal_id, - "wallet-metamask", + connector, WalletProviderOperationV2::ApproveConnectorHandoff { request_id: request_id.clone(), reason: "Approved transaction".into(), @@ -349,26 +355,57 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { }; assert_eq!(transaction["from"], external_address); assert_eq!(transaction["chainId"], "0x14"); - let request = provider + let approved = provider .store .approval_requests - .iter_mut() + .iter() .find(|r| r.request_id == request_id) - .unwrap(); - request.expires_at = now_ts() - 1; - provider.store = prune_store(std::mem::take(&mut provider.store), now_ts()); - assert_eq!( + .unwrap() + .clone(); + let now = now_ts(); + let grace = elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS; + for (elapsed, expected) in [ + (1, connector == "wallet-walletconnect"), + (grace - 1, connector == "wallet-walletconnect"), + (grace, false), + (grace + 1, false), + ] { + let mut declined = approved.clone(); + declined.expires_at = now - elapsed; + expire_approval_if_elapsed(&mut declined, now); + assert_eq!( + declined.status == ApprovalStatus::Approved, + expected, + "{connector} after {elapsed}" + ); + assert_eq!( + approval_authority_is_active(&declined, now), + expected, + "declined prompt releases its active quota after grace" + ); + } + if connector == "wallet-walletconnect" { provider .store .approval_requests - .iter() + .iter_mut() .find(|r| r.request_id == request_id) .unwrap() - .status, - ApprovalStatus::Approved - ); + .expires_at = now - 1; + provider.store = prune_store(std::mem::take(&mut provider.store), now); + assert_eq!( + provider + .store + .approval_requests + .iter() + .find(|r| r.request_id == request_id) + .unwrap() + .status, + ApprovalStatus::Approved + ); + } let transaction_hash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - let context = wallet_context(principal_id, "wallet-metamask"); + let context = wallet_context(principal_id, connector); let invalid_completion = wallet_request( &context, WalletProviderOperationV2::CompleteConnectorHandoff { @@ -402,7 +439,7 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { match invoke_wallet( &mut provider, principal_id, - "wallet-metamask", + connector, WalletProviderOperationV2::CompleteConnectorHandoff { request_id: request_id.clone(), payload_hash: payload_hash.clone(), @@ -442,7 +479,7 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { chain_namespace: "eip155:20".into(), network: elastos_wallet_contract::PublicNetwork::new("esc-mainnet").unwrap(), binding: ValidatedChainOutcomeBindingV1::ExternalConnector { - connector_id: "wallet-metamask".into(), + connector_id: connector.into(), originating_address: external_address.into(), }, transaction_hash: transaction_hash.into(), diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs index 77b2dd52d..7c9ccab67 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -113,9 +113,9 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp } if (handoff.signature_type !== 'personal_sign' || typeof handoff.message !== 'string') throw new Error('Runtime returned an invalid signature request.'); const method = 'personal_sign'; - const signature = await provider.request({method,params:method === 'eth_signTypedData_v4' ? [signer,handoff.message] : [signData(handoff.message),signer]},expiry); + const signature = await provider.request({method,params:[signData(handoff.message),signer]},expiry); await check(); - await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,signature,signature_type:method === 'eth_signTypedData_v4' ? 'eip712' : 'personal_sign'})}); + await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,signature,signature_type:'personal_sign'})}); return {status:'completed',effect:'signature'}; }}; } diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 1d49b3880..728876b8d 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -250,9 +250,10 @@ sandboxed frame. `wallet-provider` owns proof verification, linked accounts, approval state and receipts. Runtime accepts the connector's own live launch capability, bound to its principal, session and launch instance, for storage, relay admission, linking and signing handoffs. Each route checks the selected -connector resource and proof binding. Config reads and storage deletion retain -these launch checks while accepting an older storage revision, so a connector can -load the current revision or retry cleanup. Relay use and storage writes require +connector resource and proof binding. Config reads, linking, approval, completion +and storage deletion accept an older storage revision with these launch checks. +A connector can load the current revision, retain a returned result or retry +cleanup. Relay use and storage writes require the current revision. Home owns window orchestration. Mode A connects a phone wallet to sign Runtime challenges and approved requests. @@ -269,7 +270,10 @@ approved request and hash before completion. A closed connector window leaves an approved, unfinished transaction visible with "Check your phone wallet". Opening it again supplies recovery instructions and keeps the send control disabled. A returned transaction hash is passed to Runtime once even if the account, -network or expiry changed during the phone prompt. Runtime checks the returned +network or expiry changed during the phone prompt. An approved WalletConnect +transaction can complete once within 24 hours after expiry. An unfinished prompt +then expires and releases its approval slot; other connectors keep their normal TTL. +Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; the hash alone does not prove that it matches the approved payload. A completion error keeps the hash visible for checking before another send. Unused signatures and ownership diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 471902497..6ec264644 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1320,6 +1320,7 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding "signer", "pending", "expired", + "outside-grace", "principal", "connector", ] { @@ -1340,7 +1341,7 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding "account_id":"fixture-account", "address":address, "proof_type":"siwe", "chain_namespace":"eip155:20", "connector_id":if case == "connector" { WALLET_METAMASK_CAPSULE_ID } else { WALLET_WALLETCONNECT_CAPSULE_ID }, "principal_id":if case == "principal" { "other-principal" } else { &owner.principal_id }, - "payload_hash":payload, "created_at":now_ts(), "expires_at":if case == "expired" { 0 } else { now_ts() + 600 }, + "payload_hash":payload, "created_at":now_ts(), "expires_at":if case == "expired" { now_ts()-1 } else if case == "outside-grace" { now_ts()-elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS } else { now_ts()+600 }, })]), ..Default::default() })); diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index d78b54e60..5acfe26f4 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -392,7 +392,8 @@ async fn walletconnect_request_binding( && (request["expires_at"].as_u64().is_some_and(|expiry| expiry > now_ts()) // The phone can return a sent transaction after the approval TTL. // Approved state still binds its one completion to the same payload. - || status == "approved" && request["intent"] == "transaction_intent") + || status == "approved" && request["intent"] == "transaction_intent" + && request["expires_at"].as_u64().is_some_and(|expiry| expiry.saturating_add(elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS) > now_ts())) && request["payload_hash"] .as_str() .is_some_and(walletconnect_hash), diff --git a/elastos/crates/elastos-wallet-contract/src/lib.rs b/elastos/crates/elastos-wallet-contract/src/lib.rs index a39b0a4e2..8fe313834 100644 --- a/elastos/crates/elastos-wallet-contract/src/lib.rs +++ b/elastos/crates/elastos-wallet-contract/src/lib.rs @@ -17,6 +17,10 @@ use sha2::{Digest, Sha256}; use std::collections::BTreeSet; use std::fmt; +/// Time to retain an approved WalletConnect send receipt after its request expires. +/// The phone can finish a send after expiry; an abandoned prompt releases its quota afterward. +pub const WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS: u64 = 24 * 60 * 60; + pub const WALLET_PROTOCOL_VERSION: &str = "2.3"; pub const WALLET_BUS_OPERATION: &str = "wallet_contract"; pub const WALLET_REQUEST_SCHEMA: &str = "elastos.wallet.provider-request/v2"; From 4aaaa79e6b442bab77a6999bced28fe6597ef6d4 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:39:52 -0500 Subject: [PATCH 078/139] fix(walletconnect): preserve unrelated Object provider dependency pins --- capsules/object-provider/Cargo.lock | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/capsules/object-provider/Cargo.lock b/capsules/object-provider/Cargo.lock index cae2aec87..b5adb3daf 100644 --- a/capsules/object-provider/Cargo.lock +++ b/capsules/object-provider/Cargo.lock @@ -129,7 +129,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -140,7 +140,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1828,7 +1828,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3658,7 +3658,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4285,7 +4285,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4623,7 +4623,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4682,7 +4682,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5094,7 +5094,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5290,7 +5290,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6416,7 +6416,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] From 65d8ce91c3de1998013a0f411f28d8718d312b20 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:41:22 -0500 Subject: [PATCH 079/139] test(walletconnect): carry the project file through release packaging --- docs/WALLET_PROVIDER.md | 3 +-- scripts/prepare-release-platform-test.py | 6 +++++- scripts/publish-release.sh | 2 +- scripts/setup-source-home.sh | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 728876b8d..dd3c3dfc0 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -322,8 +322,7 @@ the `connectWalletConnectEvm` adapter inside the capsule's `vendor` directory; release packaging includes those bytes in the verified capsule archive. The release workflow reads the operator's `REOWN_PROJECT_ID` secret. Independent -operators can supply `ELASTOS_WALLETCONNECT_PROJECT_FILE` or -`ELASTOS_WALLETCONNECT_PROJECT_ID` during release preparation or source-home +operators can supply `ELASTOS_WALLETCONNECT_PROJECT_FILE` during release preparation or source-home setup. Staging checks the reviewed adapter hash and includes `vendor/connector.json` before the capsule is hashed. An existing operator configuration in `ElastOS/SystemServices/WalletConnect/config.json` takes precedence. Source uses diff --git a/scripts/prepare-release-platform-test.py b/scripts/prepare-release-platform-test.py index 4986911c0..3ebe54c55 100644 --- a/scripts/prepare-release-platform-test.py +++ b/scripts/prepare-release-platform-test.py @@ -757,11 +757,15 @@ def test_success_uses_real_packaging_and_receipt(self): self.assertEqual((output / "platform-input.json").read_bytes(), before) def test_walletconnect_operator_config_and_bundle_enter_the_verified_release(self): - output, result = self.prepare(env={**self.env, "ELASTOS_WALLETCONNECT_PROJECT_ID": "fixture-project-id"}) + project = self.root / "operator-project" + project.write_text("fixture-project-id") + project.chmod(0o600) + output, result = self.prepare(env={**self.env, "ELASTOS_WALLETCONNECT_PROJECT_FILE": str(project)}) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) with tarfile.open(output / "artifacts/wallet-walletconnect.tar.gz") as archive: sdk = archive.extractfile("wallet-walletconnect/vendor/reown-appkit.js").read() config = json.loads(archive.extractfile("wallet-walletconnect/vendor/connector.json").read()) + self.assertEqual(archive.getmember("wallet-walletconnect/vendor/connector.json").mode & 0o777, 0o600) self.assertEqual(config["project_id"], "fixture-project-id") self.assertEqual(config["sdk_sha256"], hashlib.sha256(sdk).hexdigest()) result = self.command("python3", "scripts/release-platform-input.py", "verify", str(output)) diff --git a/scripts/publish-release.sh b/scripts/publish-release.sh index 675821ff4..da9601219 100755 --- a/scripts/publish-release.sh +++ b/scripts/publish-release.sh @@ -497,7 +497,7 @@ build_packaged_capsule_archive() { mkdir -p "${stage_root}/${capsule_name}/bin" || return install -m 755 "$native_renderer" "${stage_root}/${capsule_name}/bin/home-cli" || return fi - if [[ "$capsule_name" == wallet-walletconnect && -n "${ELASTOS_WALLETCONNECT_PROJECT_FILE:-}${ELASTOS_WALLETCONNECT_PROJECT_ID:-}" ]]; then + if [[ "$capsule_name" == wallet-walletconnect && -n "${ELASTOS_WALLETCONNECT_PROJECT_FILE:-}" ]]; then node scripts/stage-walletconnect-release.mjs "${stage_root}/${capsule_name}" || return fi create_capsule_tar "$archive" "$stage_root" "$capsule_name" || return diff --git a/scripts/setup-source-home.sh b/scripts/setup-source-home.sh index 392e2f842..dbc6dd28b 100755 --- a/scripts/setup-source-home.sh +++ b/scripts/setup-source-home.sh @@ -1689,7 +1689,7 @@ stamp_source_home_components_manifest echo "[setup-source-home] install app capsules and manifest entrypoints" install_app_capsules -if [[ -n "${ELASTOS_WALLETCONNECT_PROJECT_FILE:-}${ELASTOS_WALLETCONNECT_PROJECT_ID:-}" ]]; then +if [[ -n "${ELASTOS_WALLETCONNECT_PROJECT_FILE:-}" ]]; then node "${ROOT}/scripts/stage-walletconnect-release.mjs" "${DATA_DIR}/capsules/wallet-walletconnect" fi for retired_provider in "${RETIRED_SOURCE_HOME_PROVIDER_BINARIES[@]}"; do From 3e4bff7b35296c47d225a5899825a1e25f47fa10 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:42:21 -0500 Subject: [PATCH 080/139] fix(walletconnect): keep connector config owner-only in release archives --- scripts/publish-release.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/publish-release.sh b/scripts/publish-release.sh index da9601219..fe040ffca 100755 --- a/scripts/publish-release.sh +++ b/scripts/publish-release.sh @@ -641,6 +641,7 @@ def normalize(info): info.uname = info.gname = "" info.pax_headers = {} info.mode = 0o777 if info.issym() else ( + 0o600 if info.isfile() and info.name == "wallet-walletconnect/vendor/connector.json" else 0o755 if info.isdir() or info.mode & 0o111 else 0o644 ) return info From 0e0f80b5734850e40d226f1b672ad31ca5bbe306 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 16:43:42 -0500 Subject: [PATCH 081/139] fix(exit): remove the import moved with shared validation --- capsules/exit-provider/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/capsules/exit-provider/src/main.rs b/capsules/exit-provider/src/main.rs index fb944a7f3..792233abf 100644 --- a/capsules/exit-provider/src/main.rs +++ b/capsules/exit-provider/src/main.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::BTreeMap; use std::io::{self, BufRead, Read, Write}; -use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; +use std::net::{SocketAddr, ToSocketAddrs}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use url::Url; From 0f40cf0e38625d92f0c94603a6777fcad1a8db1a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 17:14:53 -0500 Subject: [PATCH 082/139] test(walletconnect): wait for restored subscriptions and isolate engine pairings --- .../walletconnect-real-browser-fixture.mjs | 12 +++++++- .../walletconnect-real-preflight-smoke.mjs | 30 ++++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/scripts/lib/walletconnect-real-browser-fixture.mjs b/scripts/lib/walletconnect-real-browser-fixture.mjs index 4448352dd..5986eacab 100644 --- a/scripts/lib/walletconnect-real-browser-fixture.mjs +++ b/scripts/lib/walletconnect-real-browser-fixture.mjs @@ -12,11 +12,12 @@ window.runtimeTrace = []; window.phase = 'options'; const options = await window.walletConnectTestOptions(); const origin = new URL(import.meta.url).origin; +let storageRevision; const api = async (resource, input = {}) => { const trace = {resource, status:'request'}; if (window.runtimeTrace.length < 128) window.runtimeTrace.push(trace); const response = await fetch(`${origin}/api/apps/wallet-walletconnect/${resource}`, { - ...input, headers: { 'content-type':'application/json', 'x-elastos-home-token':options.connector }, + ...input, headers: { 'content-type':'application/json', 'x-elastos-home-token':options.connector, ...(storageRevision ? {'if-match':storageRevision} : {}) }, }); trace.status = response.status; if (!response.ok) { @@ -42,7 +43,16 @@ const api = async (resource, input = {}) => { } return values; }; +// Each engine owns a disposable pairing. Cleanup advances Runtime's revision; +// the next engine reads it before the SDK can load or write protocol state. +window.closeWalletConnectFixture = async () => { + const { disconnectWalletConnectEvm } = await import('./vendor/reown-appkit.js'); + try { await disconnectWalletConnectEvm({api}); } + finally { await api('storage', {method:'DELETE'}); } +}; try { + window.phase = 'config'; + storageRevision = (await api('wallet/config')).walletconnect.storage_revision; window.phase = 'import'; const { connectWalletConnectEvm } = await import('./vendor/reown-appkit.js'); window.phase = 'connect'; diff --git a/scripts/walletconnect-real-preflight-smoke.mjs b/scripts/walletconnect-real-preflight-smoke.mjs index 9eafa8223..b36e1177a 100644 --- a/scripts/walletconnect-real-preflight-smoke.mjs +++ b/scripts/walletconnect-real-preflight-smoke.mjs @@ -99,6 +99,19 @@ try { .replace(/([?&](?:auth|symKey|token)=)[^&\s"']+/g,'$1[redacted]').slice(0,384)); }); }); + const pingReadySession = async topic => { + run.operation = 'session-subscription'; + // transportOpen resolves at WebSocket connection. A restored session + // receives peer RPCs only after the SDK acknowledges its topic subscription. + await frame.waitForFunction(() => { + const provider = window.provider; + return provider?.signer?.client.core.relayer.subscriber.topics.includes(provider.session?.topic); + }, null, {timeout:20000, polling:100}); + assert.ok(wallet.core.relayer.subscriber.topics.includes(topic)); + run.operation = 'session-ping'; + await bounded(wallet.ping({topic})); + run.operation = 'session-ping-complete'; + }; run.phase = 'home'; assert.equal((await page.goto(`${options.origin}/apps/home/`, {timeout:10000})).status(), 200); run.phase = 'capsule'; @@ -139,7 +152,7 @@ try { await frame.waitForFunction(() => window.provider?.connected || window.failed, null, {timeout:20000, polling:100}); assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => window.provider.session.topic), session.topic); - await bounded(wallet.ping({topic:session.topic})); + await pingReadySession(session.topic); run.paired = true; run.pairing = 'PASS'; for (const phase of ['reload', 'homeRestart']) { @@ -150,7 +163,7 @@ try { assert.equal(await frame.evaluate(() => window.failed), undefined); assert.equal(await frame.evaluate(() => window.provider.session.topic), session.topic); assert.equal(await frame.locator('dialog[open] canvas').count(), 0); - await bounded(wallet.ping({topic:session.topic})); + await pingReadySession(session.topic); assert.equal(proposals, 1); run[phase] = 'PASS'; } @@ -160,6 +173,7 @@ try { for (const kind of ['pairing', 'keychain', 'session']) assert.ok(run.runtimeWrites[kind] > 0, `${kind} persisted through Runtime`); run.status = 'PASS'; } catch (error) { + run.failureDetail = /timeout|timed out/i.test(error.message) ? 'timeout' : /No matching key/i.test(error.message) ? 'session-key' : 'other'; run.failureKind = ['TimeoutError','AssertionError','Error'].includes(error.name) ? error.name : 'Error'; run.status = 'FAIL'; } finally { @@ -178,14 +192,22 @@ try { ]); } catch { run.stateUnavailable = true; } } + if (frame) { + try { + await bounded(frame.evaluate(() => window.closeWalletConnectFixture()), 10000); + run.fixtureCleanup = 'PASS'; + } catch { + run.fixtureCleanup = 'FAIL'; + run.status = 'FAIL'; + } + } try { for (const session of wallet?.session.getAll() || []) await bounded(wallet.disconnect({topic:session.topic, reason:{code:6000, message:'Test complete'}}), 5000); await wallet?.core.relayer.transportClose(); } catch { run.walletCleanup = 'transport closed at process exit'; } await browser?.close(); } - // Stop at the first Chromium blocker, as required by the round's brief. - if (engine === 'chromium' && run.status !== 'PASS') break; + // Both engines report independently; any failed journey still fails this gate. } } catch { result.setup = 'FAIL'; } if (evidence) { From 85c652458c3b02858bbacfaa92edfa62bd982dd8 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 18:01:48 -0500 Subject: [PATCH 083/139] fix(walletconnect): accept the pinned SDK numeric chain identifier --- .../wallet-walletconnect/browser/walletconnect-client.mjs | 7 +++++-- scripts/lib/walletconnect-capsule-fixture.mjs | 4 +++- scripts/walletconnect-capsule.test.mjs | 3 +++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs index 7c9ccab67..7ac23b749 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -9,8 +9,11 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp }; const chain = async () => { const value = await provider.request({method:'eth_chainId'}); - if (!/^0x[0-9a-fA-F]+$/.test(value || '')) throw new Error('Wallet returned an invalid chain.'); - return `eip155:${Number.parseInt(value,16)}`; + // The pinned WalletConnect provider returns a number; EIP-1193 wallets use hex. + const id = typeof value === 'number' ? value + : typeof value === 'string' && /^0x[0-9a-fA-F]+$/.test(value) ? Number(value) : NaN; + if (!Number.isSafeInteger(id) || id <= 0) throw new Error('Wallet returned an invalid chain.'); + return `eip155:${id}`; }; const same = (a,b) => String(a).toLowerCase() === String(b).toLowerCase(); const signData = message => /^0[xX](?:[0-9a-fA-F]{2})*$/.test(message) ? '0x'+message.slice(2) diff --git a/scripts/lib/walletconnect-capsule-fixture.mjs b/scripts/lib/walletconnect-capsule-fixture.mjs index 93c475e58..26ac07457 100644 --- a/scripts/lib/walletconnect-capsule-fixture.mjs +++ b/scripts/lib/walletconnect-capsule-fixture.mjs @@ -14,6 +14,8 @@ export async function exerciseWalletConnect(scenario='valid') { const provider={connected:true,session:{expiry:clock()/1000+3600,namespaces:{eip155:{methods:scenario==='typed-unavailable'?['personal_sign']:['personal_sign','eth_sendTransaction','eth_signTypedData_v4']}}},signer:{client:{core:{relayer:{connected:true}}}}, on:(name,fn)=>events.set(name,fn),async request(input,expiry){calls.push({...input,expiry}); if(input.method==='eth_accounts')return [scenario==='wrong-account'||changed&&kind==='account-change-during-send'?`0x${'ab'.repeat(20)}`:address]; + if(input.method==='eth_chainId'&&scenario.startsWith('numeric-chain'))return 20; + if(input.method==='eth_chainId'&&scenario.startsWith('invalid-chain:'))return JSON.parse(scenario.slice('invalid-chain:'.length)); if(input.method==='eth_chainId')return scenario==='wrong-chain'||changed&&kind==='chain-change-during-send'?'0x1':'0x14'; if(['personal_sign','eth_signTypedData_v4'].includes(input.method)){if(signatureIntent)change();return signature;} if(input.method==='eth_sendTransaction'){change();return scenario==='invalid-hash'?'Open a fake recovery website':transactionHash;} @@ -38,7 +40,7 @@ export async function exerciseWalletConnect(scenario='valid') { }; const client=createWalletConnectClient({api,origin:'http://localhost:61180',clearMemory:()=>{memoryCleared=true;}, loadAdapter:async()=>({connectWalletConnectEvm:async options=>{assert.equal(options.contextKey,'wallet-walletconnect');return provider;},disconnectWalletConnectEvm:async()=>{}})}); - try {return {result:await client.effect({kind:scenario.startsWith('link')?'link':scenario==='disconnect'?'disconnect':'approve',approvalRequestId:'approval:fixture'}),calls,routes,memoryCleared};} + try {return {result:await client.effect({kind:(scenario.startsWith('link')||scenario==='numeric-chain-link')?'link':scenario==='disconnect'?'disconnect':'approve',approvalRequestId:'approval:fixture'}),calls,routes,memoryCleared};} catch(error){return {error:error.message,calls,routes,memoryCleared};} finally{Date.now=clock;} } diff --git a/scripts/walletconnect-capsule.test.mjs b/scripts/walletconnect-capsule.test.mjs index 03642cd48..29f8e3e28 100644 --- a/scripts/walletconnect-capsule.test.mjs +++ b/scripts/walletconnect-capsule.test.mjs @@ -61,3 +61,6 @@ test('a stalled old SDK disconnect cannot block a new storage generation',async for(let i=0;i<10;i++)await Promise.resolve();assert.equal(loads,1); t.mock.timers.tick(5000);assert.deepEqual(await pending,{status:'linked'});assert.equal(loads,2); }); + +for(const scenario of ['numeric-chain','numeric-chain-link'])test(`capsule accepts the pinned SDK numeric chain for ${scenario}`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(r.error,undefined);assert.equal(r.result.status,scenario.endsWith('link')?'linked':'completed');}); +for(const value of [0,-1,1.5,9007199254740992,'20','0x0','0x20000000000000',null])test(`capsule refuses invalid chain ${JSON.stringify(value)} before authority changes`,async()=>{const r=await exerciseWalletConnect('invalid-chain:'+JSON.stringify(value));assert.match(r.error,/invalid chain/);assert.equal(r.routes.filter(c=>c.path.endsWith('/approve')||c.path.endsWith('/verify')).length,0);}); From fd82004fa54d2f4a17499edfba636f4ee2a694fe Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 19:30:17 -0500 Subject: [PATCH 084/139] fix(walletconnect): preserve upstream licence bytes in diff checks --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitattributes b/.gitattributes index 33d27b9c9..1d5d2ca75 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,3 +9,5 @@ third-party/selkies/patches/*.patch -whitespace scripts/build/crosvm-lifecycle-fds.patch whitespace=-blank-at-eol # Minified upstream template literals retain meaningful whitespace in the bundle. capsules/wallet-walletconnect/vendor/reown-appkit.js -whitespace linguist-generated=true +# This file keeps upstream licence bytes verbatim. +capsules/wallet-walletconnect/vendor/LICENSES.txt -whitespace conflict-marker-size=32 From d64301a7ff843178e62b1a93f2fb57a4b82edf51 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 20:07:10 -0500 Subject: [PATCH 085/139] test(exit): place parser unit tests in the shared library target --- capsules/exit-provider/src/lib.rs | 144 +++++++++++++++++++ capsules/exit-provider/src/main.rs | 213 ----------------------------- 2 files changed, 144 insertions(+), 213 deletions(-) diff --git a/capsules/exit-provider/src/lib.rs b/capsules/exit-provider/src/lib.rs index c5ed35df8..003b76f28 100644 --- a/capsules/exit-provider/src/lib.rs +++ b/capsules/exit-provider/src/lib.rs @@ -622,3 +622,147 @@ pub fn default_max_active_remote_streams() -> u64 { pub fn default_remote_carrier_service() -> String { DEFAULT_REMOTE_CARRIER_EXIT_SERVICE.to_string() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn services_installed_legacy_config_parses_without_accepting_unknown_schema() { + let mut config = json!({"remote_carrier_exits":[{ + "id":"services-bob", "grant_id":"services-grant-bob", "peer_did":"did:elastos:bob", + "connect_ticket":"private-ticket", "allowed_principals":["person:alice"], + "allowed_hosts":["*"], "allowed_schemes":["tcp","tls"], "allowed_ports":[80,443], + "max_active_streams":1, "max_active_streams_per_principal":1 + }]}); + config["schema"] = json!("elastos.browser.local-exit.config/v1"); + assert!( + parse_config(config.clone()).is_ok(), + "released Services config must parse" + ); + config["schema"] = json!("elastos.exit.unrecognized/v1"); + assert!(parse_config(config).is_err()); + } + + #[test] + fn backend_config_rejects_invalid_adapter_ipc() { + assert!(parse_config(json!({ + "backends": [{ + "id": "bad-http-ipc", + "kind": "http_fetch", + "allowed_hosts": ["glidefinance.io"], + "adapter_ipc": { + "kind": "unix_socket", + "path": "/tmp/elastos-browser-stream.sock" + } + }] + })) + .is_err()); + assert!(parse_config(json!({ + "backends": [{ + "id": "bad-http-relay", + "kind": "http_fetch", + "allowed_hosts": ["glidefinance.io"], + "relay_ipc": { + "kind": "unix_socket", + "path": "/tmp/elastos-exit-relay.sock" + } + }] + })) + .is_err()); + assert!(parse_config(json!({ + "backends": [{ + "id": "bad-relay-without-adapter", + "kind": "stream_relay", + "allowed_hosts": ["glidefinance.io"], + "relay_ipc": { + "kind": "unix_socket", + "path": "/tmp/elastos-exit-relay.sock" + } + }] + })) + .is_err()); + assert!(parse_config(json!({ + "backends": [{ + "id": "bad-shared-ipc", + "kind": "stream_relay", + "allowed_hosts": ["glidefinance.io"], + "adapter_ipc": { + "kind": "unix_socket", + "path": "/tmp/elastos-browser-stream.sock" + }, + "relay_ipc": { + "kind": "unix_socket", + "path": "/tmp/elastos-browser-stream.sock" + } + }] + })) + .is_err()); + assert!(parse_config(json!({ + "backends": [{ + "id": "bad-relative-ipc", + "kind": "stream_relay", + "allowed_hosts": ["glidefinance.io"], + "adapter_ipc": { + "kind": "unix_socket", + "path": "relative.sock" + } + }] + })) + .is_err()); + } + + #[test] + fn remote_carrier_exit_config_rejects_missing_permission_and_hidden_fields() { + let valid = json!({"remote_carrier_exits": [{ + "id": "server-exit", + "grant_id": "operator-grant:server-exit:alice", + "peer_did": "did:elastos:server", + "connect_ticket": "carrier-ticket-server-exit-alice", + "allowed_principals": ["person:local:alice"], + "allowed_hosts": ["example.com"], + "max_active_streams": 2 + }]}); + assert!(parse_config(valid.clone()).is_ok()); + for field in ["grant_id", "allowed_principals", "connect_ticket"] { + let mut config = valid.clone(); + config["remote_carrier_exits"][0] + .as_object_mut() + .unwrap() + .remove(field); + assert!(parse_config(config).unwrap_err().contains(field)); + } + for (field, value, expected) in [ + ("raw_socket", json!(true), "unknown field"), + ("connect_ticket", json!(" ticket-with-padding"), "padded"), + ( + "max_active_streams_per_principal", + json!(0), + "max_active_streams_per_principal", + ), + ( + "max_active_streams_per_principal", + json!(3), + "max_active_streams_per_principal", + ), + ("expires_at", json!(0), "expires_at"), + ] { + let mut config = valid.clone(); + config["remote_carrier_exits"][0][field] = value; + assert!(parse_config(config).unwrap_err().contains(expected)); + } + } + + #[test] + fn backend_config_rejects_hidden_fields() { + let response = parse_config(json!({ + "backends": [{ + "id": "bad", + "kind": "http_fetch", + "allowed_hosts": ["example.com"], + "raw_socket": true + }] + })); + assert!(response.unwrap_err().contains("unknown field")); + } +} diff --git a/capsules/exit-provider/src/main.rs b/capsules/exit-provider/src/main.rs index 792233abf..f69230967 100644 --- a/capsules/exit-provider/src/main.rs +++ b/capsules/exit-provider/src/main.rs @@ -1102,18 +1102,6 @@ mod tests { }]}) } - #[test] - fn services_installed_legacy_config_parses_without_accepting_unknown_schema() { - let mut config = services_exit_config_for_test(); - config["schema"] = json!("elastos.browser.local-exit.config/v1"); - assert!( - parse_config(config.clone()).is_ok(), - "released Services config must parse" - ); - config["schema"] = json!("elastos.exit.unrecognized/v1"); - assert!(parse_config(config).is_err()); - } - #[test] fn refresh_config_preserves_live_stream_quota_and_close_owner() { let mut provider = ExitProvider::new(); @@ -1460,85 +1448,6 @@ mod tests { assert!(err.contains("unknown field")); } - #[test] - fn backend_config_rejects_invalid_adapter_ipc() { - let mut provider = ExitProvider::new(); - assert_eq!( - error_code(provider.init(json!({ - "backends": [{ - "id": "bad-http-ipc", - "kind": "http_fetch", - "allowed_hosts": ["glidefinance.io"], - "adapter_ipc": { - "kind": "unix_socket", - "path": "/tmp/elastos-browser-stream.sock" - } - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "backends": [{ - "id": "bad-http-relay", - "kind": "http_fetch", - "allowed_hosts": ["glidefinance.io"], - "relay_ipc": { - "kind": "unix_socket", - "path": "/tmp/elastos-exit-relay.sock" - } - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "backends": [{ - "id": "bad-relay-without-adapter", - "kind": "stream_relay", - "allowed_hosts": ["glidefinance.io"], - "relay_ipc": { - "kind": "unix_socket", - "path": "/tmp/elastos-exit-relay.sock" - } - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "backends": [{ - "id": "bad-shared-ipc", - "kind": "stream_relay", - "allowed_hosts": ["glidefinance.io"], - "adapter_ipc": { - "kind": "unix_socket", - "path": "/tmp/elastos-browser-stream.sock" - }, - "relay_ipc": { - "kind": "unix_socket", - "path": "/tmp/elastos-browser-stream.sock" - } - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "backends": [{ - "id": "bad-relative-ipc", - "kind": "stream_relay", - "allowed_hosts": ["glidefinance.io"], - "adapter_ipc": { - "kind": "unix_socket", - "path": "relative.sock" - } - }] - }))), - "invalid_config" - ); - } - #[test] fn configured_http_fetch_backend_can_fetch_allowlisted_target() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); @@ -2266,113 +2175,6 @@ mod tests { assert_eq!(accounting["principal_active_streams"], 0); } - #[test] - fn remote_carrier_exit_config_rejects_missing_permission_and_hidden_fields() { - let mut provider = ExitProvider::new(); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "peer_did": "did:elastos:server", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"] - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "allowed_hosts": ["example.com"] - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"] - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "connect_ticket": "carrier-ticket-server-exit-alice", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"], - "raw_socket": true - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"], - "connect_ticket": " ticket-with-padding" - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"], - "max_active_streams": 2, - "max_active_streams_per_principal": 0 - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"], - "max_active_streams": 2, - "max_active_streams_per_principal": 3 - }] - }))), - "invalid_config" - ); - assert_eq!( - error_code(provider.init(json!({ - "remote_carrier_exits": [{ - "id": "server-exit", - "grant_id": "operator-grant:server-exit:alice", - "peer_did": "did:elastos:server", - "allowed_principals": ["person:local:alice"], - "allowed_hosts": ["example.com"], - "expires_at": 0 - }] - }))), - "invalid_config" - ); - } - #[test] fn stream_backend_can_limit_schemes_and_ports() { let mut provider = ExitProvider::new(); @@ -2404,19 +2206,4 @@ mod tests { "exit_policy_blocked" ); } - - #[test] - fn backend_config_rejects_hidden_fields() { - let mut provider = ExitProvider::new(); - let response = provider.init(json!({ - "backends": [{ - "id": "bad", - "kind": "http_fetch", - "allowed_hosts": ["example.com"], - "raw_socket": true - }] - })); - - assert_eq!(error_code(response), "invalid_config"); - } } From d325839706a834547a375af65518d20ae87cabc3 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 20:56:52 -0500 Subject: [PATCH 086/139] test(walletconnect): use canonical owned cleanup fixture roots --- .../elastos-server/src/api/gateway_tests/wallet/connectors.rs | 2 +- elastos/crates/elastos-server/src/auth.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 6ec264644..32078cd20 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1575,7 +1575,7 @@ async fn test_walletconnect_account_removal_clears_its_store_through_wallet_rout (WALLET_WALLETCONNECT_CAPSULE_ID, true), (WALLET_METAMASK_CAPSULE_ID, false), ] { - let dir = tempfile::tempdir().unwrap(); + let dir = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); let owner = passkey_authority(dir.path()); let token = app_token_for_authority(dir.path(), WALLET_CAPSULE_ID, &owner); let principal = &owner.principal_id; diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index c05292624..de2cca1f5 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -15788,7 +15788,7 @@ mod tests { #[test] fn walletconnect_removed_principal_clears_only_its_session_file() { - let data = tempfile::tempdir().unwrap(); + let data = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); let principal = upsert_principal_for_binding(data.path(), passkey_binding(1, 100, 100), 100).unwrap(); let directory = data @@ -15815,7 +15815,7 @@ mod tests { #[test] fn walletconnect_principal_cleanup_failure_preserves_the_committed_auth_result() { - let data = tempfile::tempdir().unwrap(); + let data = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap(); let principal = upsert_principal_for_binding(data.path(), passkey_binding(1, 100, 100), 100).unwrap(); let directory = data From 779e67527835ea9bc112cad241d076851f9e4085 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 20:59:16 -0500 Subject: [PATCH 087/139] test(exit): retain provider parse error code coverage --- capsules/exit-provider/src/main.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/capsules/exit-provider/src/main.rs b/capsules/exit-provider/src/main.rs index f69230967..ad57f02e0 100644 --- a/capsules/exit-provider/src/main.rs +++ b/capsules/exit-provider/src/main.rs @@ -1179,7 +1179,11 @@ mod tests { json!({"op":"refresh_config","request_id":"refresh-bad","config":config}), ) .unwrap(); - assert!(matches!(provider.handle(request), Response::Error { .. })); + let response = provider.handle(request); + assert!(matches!(&response, Response::Error { .. })); + if mutation == "invalid" { + assert_eq!(error_code(response), "invalid_config"); + } assert_eq!( serde_json::to_value(provider.status(Some("person:alice".into()))).unwrap(), before @@ -1243,6 +1247,10 @@ mod tests { assert_eq!(response["status"], "ok"); assert_eq!(response["data"]["backend_count"], 0); + assert_eq!( + error_code(provider.init(json!({"timeout_secs": 0}))), + "invalid_config" + ); } #[test] From 495016361314b0bb63cc47a1082bbd6ce2821907 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 22:49:38 -0500 Subject: [PATCH 088/139] test(wallet): wait for ready connector controls before clicking --- ...-wallet-connector-launch-headless-smoke.mjs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/scripts/home-wallet-connector-launch-headless-smoke.mjs b/scripts/home-wallet-connector-launch-headless-smoke.mjs index 8954e9058..8c3a0274a 100644 --- a/scripts/home-wallet-connector-launch-headless-smoke.mjs +++ b/scripts/home-wallet-connector-launch-headless-smoke.mjs @@ -501,6 +501,8 @@ try { await homeGui.locator('#launcher-grid [data-target="wallet"]').click(); await waitFor(() => frameFor(page, "wallet"), 15_000, "real Wallet frame"); const wallet = frameFor(page, "wallet"); + // The static Settings button can exist before Wallet's module binds handlers. + await wallet.waitForLoadState("domcontentloaded", { timeout: 15_000 }); await wallet.waitForSelector("#wallet-settings-open", { timeout: 15_000 }); const connectorLabels = Object.freeze({ "wallet-metamask": "Connect wallet", @@ -519,15 +521,13 @@ try { assert(walletUiBeforeConnectors.settingsOpen === false, "Wallet fixture opened settings early"); for (const [target, connectLabel] of Object.entries(connectorLabels)) { - await wallet.evaluate(({ connectorTarget }) => { - const drawer = document.querySelector("#wallet-settings-drawer"); - if (drawer?.hidden !== false) { - document.querySelector("#wallet-settings-open")?.click(); - } - document - .querySelector(`[data-wallet-open-method="${connectorTarget}"]`) - ?.click(); - }, { connectorTarget: target }); + if (await wallet.locator("#wallet-settings-drawer").isHidden()) { + await wallet.locator("#wallet-settings-open").click({ timeout: 15_000 }); + } + // Connector controls arrive with the summary; wait for an actionable button. + await wallet.locator(`[data-wallet-open-method="${target}"]`).click({ + timeout: 15_000, + }); await waitFor(() => frameFor(page, target), 15_000, `${target} connector UI`); const connector = frameFor(page, target); await connector.waitForSelector("#wallet-connect", { timeout: 15_000 }); From 5318a192658e8a8c44b3320e51d042ccfd760ab0 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 13 Nov 2026 22:53:07 -0500 Subject: [PATCH 089/139] test(wallet): preserve settings continuity during ready connector activation --- ...wallet-connector-launch-headless-smoke.mjs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/scripts/home-wallet-connector-launch-headless-smoke.mjs b/scripts/home-wallet-connector-launch-headless-smoke.mjs index 8c3a0274a..a79049caa 100644 --- a/scripts/home-wallet-connector-launch-headless-smoke.mjs +++ b/scripts/home-wallet-connector-launch-headless-smoke.mjs @@ -521,13 +521,20 @@ try { assert(walletUiBeforeConnectors.settingsOpen === false, "Wallet fixture opened settings early"); for (const [target, connectLabel] of Object.entries(connectorLabels)) { - if (await wallet.locator("#wallet-settings-drawer").isHidden()) { - await wallet.locator("#wallet-settings-open").click({ timeout: 15_000 }); - } - // Connector controls arrive with the summary; wait for an actionable button. - await wallet.locator(`[data-wallet-open-method="${target}"]`).click({ - timeout: 15_000, + // Connector controls arrive with the summary, after the static Wallet HTML. + await wallet.locator(`[data-wallet-open-method="${target}"]`).waitFor({ + state: "attached", timeout: 15_000, }); + // Keep Settings open for the continuity proof while activating the handler. + await wallet.evaluate(({ connectorTarget }) => { + const drawer = document.querySelector("#wallet-settings-drawer"); + if (drawer?.hidden !== false) { + document.querySelector("#wallet-settings-open").click(); + } + document + .querySelector(`[data-wallet-open-method="${connectorTarget}"]`) + .click(); + }, { connectorTarget: target }); await waitFor(() => frameFor(page, target), 15_000, `${target} connector UI`); const connector = frameFor(page, target); await connector.waitForSelector("#wallet-connect", { timeout: 15_000 }); From 9d9a3dec0aa11adc6e38bdf11f0348c76606bd77 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 02:53:50 -0500 Subject: [PATCH 090/139] fix(walletconnect): select relay Exit by Browser helper readiness --- .../wallet/walletconnect_real_relay.rs | 2 +- .../crates/elastos-server/src/server_infra.rs | 5 + .../elastos-server/src/setup/walletconnect.rs | 156 ++++++++++++++++-- 3 files changed, 147 insertions(+), 16 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs index bbbe9a336..4f57ad6b2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect_real_relay.rs @@ -70,7 +70,7 @@ async fn production_exit(data: &std::path::Path) -> Arc { let bridge = ProviderBridge::spawn( std::path::Path::new(&binary), BridgeProviderConfig { - extra: crate::setup::walletconnect::exit_config(Value::Null, Some(&config)), + extra: crate::setup::walletconnect::exit_config(Value::Null, Some(&config), false), ..Default::default() }, ) diff --git a/elastos/crates/elastos-server/src/server_infra.rs b/elastos/crates/elastos-server/src/server_infra.rs index 0e25cafe1..07f2b3cdd 100644 --- a/elastos/crates/elastos-server/src/server_infra.rs +++ b/elastos/crates/elastos-server/src/server_infra.rs @@ -1203,6 +1203,7 @@ async fn setup_server_infrastructure_impl( let browser_exit = browser_available .then(|| browser_local_exit_config_from_env(&data_dir)) .flatten(); + let mut browser_exit_running = false; for (name, config) in [ ("browser-local-exit", browser_exit), ( @@ -1224,6 +1225,9 @@ async fn setup_server_infrastructure_impl( } else { match spawn_browser_local_exit(&path, &local_exit_config) { Ok(child) => { + if name == "browser-local-exit" { + browser_exit_running = true; + } tracing::info!("{name} helper from {}", path.display()); managed_host_processes.push(api::server::HostHelperProcess { name, child }); } @@ -1244,6 +1248,7 @@ async fn setup_server_infrastructure_impl( let extra = elastos_server::setup::walletconnect::exit_config( existing_exit, walletconnect_exit.as_ref().map(|(_, provider)| provider), + browser_exit_running, ); let exit_config = provider::BridgeProviderConfig { extra, diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs index 1fbf9e3cf..a2e24cb35 100644 --- a/elastos/crates/elastos-server/src/setup/walletconnect.rs +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -27,6 +27,7 @@ pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, ser pub fn merge_exit_config( mut existing: serde_json::Value, walletconnect: Option<&serde_json::Value>, + browser_helper_running: bool, ) -> anyhow::Result { let Some(walletconnect) = walletconnect else { return Ok(existing); @@ -43,15 +44,20 @@ pub fn merge_exit_config( .as_array_mut() .ok_or_else(|| anyhow::anyhow!("Exit backends must be a list"))?; let managed = &walletconnect["backends"][0]; - if let Some(previous) = backends.iter().find(|b| b["id"] == managed["id"]) { + if let Some(index) = backends.iter().position(|b| b["id"] == managed["id"]) { anyhow::ensure!( - previous == managed, + &backends[index] == managed, "WalletConnect Exit backend has a conflicting route" ); - } else { - // Exit matches local backends in list order. Browser keeps first match; - // WalletConnect supplies a route only when earlier backends do not match. + backends.remove(index); + } + // Exit matches in list order. A running Browser helper keeps first match. + // Without it, the relay-only route precedes retained Browser wildcards; + // every other backend retains its order and its matching policy. + if browser_helper_running { backends.push(managed.clone()); + } else { + backends.insert(0, managed.clone()); } exit_provider::parse_config(existing.clone()).map_err(anyhow::Error::msg)?; Ok(existing) @@ -61,11 +67,12 @@ pub fn merge_exit_config( pub fn exit_config( existing: serde_json::Value, walletconnect: Option<&serde_json::Value>, + browser_helper_running: bool, ) -> serde_json::Value { - match merge_exit_config(existing.clone(), walletconnect) { + match merge_exit_config(existing.clone(), walletconnect, browser_helper_running) { Ok(config) => config, - Err(_) => { - tracing::warn!("WalletConnect Exit configuration was refused; starting the existing Exit configuration"); + Err(error) => { + tracing::warn!(%error, "WalletConnect Exit configuration was refused; starting the existing Exit configuration"); existing } } @@ -132,24 +139,27 @@ mod tests { fn walletconnect_keeps_existing_remote_and_local_exit_configuration() { let remote = serde_json::json!({"backends":[], "timeout_secs":12}); let wc = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"]}]}); - let merged = merge_exit_config(remote.clone(), Some(&wc)).unwrap(); + let merged = merge_exit_config(remote.clone(), Some(&wc), true).unwrap(); assert_eq!(merged["timeout_secs"], remote["timeout_secs"]); assert_eq!(merged["backends"], wc["backends"]); let local = serde_json::json!({"backends":[{"id":"owner-local", "kind":"stream_relay", "allowed_hosts":["*"]}]}); - let merged = merge_exit_config(local.clone(), Some(&wc)).unwrap(); + let merged = merge_exit_config(local.clone(), Some(&wc), true).unwrap(); assert_eq!(merged["backends"][0], local["backends"][0]); - assert_eq!(merge_exit_config(remote.clone(), None).unwrap(), remote); - assert!(merge_exit_config(serde_json::json!({"backends":false}), Some(&wc)).is_err()); + assert_eq!( + merge_exit_config(remote.clone(), None, true).unwrap(), + remote + ); + assert!(merge_exit_config(serde_json::json!({"backends":false}), Some(&wc), true).is_err()); } #[test] fn walletconnect_refused_merge_preserves_browser_exit_and_matching_order() { let browser = serde_json::json!({"backends":[{"id":"browser", "kind":"stream_relay", "allowed_hosts":["*"]}]}); let bad = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"], "adapter_ipc":{"kind":"unix_socket","path":"/tmp/same.sock"}, "relay_ipc":{"kind":"unix_socket","path":"/tmp/same.sock"}}]}); - assert!(merge_exit_config(browser.clone(), Some(&bad)).is_err()); - assert_eq!(exit_config(browser.clone(), Some(&bad)), browser); + assert!(merge_exit_config(browser.clone(), Some(&bad), true).is_err()); + assert_eq!(exit_config(browser.clone(), Some(&bad), true), browser); let good = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"]}]}); - let merged = exit_config(browser, Some(&good)); + let merged = exit_config(browser, Some(&good), true); let parsed = exit_provider::parse_config(merged).unwrap(); for host in [ "relay.walletconnect.org", @@ -168,4 +178,120 @@ mod tests { ); } } + + #[test] + fn retained_linux_browser_wildcard_uses_walletconnect_when_helper_is_stopped() { + let platform = "linux-amd64"; + assert!(!super::super::browser_available(platform)); + let data = tempfile::tempdir().unwrap(); + let browser = serde_json::json!({"backends":[{ + "id":"source-home-browser-exit", "kind":"stream_relay", + "allowed_hosts":["*"], "allowed_schemes":["tcp","tls"], + "allowed_ports":[80,443], + "adapter_ipc":{"kind":"unix_socket","path":super::super::browser_config::runtime_socket_path(data.path(), platform, "adapter")}, + "relay_ipc":{"kind":"unix_socket","path":super::super::browser_config::runtime_socket_path(data.path(), platform, "relay")} + }]}); + let wc = serde_json::json!({"backends":[{ + "id":"walletconnect-local-exit", "kind":"stream_relay", + "allowed_hosts":["relay.walletconnect.org","relay.walletconnect.com"], + "allowed_schemes":["tls"], "allowed_ports":[443], + "adapter_ipc":{"kind":"unix_socket","path":super::super::browser_config::runtime_socket_path(data.path(), platform, "wc-adapter")}, + "relay_ipc":{"kind":"unix_socket","path":super::super::browser_config::runtime_socket_path(data.path(), platform, "wc-relay")} + }]}); + for running in [false, true] { + let merged = merge_exit_config(browser.clone(), Some(&wc), running).unwrap(); + assert_eq!( + merged["backends"][usize::from(!running)], + browser["backends"][0] + ); + let parsed = exit_provider::parse_config(merged.clone()).unwrap(); + for (target, expected) in [ + ( + "tls://relay.walletconnect.org:443", + if running { + "source-home-browser-exit" + } else { + "walletconnect-local-exit" + }, + ), + ( + "tls://relay.walletconnect.com:443", + if running { + "source-home-browser-exit" + } else { + "walletconnect-local-exit" + }, + ), + ("tls://example.org:443", "source-home-browser-exit"), + ("tcp://example.org:80", "source-home-browser-exit"), + ( + "tcp://relay.walletconnect.org:443", + "source-home-browser-exit", + ), + ( + "tls://relay.walletconnect.org:80", + "source-home-browser-exit", + ), + ] { + let target = url::Url::parse(target).unwrap(); + assert_eq!( + parsed + .backends + .iter() + .find(|b| b.allows_target(&target)) + .unwrap() + .id, + expected + ); + } + // Restarting with the other helper state normalises the managed route once. + let reordered = merge_exit_config(merged, Some(&wc), !running).unwrap(); + assert_eq!(reordered["backends"].as_array().unwrap().len(), 2); + assert_eq!( + reordered["backends"][usize::from(running)], + browser["backends"][0] + ); + } + } + + #[test] + fn refused_merge_logs_parser_error_without_dumping_configuration() { + #[derive(Clone)] + struct Capture(std::sync::Arc>>); + impl std::io::Write for Capture { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let bytes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let writer = Capture(bytes.clone()); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(); + let existing = serde_json::json!({"backends":[]}); + let bad = serde_json::json!({"backends":[{ + "id":"walletconnect-local-exit", "kind":"stream_relay", + "allowed_hosts":["relay.walletconnect.org"], + "private_test_payload":"not-to-log" + }]}); + let error = merge_exit_config(existing.clone(), Some(&bad), false) + .unwrap_err() + .to_string(); + assert!(error.contains("unknown field")); + tracing::subscriber::with_default(subscriber, || { + assert_eq!(exit_config(existing.clone(), Some(&bad), false), existing); + }); + let output = String::from_utf8(bytes.lock().unwrap().clone()).unwrap(); + assert!(output.contains(&error), "parser refusal is logged"); + assert!( + !output.contains("not-to-log"), + "configuration values remain private" + ); + } } From 1cd1ecf7a0dd9b244beae6a2e9d55ab92f2c091e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 02:56:10 -0500 Subject: [PATCH 091/139] test(walletconnect): use release behavior proof instead of YAML text --- scripts/walletconnect-runtime.test.mjs | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/scripts/walletconnect-runtime.test.mjs b/scripts/walletconnect-runtime.test.mjs index bede02d45..eac5e2c58 100644 --- a/scripts/walletconnect-runtime.test.mjs +++ b/scripts/walletconnect-runtime.test.mjs @@ -135,18 +135,3 @@ test("release stage installs config automatically only from the operator file an assert.throws(() => execFileSync(process.execPath, [script, dir], { env, stdio: "pipe" }), /failed/); } finally { await rm(dir, { recursive: true, force: true }); } }); - -test("release project secret is scoped to the build step and passed only by file", async () => { - const workflow = await readFile(resolve(".github/workflows/release-package.yml"), "utf8"); - assert.doesNotMatch(workflow, /ELASTOS_WALLETCONNECT_PROJECT_ID/); - const steps = workflow.split(" - name:"); - const secretSteps = steps.filter(step => step.includes("secrets.REOWN_PROJECT_ID")); - assert.equal(secretSteps.length, 2); - for (const step of secretSteps) { - assert.match(step, /^ build N, then N\+1/); - assert.match(step, /os.fchmod\(f.fileno\(\),0o600\)/); - assert.match(step, /ELASTOS_WALLETCONNECT_PROJECT_FILE/); - assert.match(step, /unset REOWN_PROJECT_ID/); - assert.match(step, /trap .*EXIT/); - } -}); From 861a83ae4ea829a5673f350eb5fc466afdefbe45 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 02:58:50 -0500 Subject: [PATCH 092/139] fix(wallet): dismiss approved connector transactions and release slots --- capsules/wallet-provider/src/approval.rs | 10 ++- .../src/tests/approvals/transactions.rs | 83 ++++++++++++++++++- docs/WALLET_PROVIDER.md | 15 +++- 3 files changed, 100 insertions(+), 8 deletions(-) diff --git a/capsules/wallet-provider/src/approval.rs b/capsules/wallet-provider/src/approval.rs index dfa639f86..6415537a5 100644 --- a/capsules/wallet-provider/src/approval.rs +++ b/capsules/wallet-provider/src/approval.rs @@ -409,8 +409,14 @@ impl WalletProvider { "wallet approval request belongs to a different connector", ); } - if request.status != ApprovalStatus::Pending { - return Response::error("invalid_request", "wallet approval request is not pending"); + let approved_connector_transaction = request.status == ApprovalStatus::Approved + && request.intent == "transaction_intent" + && request.connector_id.is_some(); + if request.status != ApprovalStatus::Pending && !approved_connector_transaction { + return Response::error( + "invalid_request", + "wallet approval request cannot be rejected", + ); } request.status = ApprovalStatus::Rejected; request.resolved_at = Some(now); diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 7b9213500..0577c5c45 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -234,11 +234,18 @@ fn validated_chain_outcome_projection_is_exact_and_idempotent() { #[test] fn transaction_intent_validates_payload_and_allows_external_handoff() { for connector in ["wallet-metamask", "wallet-walletconnect"] { - external_transaction_handoff_with_expiry(connector); + external_transaction_handoff_with_expiry(connector, false); } } -fn external_transaction_handoff_with_expiry(connector: &str) { +#[test] +fn approved_connector_transaction_can_be_rejected_and_releases_its_slot() { + for connector in ["wallet-metamask", "wallet-walletconnect"] { + external_transaction_handoff_with_expiry(connector, true); + } +} + +fn external_transaction_handoff_with_expiry(connector: &str, dismiss: bool) { let dir = tempfile::tempdir().unwrap(); let mut provider = init_provider(dir.path()); let principal_id = "person:local:alice"; @@ -404,6 +411,78 @@ fn external_transaction_handoff_with_expiry(connector: &str) { ApprovalStatus::Approved ); } + if dismiss { + let reject = || WalletProviderOperationV2::RejectApproval { + request_id: request_id.clone(), + reason: "Dismiss abandoned send".into(), + }; + for context in [ + wallet_context_in_session(principal_id, "wallet", "session:other"), + wallet_context("person:local:bob", "wallet"), + wallet_context(principal_id, "wallet-unisat"), + ] { + assert!(matches!( + invoke_wallet_with_context(&mut provider, &context, reject()), + Response::Error { .. } + )); + } + // Fill the quota from an actual approved handoff; rejecting one must permit + // a new request through the provider's real admission path. + for index in 1..MAX_ACTIVE_APPROVAL_REQUESTS_PER_PRINCIPAL { + let mut other = approved.clone(); + other.request_id = format!("quota:{index}"); + provider.store.approval_requests.push(other); + } + let next = || WalletProviderOperationV2::RequestApproval { + account_id: external_account_id.clone(), + chain_namespace: "eip155:20".into(), + intent: "transaction_intent".into(), + resource: "elastos://chain/esc-mainnet/broadcast_transaction".into(), + reason: "Another transaction".into(), + payload: transaction_intent_payload(external_address), + expires_at: now_ts().saturating_add(APPROVAL_REQUEST_TTL_SECS), + }; + assert!( + matches!(invoke_wallet(&mut provider, principal_id, "system", next()), + Response::Error { ref code, .. } if code == "approval_limit_reached") + ); + let response = invoke_wallet(&mut provider, principal_id, "wallet", reject()); + assert!(matches!(response, Response::Ok { .. }), "{response:?}"); + let rejected = provider + .store + .approval_requests + .iter() + .find(|r| r.request_id == request_id) + .unwrap(); + assert_eq!(rejected.status, ApprovalStatus::Rejected); + assert!(!approval_authority_is_active(rejected, now_ts())); + assert!(matches!( + invoke_wallet(&mut provider, principal_id, "system", next()), + Response::Ok { .. } + )); + assert!(matches!( + invoke_wallet(&mut provider, principal_id, "wallet", reject()), + Response::Error { .. } + )); + assert!(matches!( + invoke_wallet( + &mut provider, + principal_id, + connector, + WalletProviderOperationV2::CompleteConnectorHandoff { + request_id, + payload_hash, + signature: None, + signature_type: None, + public_key: None, + signer: external_address.into(), + transaction_hash: Some(format!("0x{}", "a".repeat(64))), + } + ), + Response::Error { .. } + )); + return; + } let transaction_hash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; let context = wallet_context(principal_id, connector); let invalid_completion = wallet_request( diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index dd3c3dfc0..9c709e8c1 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -271,8 +271,10 @@ approved, unfinished transaction visible with "Check your phone wallet". Opening it again supplies recovery instructions and keeps the send control disabled. A returned transaction hash is passed to Runtime once even if the account, network or expiry changed during the phone prompt. An approved WalletConnect -transaction can complete once within 24 hours after expiry. An unfinished prompt -then expires and releases its approval slot; other connectors keep their normal TTL. +transaction can complete once within 24 hours after expiry, in the same Runtime +session. Reject dismisses an approved connector transaction and releases its +approval slot. It does not cancel a transaction on the phone wallet. An unfinished +prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; the hash alone does not prove that it matches the approved payload. A completion error keeps the @@ -302,8 +304,13 @@ admits only the opaque connector's single-use relay ticket, caps waiting sockets rechecks the launch and owner on each heartbeat and outbound frame, authenticates relay TLS, and limits frames and sockets. It reaches only `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through -a local Exit backend and its separate adapter and relay sockets. Existing Browser -backends keep first match. Runtime validates the merged configuration with +a local Exit backend and its separate adapter and relay sockets. When Browser's +local Exit helper starts successfully, Browser's existing backends keep first +match and its wildcard backend carries the relay. When that helper stays stopped +or fails to start, WalletConnect's own relay-only backend takes first match for +these two TLS hosts. Retained Browser backends keep their order and matching for +other traffic, including on older linux-amd64 Homes with a wildcard Browser config. +Runtime validates the merged configuration with exit-provider's parser and keeps the existing Exit configuration if the addition is refused. Turn Off cancels handshakes and open sockets. Hosted Carrier Exit selection remains a separate integration. From fd75fb0f691b51fb3b6753e48478b11072d5ff10 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 02:58:50 -0500 Subject: [PATCH 093/139] build(exit): keep HTTP client out of parser consumers --- capsules/exit-provider/Cargo.toml | 7 ++++++- elastos/Cargo.lock | 1 - elastos/crates/elastos-server/Cargo.toml | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/capsules/exit-provider/Cargo.toml b/capsules/exit-provider/Cargo.toml index a8c254305..afe603b50 100644 --- a/capsules/exit-provider/Cargo.toml +++ b/capsules/exit-provider/Cargo.toml @@ -8,11 +8,16 @@ license = "MIT" [[bin]] name = "exit-provider" path = "src/main.rs" +required-features = ["http"] + +[features] +default = ["http"] +http = ["dep:ureq"] [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -ureq = "2" +ureq = { version = "2", optional = true } url = "2" [dev-dependencies] diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index b4b987f46..4e69dc6cf 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -1912,7 +1912,6 @@ version = "0.1.0" dependencies = [ "serde", "serde_json", - "ureq", "url", ] diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index b91ef37a4..ba287c500 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -10,7 +10,7 @@ name = "elastos" path = "src/main.rs" [dependencies] -exit-provider = { path = "../../../capsules/exit-provider" } +exit-provider = { path = "../../../capsules/exit-provider", default-features = false } elastos-runtime = { path = "../elastos-runtime" } elastos-common = { path = "../elastos-common" } elastos-storage = { path = "../elastos-storage" } From 500b581d776092241864e7aa179b12a189e9caa9 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 02:59:04 -0500 Subject: [PATCH 094/139] test(walletconnect): exercise real WebKit relay ticket admission --- .../api/gateway_tests/wallet/walletconnect.rs | 19 ++++++++++++++++++- .../src/api/gateway_walletconnect.rs | 13 +++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index c69373271..1cfa3fa9f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -497,6 +497,7 @@ async fn walletconnect_refused_remote_exit_closes_its_reservation() { #[tokio::test] async fn walletconnect_webkit_fetch_metadata_upgrades_only_the_exact_ticketed_socket() { let f = Fixture::new().await; + f.allow().await; for dest in ["websocket", "empty", "document", "iframe", "script"] { for origin in ["null", "https://other.example"] { let mut request = format!("ws://{}/api/apps/wallet-walletconnect/relay", f.addr) @@ -514,9 +515,20 @@ async fn walletconnect_webkit_fetch_metadata_upgrades_only_the_exact_ticketed_so if origin == "null" && matches!(dest, "websocket" | "empty") { let (mut socket, response) = result.expect("WebKit connection upgrades"); assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS); + let (status, admission) = f + .route( + &f.connector, + "/api/apps/wallet-walletconnect/relay-admission", + Some(json!({})), + ) + .await; + assert_eq!(status, StatusCode::OK); + let ticket = admission["token"].as_str().unwrap(); + gateway_walletconnect::expire_admissions_for_test(&f.state).await; + assert!(gateway_walletconnect::admission_pending_for_test(&f.state, ticket).await); socket .send(Message::Text( - json!({"token":"refused","url":RELAY}).to_string(), + json!({"token":ticket,"relay":RELAY}).to_string(), )) .await .unwrap(); @@ -524,6 +536,11 @@ async fn walletconnect_webkit_fetch_metadata_upgrades_only_the_exact_ticketed_so socket.next().await, Some(Ok(Message::Close(_))) | None )); + assert!( + !gateway_walletconnect::admission_pending_for_test(&f.state, ticket).await, + "the real RelayHello reached and consumed its expired single-use ticket" + ); + assert_eq!(f.calls.load(Ordering::SeqCst), 0); } else { assert!( matches!(result, Err(tokio_tungstenite::tungstenite::Error::Http(ref response)) if response.status() == StatusCode::FORBIDDEN), diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 4098c264e..0c9cba295 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -442,6 +442,19 @@ pub(in crate::api::gateway) async fn expire_admissions_for_test(state: &GatewayS *expiry = 0; } } +#[cfg(test)] +pub(in crate::api::gateway) async fn admission_pending_for_test( + state: &GatewayState, + ticket: &str, +) -> bool { + state + .walletconnect + .inner + .lock() + .await + .admissions + .contains_key(ticket) +} pub(super) async fn admission(State(state): State, headers: HeaderMap) -> Response { let result = async { let authority = connector_authority(&state, &headers)?; From ae0d2b38909f4a7a8281213a66234fcb5c4b0a20 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 02:59:04 -0500 Subject: [PATCH 095/139] test(walletconnect): prove default installed connector availability --- .github/workflows/ci.yml | 16 +-- scripts/home-frontdoor-smoke.sh | 9 +- scripts/local-carrier-setup-smoke.sh | 11 +- .../walletconnect-installed-policy-smoke.mjs | 132 ++++++++++++++++++ 4 files changed, 155 insertions(+), 13 deletions(-) create mode 100644 scripts/walletconnect-installed-policy-smoke.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5dc79976..3587a3ccc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -905,14 +905,6 @@ jobs: scripts/setup-source-home.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/setup-source-home.log" ELASTOS_DATA_DIR="${XDG_DATA_HOME}/elastos" \ scripts/installed-provider-verify.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/installed-provider-verify.log" - - name: local-carrier setup smoke - env: - ELASTOS_LLAMA_AMD64_BUNDLE: ${{ runner.temp }}/llama-amd64-bundle/llama-b10516-bin-ubuntu22.04-amd64-cpu.tar.gz - ELASTOS_LLAMA_ARM64_BUNDLE: ${{ runner.temp }}/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz - run: | - set -euo pipefail - mkdir -p "${RUNNER_TEMP}/source-home-logs" - scripts/local-carrier-setup-smoke.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/local-carrier-setup-smoke.log" - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '24' @@ -926,6 +918,14 @@ jobs: - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '26' + - name: local-carrier setup smoke + env: + ELASTOS_LLAMA_AMD64_BUNDLE: ${{ runner.temp }}/llama-amd64-bundle/llama-b10516-bin-ubuntu22.04-amd64-cpu.tar.gz + ELASTOS_LLAMA_ARM64_BUNDLE: ${{ runner.temp }}/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/source-home-logs" + scripts/local-carrier-setup-smoke.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/local-carrier-setup-smoke.log" - name: prepare signed SmolLM2 fixture timeout-minutes: 20 env: diff --git a/scripts/home-frontdoor-smoke.sh b/scripts/home-frontdoor-smoke.sh index 84d577ea1..8fb39f669 100755 --- a/scripts/home-frontdoor-smoke.sh +++ b/scripts/home-frontdoor-smoke.sh @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail umask 077 +# This fixture proves the default unconfigured installation independently of operator inputs. +unset ELASTOS_WALLETCONNECT_PROJECT_FILE ELASTOS_WALLETCONNECT_PROJECT_ID + # This fixture owns setup, launch, and cleanup after bootstrap. export ELASTOS_INSTALL_ONLY=1 @@ -375,6 +378,7 @@ for installed in \ "$HOME_DIR/xdg-data/elastos/capsules/archive-manager/browser/index.html" \ "$HOME_DIR/xdg-data/elastos/capsules/wallet/browser/index.html" \ "$HOME_DIR/xdg-data/elastos/capsules/wallet-metamask/browser/index.html" \ + "$HOME_DIR/xdg-data/elastos/capsules/wallet-walletconnect/browser/index.html" \ "$HOME_DIR/xdg-data/elastos/capsules/wallet-unisat/browser/index.html" \ "$HOME_DIR/xdg-data/elastos/bin/net-provider" \ "$HOME_DIR/xdg-data/elastos/bin/chain-provider" \ @@ -389,10 +393,9 @@ do exit 1 fi done -# Hidden in 0.8.0: the Home profile leaves them out; `setup --with` adds them. +# Optional components are installed through `setup --with`. for absent in \ "$HOME_DIR/xdg-data/elastos/capsules/services" \ - "$HOME_DIR/xdg-data/elastos/capsules/wallet-walletconnect" \ "$HOME_DIR/xdg-data/elastos/capsules/elacity-player" \ "$HOME_DIR/xdg-data/elastos/bin/content-block-graph-provider" \ "$HOME_DIR/xdg-data/elastos/bin/media-provider" \ @@ -538,4 +541,6 @@ run_repeated_action_case() PY test -x "$INSTALLED_HOME_CLI_DIR/bin/home-cli" cmp "$HOME_CLI_RENDERER" "$INSTALLED_HOME_CLI_DIR/bin/home-cli" +node "${ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "$ROOT/elastos/target/debug/elastos" "$HOME_DIR/xdg-data/elastos" "$HOME_DIR" + echo "[home-frontdoor] OK" diff --git a/scripts/local-carrier-setup-smoke.sh b/scripts/local-carrier-setup-smoke.sh index d9edc9dc9..17660805f 100755 --- a/scripts/local-carrier-setup-smoke.sh +++ b/scripts/local-carrier-setup-smoke.sh @@ -5,6 +5,9 @@ set -euo pipefail # tree world-readable and setup fails with "Runtime data root must be # owner-only". umask 077 +# This fixture proves the default unconfigured installation independently of operator inputs. +unset ELASTOS_WALLETCONNECT_PROJECT_FILE ELASTOS_WALLETCONNECT_PROJECT_ID + REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" ELASTOS_ROOT="${REPO_ROOT}/elastos" @@ -619,6 +622,7 @@ for installed in \ "${DATA_DIR}/capsules/assistant/browser/index.html" \ "${DATA_DIR}/capsules/wallet/browser/index.html" \ "${DATA_DIR}/capsules/wallet-metamask/browser/index.html" \ + "${DATA_DIR}/capsules/wallet-walletconnect/browser/index.html" \ "${DATA_DIR}/capsules/wallet-unisat/browser/index.html" do if [[ ! -f "${installed}" ]]; then @@ -626,7 +630,7 @@ do exit 1 fi done -# Hidden in 0.8.0: the Home profile leaves them out; `setup --with` adds them. +# Optional components are installed through `setup --with`. for absent in \ "${DATA_DIR}/bin/content-block-graph-provider" \ "${DATA_DIR}/bin/media-provider" \ @@ -634,8 +638,7 @@ for absent in \ "${DATA_DIR}/bin/protected-content-decrypt-provider" \ "${DATA_DIR}/tools/media-tools" \ "${DATA_DIR}/capsules/services" \ - "${DATA_DIR}/capsules/elacity-player" \ - "${DATA_DIR}/capsules/wallet-walletconnect" + "${DATA_DIR}/capsules/elacity-player" do if [[ -e "${absent}" ]]; then echo "hidden component installed by the Home profile: ${absent}" >&2 @@ -667,6 +670,8 @@ grep -q "Home CLI /" "${HOME_OUT}" || { exit 1 } +node "${REPO_ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "${ELASTOS_BIN}" "${DATA_DIR}" "${TEST_ROOT}" + echo "[local-carrier-setup] OK" echo "[local-carrier-setup] temp data dir: ${DATA_DIR}" echo "[local-carrier-setup] runtime log: ${LOG_PATH}" diff --git a/scripts/walletconnect-installed-policy-smoke.mjs b/scripts/walletconnect-installed-policy-smoke.mjs new file mode 100644 index 000000000..c7322692e --- /dev/null +++ b/scripts/walletconnect-installed-policy-smoke.mjs @@ -0,0 +1,132 @@ +#!/usr/bin/env node +// Exercise default installation through the signed Home, Wallet and Marketplace APIs. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createWriteStream } from "node:fs"; +import { access, chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:net"; +import { dirname, join, resolve } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { importProductSmokePlaywright, productSmokeLaunchOptions } from "./product-smoke-browser.mjs"; + +const [binary, dataArgument, homeArgument] = process.argv.slice(2); +assert(binary && dataArgument && homeArgument, "runtime, isolated data and Home required"); +const data = resolve(dataArgument), home = resolve(homeArgument); +const capsule = join(data, "capsules/wallet-walletconnect"); +for (const file of ["capsule.json", "browser/index.html", "vendor/adapter.json", "vendor/reown-appkit.js"]) { + await access(join(capsule, file)); +} +const config = join(data, "ElastOS/SystemServices/WalletConnect/config.json"); +await assert.rejects(access(config), { code: "ENOENT" }, "default Home has no operator project"); +await assert.rejects(access(join(capsule, "vendor/connector.json")), { code: "ENOENT" }); +const listener = createServer(); +await new Promise(resolve => listener.listen(0, "127.0.0.1", resolve)); +const port = listener.address().port; +await new Promise(resolve => listener.close(resolve)); +const base = `http://localhost:${port}`; +const env = { ...process.env, HOME: home, XDG_DATA_HOME: dirname(data), ELASTOS_DATA_DIR: data, + ELASTOS_COLLABORATION_STARTUP_MODE: "isolated" }; +delete env.ELASTOS_WALLETCONNECT_PROJECT_FILE; +delete env.ELASTOS_WALLETCONNECT_PROJECT_ID; +const log = createWriteStream(join(home, "walletconnect-installed-policy.log"), { mode: 0o600 }); +const runtime = spawn(binary, ["serve", "--addr", `127.0.0.1:${port}`], { env, stdio: ["ignore", log, log] }); +const stopped = new Promise(resolve => runtime.once("exit", resolve)); +let browser; +const project = join(home, "walletconnect-test-project"); +try { + const deadline = Date.now() + 60000; + for (;;) { + assert(runtime.exitCode === null, "owned Runtime remains running"); + try { if ((await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(1000) })).ok) break; } catch {} + assert(Date.now() < deadline, "owned Runtime reaches health readiness"); + await delay(100); + } + const { chromium } = await importProductSmokePlaywright(); + browser = await chromium.launch({ headless: true, ...productSmokeLaunchOptions() }); + const context = await browser.newContext(); + const page = await context.newPage(); + let homeToken; + page.on("request", request => { + if (request.frame() === page.mainFrame() && new URL(request.url()).pathname === "/api/apps/home/launch") { + homeToken = request.headers()["x-elastos-home-token"]; + } + }); + const cdp = await context.newCDPSession(page); + await cdp.send("WebAuthn.enable"); + await cdp.send("WebAuthn.addVirtualAuthenticator", { options: { + protocol: "ctap2", transport: "internal", hasResidentKey: true, + hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true, + } }); + assert((await page.goto(`${base}/home/`)).ok()); + await page.locator("#home-unlock-name").fill("Connector install fixture"); + const registered = page.waitForResponse(response => response.url().endsWith("/api/auth/passkey/register/complete")); + await page.locator("#home-unlock-primary").click(); + assert((await registered).ok(), "isolated owner registers through Home"); + await page.frameLocator("#active-shell-frame").locator("#desktop").waitFor({ state: "visible", timeout: 60000 }); + assert(homeToken, "Home carries its signed launch authority"); + async function api(path, token, body, frame = page) { + return frame.evaluate(async ({ path, token, body }) => { + const response = await fetch(path, { + method: body ? "POST" : "GET", + headers: { "content-type": "application/json", "x-elastos-home-token": token }, + body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(30000), + }); + return { status: response.status, body: await response.json() }; + }, { path, token, body }); + } + async function launch(target) { + return api("/api/apps/home/launch", homeToken, { target, query: { home_origin: base } }); + } + async function appToken(target) { + const response = await launch(target); + assert.equal(response.status, 200, `${target} launches`); + const token = new URLSearchParams(new URL(response.body.route, base).hash.slice(1)).get("home_token"); + assert(token, `${target} has capsule authority`); + // Capsules own opaque origins. Fetch their projections from a real sandboxed + // frame with the route and authority returned by Home's launch surface. + await page.evaluate(({ route, target }) => { + const iframe = document.createElement("iframe"); + iframe.id = `installed-policy-${target}`; + iframe.sandbox = "allow-scripts allow-forms"; + iframe.src = route; + document.body.append(iframe); + }, { route: response.body.route, target }); + const frame = await (await page.locator(`#installed-policy-${target}`).elementHandle()).contentFrame(); + await frame.waitForURL(url => url.pathname.startsWith(`/apps/${target}/`)); + return { token, frame }; + } + const wallet = await appToken("wallet"), marketplace = await appToken("marketplace"); + async function policy(configured) { + const summary = await api("/api/apps/wallet/wallet/summary", wallet.token, undefined, wallet.frame); + assert.equal(summary.status, 200, "Wallet summary responds"); + assert.equal(summary.body.approval_methods.walletconnect.available, configured, "Wallet offers only configured connector"); + const catalog = await api("/api/capsules/catalog", marketplace.token, undefined, marketplace.frame); + assert.equal(catalog.status, 200, "Marketplace catalog responds"); + const row = catalog.body.capsules.find(row => row.name === "wallet-walletconnect"); + assert.equal(Boolean(row?.launchable), configured, "Marketplace offers only configured connector"); + if (!configured) assert.equal(row, undefined, "unconfigured connector stays hidden"); + const launched = await launch("wallet-walletconnect"); + assert.equal(launched.status === 200, configured, "Home launches only configured connector"); + if (!configured) assert(launched.status >= 400 && launched.status < 500, "Home refuses unconfigured launch"); + } + await policy(false); + // A disposable project file exercises operator configuration without relay access. + await writeFile(project, "installed-policy-fixture", { flag: "wx", mode: 0o600 }); + const adapter = JSON.parse(await readFile(join(capsule, "vendor/adapter.json"), "utf8")); + assert.equal(adapter.sdk_sha256, createHash("sha256").update(await readFile(join(capsule, "vendor/reown-appkit.js"))).digest("hex")); + await mkdir(dirname(config), { recursive: true, mode: 0o700 }); + await chmod(dirname(config), 0o700); + await writeFile(config, JSON.stringify({ schema: "elastos.walletconnect.connector/v1", + project_id: (await readFile(project, "utf8")).trim(), sdk_package: adapter.sdk_package, + sdk_version: adapter.sdk_version, sdk_sha256: adapter.sdk_sha256 }), { flag: "wx", mode: 0o600 }); + await policy(true); + console.log("WalletConnect installed policy PASS: installed; unconfigured hidden and refused; configured offered and launchable"); +} finally { + await browser?.close(); + runtime.kill("SIGTERM"); + const timeout = setTimeout(() => runtime.kill("SIGKILL"), 10000); + await stopped; clearTimeout(timeout); log.end(); + await rm(project, { force: true }); + await rm(config, { force: true }); +} From 12a66b08ad4dd9f693f32f7b54b5fdd86a6bff16 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:01:01 -0500 Subject: [PATCH 096/139] test(walletconnect): bind installed proof to its setup manifest --- scripts/walletconnect-installed-policy-smoke.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/walletconnect-installed-policy-smoke.mjs b/scripts/walletconnect-installed-policy-smoke.mjs index c7322692e..c636d2347 100644 --- a/scripts/walletconnect-installed-policy-smoke.mjs +++ b/scripts/walletconnect-installed-policy-smoke.mjs @@ -26,7 +26,8 @@ const port = listener.address().port; await new Promise(resolve => listener.close(resolve)); const base = `http://localhost:${port}`; const env = { ...process.env, HOME: home, XDG_DATA_HOME: dirname(data), ELASTOS_DATA_DIR: data, - ELASTOS_COLLABORATION_STARTUP_MODE: "isolated" }; + ELASTOS_COLLABORATION_STARTUP_MODE: "isolated", + ELASTOS_COMPONENTS_MANIFEST: join(data, "components.json") }; delete env.ELASTOS_WALLETCONNECT_PROJECT_FILE; delete env.ELASTOS_WALLETCONNECT_PROJECT_ID; const log = createWriteStream(join(home, "walletconnect-installed-policy.log"), { mode: 0o600 }); From e68e44f0087251b4a7c333b6a2743c8765467328 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:08:28 -0500 Subject: [PATCH 097/139] test(walletconnect): open owned Runtime log before spawning --- scripts/walletconnect-installed-policy-smoke.mjs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/scripts/walletconnect-installed-policy-smoke.mjs b/scripts/walletconnect-installed-policy-smoke.mjs index c636d2347..5e22d3267 100644 --- a/scripts/walletconnect-installed-policy-smoke.mjs +++ b/scripts/walletconnect-installed-policy-smoke.mjs @@ -3,8 +3,7 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; -import { createWriteStream } from "node:fs"; -import { access, chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { access, chmod, mkdir, open, readFile, rm, writeFile } from "node:fs/promises"; import { createServer } from "node:net"; import { dirname, join, resolve } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; @@ -30,8 +29,8 @@ const env = { ...process.env, HOME: home, XDG_DATA_HOME: dirname(data), ELASTOS_ ELASTOS_COMPONENTS_MANIFEST: join(data, "components.json") }; delete env.ELASTOS_WALLETCONNECT_PROJECT_FILE; delete env.ELASTOS_WALLETCONNECT_PROJECT_ID; -const log = createWriteStream(join(home, "walletconnect-installed-policy.log"), { mode: 0o600 }); -const runtime = spawn(binary, ["serve", "--addr", `127.0.0.1:${port}`], { env, stdio: ["ignore", log, log] }); +const log = await open(join(home, "walletconnect-installed-policy.log"), "w", 0o600); +const runtime = spawn(binary, ["serve", "--addr", `127.0.0.1:${port}`], { env, stdio: ["ignore", log.fd, log.fd] }); const stopped = new Promise(resolve => runtime.once("exit", resolve)); let browser; const project = join(home, "walletconnect-test-project"); @@ -127,7 +126,7 @@ try { await browser?.close(); runtime.kill("SIGTERM"); const timeout = setTimeout(() => runtime.kill("SIGKILL"), 10000); - await stopped; clearTimeout(timeout); log.end(); + await stopped; clearTimeout(timeout); await log.close(); await rm(project, { force: true }); await rm(config, { force: true }); } From 09c58bf0c5a2e50c9e7e1361c1b29686014c3987 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:13:53 -0500 Subject: [PATCH 098/139] fix(wallet): expose Reject for unfinished connector sends --- capsules/wallet/browser/wallet-activity.js | 9 +++- capsules/wallet/browser/wallet-requests.js | 16 ++++-- docs/WALLET_PROVIDER.md | 4 +- scripts/wallet-approved-dismissal.test.mjs | 63 ++++++++++++++++++++++ scripts/wallet-product-layout-smoke.mjs | 25 +++++++++ 5 files changed, 111 insertions(+), 6 deletions(-) create mode 100644 scripts/wallet-approved-dismissal.test.mjs diff --git a/capsules/wallet/browser/wallet-activity.js b/capsules/wallet/browser/wallet-activity.js index 753ff555b..94a2cd920 100644 --- a/capsules/wallet/browser/wallet-activity.js +++ b/capsules/wallet/browser/wallet-activity.js @@ -26,7 +26,11 @@ export function createWalletActivity({ activityNode, textNode }) { } export function pendingRequests(requests) { - return requests.filter((request) => readText(request.status) === "pending"); + // An approved connector send still needs its receipt or explicit dismissal. + return requests.filter((request) => readText(request.status) === "pending" + || (readText(request.status) === "approved" + && readText(request.intent) === "transaction_intent" + && Boolean(readText(request.connector_id)))); } export function activityTime(request) { @@ -50,6 +54,9 @@ export function activityTitle(request) { return `${capsule} · Approved ${requestTitle(request)}`; } if (status === "rejected") { + if (request.intent === "transaction_intent" && readText(request.connector_id)) { + return `${capsule} · Dismissed transaction request`; + } return `${capsule} · Rejected ${requestTitle(request)}`; } if (status === "expired") { diff --git a/capsules/wallet/browser/wallet-requests.js b/capsules/wallet/browser/wallet-requests.js index 27a41510f..843941c36 100644 --- a/capsules/wallet/browser/wallet-requests.js +++ b/capsules/wallet/browser/wallet-requests.js @@ -45,6 +45,7 @@ export function createWalletRequests({ function requestCard(request, focused = false) { const requestId = readText(request.request_id); + const approvedTransaction = request.status === "approved" && request.intent === "transaction_intent"; const accountAccess = readText(request.intent) === "browser_account_access"; const accountAccessReview = accountAccess ? requestAccountAccessReview(request.review) : null; const card = document.createElement("article"); @@ -62,12 +63,17 @@ export function createWalletRequests({ if (accountAccessReview) { main.append(accountAccessReview); } + if (approvedTransaction) { + main.append(textNode("small", "Check your connected wallet before sending again. Reject dismisses this request; it does not cancel a transaction in your wallet.")); + } card.append(main); const actions = document.createElement("div"); actions.className = "wallet-request-actions"; const connectorId = readText(request.connector_id); - if (isManagedRequest(request) && (!accountAccess || accountAccessReview)) { + if (approvedTransaction) { + // Keep an unfinished external send visible without offering another handoff. + } else if (isManagedRequest(request) && (!accountAccess || accountAccessReview)) { const approve = actionButton( accountAccess ? "Allow" : "Approve", "walletRequestManagedApprove", @@ -80,7 +86,9 @@ export function createWalletRequests({ } else if (connectorId === "wallet-metamask") { actions.append(actionButton("Open MetaMask", "walletOpenMethod", connectorId)); } - actions.append(actionButton("Reject", "walletRequestReject", requestId, true)); + const reject = actionButton("Reject", "walletRequestReject", requestId, true); + if (approvedTransaction) reject.dataset.walletApprovedTransaction = "true"; + actions.append(reject); card.append(actions); return card; } @@ -180,7 +188,9 @@ export function createWalletRequests({ headers: shellHeaders({ "content-type": "application/json" }), body: JSON.stringify({ reason: "Rejected in Wallet" }), }); - showStatus("Request rejected.", "success"); + showStatus(button.dataset.walletApprovedTransaction === "true" + ? "Request dismissed. Check your connected wallet before sending again." + : "Request rejected.", "success"); notifyHomeSummaryChanged(); await refreshWalletState(); } catch (error) { diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 9c709e8c1..2b60b541e 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -272,8 +272,8 @@ it again supplies recovery instructions and keeps the send control disabled. A returned transaction hash is passed to Runtime once even if the account, network or expiry changed during the phone prompt. An approved WalletConnect transaction can complete once within 24 hours after expiry, in the same Runtime -session. Reject dismisses an approved connector transaction and releases its -approval slot. It does not cancel a transaction on the phone wallet. An unfinished +session. Wallet keeps an approved connector transaction in its request list. +Reject dismisses it and releases its approval slot. It does not cancel a transaction on the phone wallet. An unfinished prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs new file mode 100644 index 000000000..476ad2130 --- /dev/null +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -0,0 +1,63 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createWalletRequests } from "../capsules/wallet/browser/wallet-requests.js"; +import { activityTitle } from "../capsules/wallet/browser/wallet-activity.js"; + +class Element { + children = []; dataset = {}; hidden = false; textContent = ""; + classList = { toggle() {} }; + constructor(tagName) { this.tagName = tagName; } + append(...children) { this.children.push(...children); } + replaceChildren(...children) { this.children = children; } + closest(selector) { + return selector === "[data-wallet-request-reject]" && this.dataset.walletRequestReject ? this : null; + } +} +const descendants = node => [node, ...node.children.flatMap(descendants)]; + +test("Wallet exposes and dismisses approved connector sends without another approval", async t => { + const previous = globalThis.document; + globalThis.document = { createElement: tag => new Element(tag) }; + t.after(() => { globalThis.document = previous; }); + for (const connector of ["wallet-walletconnect", "wallet-metamask"]) { + let request = { request_id: "approval:abandoned", status: "approved", intent: "transaction_intent", + connector_id: connector, capsule_id: "browser", address: `0x${"12".repeat(20)}`, + created_at: 1, expires_at: 2, reason: "Send transaction" }; + const root = new Element("section"), panel = new Element("section"), calls = [], messages = []; + let refuse = true; + const requests = createWalletRequests({ requestsNode: root, requestsPanelNode: panel, + shellHeaders: headers => ({ ...headers, "x-elastos-home-token": "fixture-wallet-token" }), + fetchJson: async (path, input) => { + calls.push({ path, input }); + if (refuse) throw new Error("Runtime refused dismissal"); + request = { ...request, status: "rejected" }; + }, + notifyHomeSummaryChanged() {}, + openApprovalMethod() { assert.fail("dismissal opens no signer"); }, + requestPasskeyStepUp() { assert.fail("dismissal grants no new approval"); }, + showStatus: message => messages.push(message), + refreshWalletState: async () => requests.renderRequests(requests.pendingWalletRequests([request])), + }); + assert.deepEqual(requests.pendingWalletRequests([request]), [request], "an approved send remains actionable after its TTL"); + for (const other of [ + { ...request, status: "completed" }, { ...request, status: "rejected" }, + { ...request, intent: "browser_personal_sign" }, { ...request, connector_id: null }, + ]) assert.deepEqual(requests.pendingWalletRequests([other]), []); + requests.renderRequests(requests.pendingWalletRequests([request])); + const buttons = descendants(root).filter(node => node.tagName === "button"); + assert.deepEqual(buttons.map(button => button.textContent), ["Reject"], "approved sends offer dismissal without another send"); + assert(descendants(root).some(node => node.textContent.includes("does not cancel"))); + await requests.onRequestClick({ target: buttons[0] }); + assert.equal(root.children.length, 1, "a refused dismissal keeps its recovery card"); + assert.equal(buttons[0].disabled, false); + refuse = false; + await requests.onRequestClick({ target: buttons[0] }); + assert.equal(calls.length, 2); + assert.equal(calls[1].path, "/api/apps/wallet/wallet/approvals/approval%3Aabandoned/reject"); + assert.equal(calls[1].input.method, "POST"); + assert.equal(root.children.length, 0, "successful refresh removes the dismissed request"); + assert.equal(panel.hidden, true); + assert(messages.some(message => message.startsWith("Request dismissed."))); + assert.match(activityTitle(request), /Dismissed transaction request/); + } +}); diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 377e10e56..dd114756f 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -67,6 +67,7 @@ function defaultState() { balanceCalls: [], qrCalls: [], sendBodies: [], + rejectBodies: [], defaultBodies: [], renameBodies: [], deleteBodies: [], @@ -337,6 +338,13 @@ async function startServer() { json(response, 200, summaryResponse(state)); return; } + if (url.pathname === "/api/apps/wallet/wallet/approvals/approved-send/reject" && request.method === "POST") { + assert(request.headers["x-elastos-home-token"] === "wallet-home-token", "dismissal carries Wallet authority"); + state.rejectBodies.push(await readBody(request)); + state.approvals[0].status = "rejected"; + json(response, 200, { approval_requests: state.approvals }); + return; + } if (url.pathname === "/api/wallet/prices" && request.method === "GET") { state.priceCalls += 1; json(response, 200, { @@ -855,6 +863,23 @@ async function run() { })); assert(railState.presentation === "rail" && railState.heroNavHidden, "Rail mode must keep the reviewed Wallet rail presentation."); await assertNoErrors(railPage, server, "rail"); + server.state.approvals = [{ ...railFixtureState.approvals[0], request_id: "approved-send", + status: "approved", intent: "transaction_intent", connector_id: "wallet-walletconnect", + expires_at: Math.floor(Date.now() / 1000) - 1 }]; + await railPage.reload({ waitUntil: "networkidle" }); + const dismissFrame = await walletFrame(railPage); + await dismissFrame.locator(".wallet-account").waitFor({ state: "visible" }); + await dismissFrame.locator("#wallet-activity-open").click(); + const approvedCard = dismissFrame.locator('[data-wallet-request-id="approved-send"]'); + await approvedCard.waitFor({ state: "visible" }); + assert((await approvedCard.textContent()).includes("does not cancel"), "dismissal explains ownership of the wallet transaction"); + assert(await approvedCard.getByRole("button").count() === 1, "approved send offers Reject without another approval"); + await approvedCard.getByRole("button", { name: "Reject", exact: true }).click(); + await approvedCard.waitFor({ state: "detached" }); + assert(server.state.rejectBodies.length === 1, "one dismissal reaches Runtime"); + assert((await dismissFrame.locator("#wallet-status").textContent()).startsWith("Request dismissed."), "person sees dismissal confirmation"); + await assertNoErrors(railPage, server, "dismissal"); + console.log("Wallet approved-send dismissal PASS: visible recovery card, Reject, one Runtime request, removed after refresh"); await railPage.close(); console.log(`wallet-product-layout-smoke: OK\n${desktopShot}\n${narrowShot}`); From 09a330f0a99700ec6d81899ddef7dd9aa9b00f05 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:16:09 -0500 Subject: [PATCH 099/139] build(object): sync parser-only Exit dependency lock --- capsules/object-provider/Cargo.lock | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/capsules/object-provider/Cargo.lock b/capsules/object-provider/Cargo.lock index b5adb3daf..61f24b140 100644 --- a/capsules/object-provider/Cargo.lock +++ b/capsules/object-provider/Cargo.lock @@ -1837,7 +1837,6 @@ version = "0.1.0" dependencies = [ "serde", "serde_json", - "ureq", "url", ] @@ -5811,22 +5810,6 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" -[[package]] -name = "ureq" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" -dependencies = [ - "base64", - "flate2", - "log", - "once_cell", - "rustls", - "rustls-pki-types", - "url", - "webpki-roots 0.26.11", -] - [[package]] name = "url" version = "2.5.8" From a88027a7e6794e17eff2b69ceefa20a6de62b065 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:17:36 -0500 Subject: [PATCH 100/139] test(wallet): exercise dismissal through visible Activity control --- scripts/wallet-product-layout-smoke.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index dd114756f..588b5a1a0 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -866,7 +866,7 @@ async function run() { server.state.approvals = [{ ...railFixtureState.approvals[0], request_id: "approved-send", status: "approved", intent: "transaction_intent", connector_id: "wallet-walletconnect", expires_at: Math.floor(Date.now() / 1000) - 1 }]; - await railPage.reload({ waitUntil: "networkidle" }); + await railPage.goto(`${server.baseUrl}/fixture-host.html?mode=window`, { waitUntil: "networkidle" }); const dismissFrame = await walletFrame(railPage); await dismissFrame.locator(".wallet-account").waitFor({ state: "visible" }); await dismissFrame.locator("#wallet-activity-open").click(); From e17488af74717df7855a5a8d6bacc99cdcbb5797 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:39:25 -0500 Subject: [PATCH 101/139] test(walletconnect): include pinned SDK in install smoke archives --- scripts/home-frontdoor-smoke.sh | 3 +++ scripts/local-carrier-setup-smoke.sh | 3 +++ 2 files changed, 6 insertions(+) diff --git a/scripts/home-frontdoor-smoke.sh b/scripts/home-frontdoor-smoke.sh index 8fb39f669..600e72bc1 100755 --- a/scripts/home-frontdoor-smoke.sh +++ b/scripts/home-frontdoor-smoke.sh @@ -271,6 +271,9 @@ def write_capsule_archive(name, capsule_dir): browser_dir = capsule_dir / "browser" if browser_dir.is_dir(): tar.add(browser_dir, arcname=f"{name}/browser") + if name == "wallet-walletconnect": + # Match the release capsule: its pinned SDK lives beside browser/. + tar.add(capsule_dir / "vendor", arcname=f"{name}/vendor") if name == "home-cli": renderer = pathlib.Path(os.environ["HOME_CLI_RENDERER"]) if not renderer.is_file() or renderer.is_symlink() or not os.access(renderer, os.X_OK): diff --git a/scripts/local-carrier-setup-smoke.sh b/scripts/local-carrier-setup-smoke.sh index 17660805f..2b5d94fd6 100755 --- a/scripts/local-carrier-setup-smoke.sh +++ b/scripts/local-carrier-setup-smoke.sh @@ -372,6 +372,9 @@ def write_capsule_archive(name, capsule_dir): browser_dir = capsule_dir / "browser" if browser_dir.is_dir(): tar.add(browser_dir, arcname=f"{name}/browser") + if name == "wallet-walletconnect": + # Match the release capsule: its pinned SDK lives beside browser/. + tar.add(capsule_dir / "vendor", arcname=f"{name}/vendor") if name == "home-cli": renderer = pathlib.Path(os.environ["HOME_CLI_RENDERER"]) if not renderer.is_file() or renderer.is_symlink() or not os.access(renderer, os.X_OK): From 76979dc6ed0bf08cf52c0f8d815aead11e14a5be Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:40:59 -0500 Subject: [PATCH 102/139] test(wallet): cover dismissal after a replacement Runtime session --- .../src/tests/approvals/transactions.rs | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 0577c5c45..503e756ee 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -234,18 +234,20 @@ fn validated_chain_outcome_projection_is_exact_and_idempotent() { #[test] fn transaction_intent_validates_payload_and_allows_external_handoff() { for connector in ["wallet-metamask", "wallet-walletconnect"] { - external_transaction_handoff_with_expiry(connector, false); + external_transaction_handoff_with_expiry(connector, None); } } #[test] fn approved_connector_transaction_can_be_rejected_and_releases_its_slot() { - for connector in ["wallet-metamask", "wallet-walletconnect"] { - external_transaction_handoff_with_expiry(connector, true); + for actor in ["wallet", "system", "inbox"] { + for connector in ["wallet-metamask", "wallet-walletconnect"] { + external_transaction_handoff_with_expiry(connector, Some(actor)); + } } } -fn external_transaction_handoff_with_expiry(connector: &str, dismiss: bool) { +fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Option<&str>) { let dir = tempfile::tempdir().unwrap(); let mut provider = init_provider(dir.path()); let principal_id = "person:local:alice"; @@ -345,6 +347,13 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss: bool) { } other => panic!("expected external transaction approval request, got {other:?}"), }; + if let Some(actor) = dismiss_actor { + let context = wallet_context_in_session(principal_id, actor, "session:replacement"); + assert!(matches!(invoke_wallet_with_context(&mut provider, &context, + WalletProviderOperationV2::RejectApproval { + request_id: request_id.clone(), reason: "Pending request in another session".into(), + }), Response::Error { .. }), "pending requests keep their original session binding"); + } let transaction = match invoke_wallet( &mut provider, principal_id, @@ -411,13 +420,14 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss: bool) { ApprovalStatus::Approved ); } - if dismiss { + if let Some(actor) = dismiss_actor { let reject = || WalletProviderOperationV2::RejectApproval { request_id: request_id.clone(), reason: "Dismiss abandoned send".into(), }; for context in [ - wallet_context_in_session(principal_id, "wallet", "session:other"), + wallet_context_in_session(principal_id, connector, "session:replacement"), + wallet_context_in_session(principal_id, "browser", "session:replacement"), wallet_context("person:local:bob", "wallet"), wallet_context(principal_id, "wallet-unisat"), ] { @@ -426,6 +436,13 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss: bool) { Response::Error { .. } )); } + let connector_context = wallet_context_in_session(principal_id, connector, "session:replacement"); + assert!(matches!(invoke_wallet_with_context(&mut provider, &connector_context, + WalletProviderOperationV2::CompleteConnectorHandoff { + request_id: request_id.clone(), payload_hash: payload_hash.clone(), + signature: None, signature_type: None, public_key: None, + signer: external_address.into(), transaction_hash: Some(format!("0x{}", "a".repeat(64))), + }), Response::Error { .. }), "completion keeps its original session binding"); // Fill the quota from an actual approved handoff; rejecting one must permit // a new request through the provider's real admission path. for index in 1..MAX_ACTIVE_APPROVAL_REQUESTS_PER_PRINCIPAL { @@ -446,7 +463,8 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss: bool) { matches!(invoke_wallet(&mut provider, principal_id, "system", next()), Response::Error { ref code, .. } if code == "approval_limit_reached") ); - let response = invoke_wallet(&mut provider, principal_id, "wallet", reject()); + let context = wallet_context_in_session(principal_id, actor, "session:replacement"); + let response = invoke_wallet_with_context(&mut provider, &context, reject()); assert!(matches!(response, Response::Ok { .. }), "{response:?}"); let rejected = provider .store From 17e2c8a3078281ad4c8bcdc9034ef60f5fee1382 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:43:40 -0500 Subject: [PATCH 103/139] fix(wallet): dismiss owned approved sends after signing in again --- capsules/wallet-provider/src/approval.rs | 12 +++-- .../src/tests/approvals/transactions.rs | 46 ++++++++++++++----- docs/WALLET_PROVIDER.md | 4 +- 3 files changed, 46 insertions(+), 16 deletions(-) diff --git a/capsules/wallet-provider/src/approval.rs b/capsules/wallet-provider/src/approval.rs index 6415537a5..cfc7fd09e 100644 --- a/capsules/wallet-provider/src/approval.rs +++ b/capsules/wallet-provider/src/approval.rs @@ -397,7 +397,14 @@ impl WalletProvider { }) else { return Response::error("not_found", "wallet approval request not found"); }; - if request.session_id != session_id { + let approved_connector_transaction = request.status == ApprovalStatus::Approved + && request.intent == "transaction_intent" + && request.connector_id.is_some(); + // Dismissal grants no signing authority. The request's person may clear + // an approved external send from an owner surface after signing in again. + let owner_dismissal = + approved_connector_transaction && matches!(actor, "wallet" | "system" | "inbox"); + if request.session_id != session_id && !owner_dismissal { return Response::error( "invalid_request", "wallet approval request belongs to a different Runtime session", @@ -409,9 +416,6 @@ impl WalletProvider { "wallet approval request belongs to a different connector", ); } - let approved_connector_transaction = request.status == ApprovalStatus::Approved - && request.intent == "transaction_intent" - && request.connector_id.is_some(); if request.status != ApprovalStatus::Pending && !approved_connector_transaction { return Response::error( "invalid_request", diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 503e756ee..330e63b3b 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -349,10 +349,20 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Opti }; if let Some(actor) = dismiss_actor { let context = wallet_context_in_session(principal_id, actor, "session:replacement"); - assert!(matches!(invoke_wallet_with_context(&mut provider, &context, - WalletProviderOperationV2::RejectApproval { - request_id: request_id.clone(), reason: "Pending request in another session".into(), - }), Response::Error { .. }), "pending requests keep their original session binding"); + assert!( + matches!( + invoke_wallet_with_context( + &mut provider, + &context, + WalletProviderOperationV2::RejectApproval { + request_id: request_id.clone(), + reason: "Pending request in another session".into(), + } + ), + Response::Error { .. } + ), + "pending requests keep their original session binding" + ); } let transaction = match invoke_wallet( &mut provider, @@ -436,13 +446,27 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Opti Response::Error { .. } )); } - let connector_context = wallet_context_in_session(principal_id, connector, "session:replacement"); - assert!(matches!(invoke_wallet_with_context(&mut provider, &connector_context, - WalletProviderOperationV2::CompleteConnectorHandoff { - request_id: request_id.clone(), payload_hash: payload_hash.clone(), - signature: None, signature_type: None, public_key: None, - signer: external_address.into(), transaction_hash: Some(format!("0x{}", "a".repeat(64))), - }), Response::Error { .. }), "completion keeps its original session binding"); + let connector_context = + wallet_context_in_session(principal_id, connector, "session:replacement"); + assert!( + matches!( + invoke_wallet_with_context( + &mut provider, + &connector_context, + WalletProviderOperationV2::CompleteConnectorHandoff { + request_id: request_id.clone(), + payload_hash: payload_hash.clone(), + signature: None, + signature_type: None, + public_key: None, + signer: external_address.into(), + transaction_hash: Some(format!("0x{}", "a".repeat(64))), + } + ), + Response::Error { .. } + ), + "completion keeps its original session binding" + ); // Fill the quota from an actual approved handoff; rejecting one must permit // a new request through the provider's real admission path. for index in 1..MAX_ACTIVE_APPROVAL_REQUESTS_PER_PRINCIPAL { diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 2b60b541e..cf0723ebc 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -273,7 +273,9 @@ A returned transaction hash is passed to Runtime once even if the account, network or expiry changed during the phone prompt. An approved WalletConnect transaction can complete once within 24 hours after expiry, in the same Runtime session. Wallet keeps an approved connector transaction in its request list. -Reject dismisses it and releases its approval slot. It does not cancel a transaction on the phone wallet. An unfinished +Its owner can use Reject in Wallet, System or Inbox to dismiss it in a later +Runtime session and release its approval slot. Connector calls and completion +keep their original session binding. Reject does not cancel a phone transaction. An unfinished prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; From ca4c8e103abceec1ad79e224eee30e57e26451ba Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 03:45:07 -0500 Subject: [PATCH 104/139] test(wallet): show earlier-session sends with current launch authority --- scripts/wallet-approved-dismissal.test.mjs | 10 +++++++--- scripts/wallet-product-layout-smoke.mjs | 3 ++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs index 476ad2130..200573b07 100644 --- a/scripts/wallet-approved-dismissal.test.mjs +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -15,18 +15,20 @@ class Element { } const descendants = node => [node, ...node.children.flatMap(descendants)]; -test("Wallet exposes and dismisses approved connector sends without another approval", async t => { +test("Wallet dismisses earlier-session connector sends without another approval", async t => { const previous = globalThis.document; globalThis.document = { createElement: tag => new Element(tag) }; t.after(() => { globalThis.document = previous; }); for (const connector of ["wallet-walletconnect", "wallet-metamask"]) { + const now = Math.floor(Date.now() / 1000); + const expires = connector === "wallet-walletconnect" ? now - 13 * 3600 : now + 300; let request = { request_id: "approval:abandoned", status: "approved", intent: "transaction_intent", connector_id: connector, capsule_id: "browser", address: `0x${"12".repeat(20)}`, - created_at: 1, expires_at: 2, reason: "Send transaction" }; + created_at: expires - 300, expires_at: expires, reason: "Send transaction" }; const root = new Element("section"), panel = new Element("section"), calls = [], messages = []; let refuse = true; const requests = createWalletRequests({ requestsNode: root, requestsPanelNode: panel, - shellHeaders: headers => ({ ...headers, "x-elastos-home-token": "fixture-wallet-token" }), + shellHeaders: headers => ({ ...headers, "x-elastos-home-token": "fixture-current-session-wallet-token" }), fetchJson: async (path, input) => { calls.push({ path, input }); if (refuse) throw new Error("Runtime refused dismissal"); @@ -55,6 +57,8 @@ test("Wallet exposes and dismisses approved connector sends without another appr assert.equal(calls.length, 2); assert.equal(calls[1].path, "/api/apps/wallet/wallet/approvals/approval%3Aabandoned/reject"); assert.equal(calls[1].input.method, "POST"); + assert.equal(calls[1].input.headers["x-elastos-home-token"], "fixture-current-session-wallet-token", + "dismissal uses the current Wallet launch, including for an earlier-session send"); assert.equal(root.children.length, 0, "successful refresh removes the dismissed request"); assert.equal(panel.hidden, true); assert(messages.some(message => message.startsWith("Request dismissed."))); diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 588b5a1a0..04ae1dbe6 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -865,7 +865,8 @@ async function run() { await assertNoErrors(railPage, server, "rail"); server.state.approvals = [{ ...railFixtureState.approvals[0], request_id: "approved-send", status: "approved", intent: "transaction_intent", connector_id: "wallet-walletconnect", - expires_at: Math.floor(Date.now() / 1000) - 1 }]; + created_at: Math.floor(Date.now() / 1000) - 13 * 3600 - 300, + expires_at: Math.floor(Date.now() / 1000) - 13 * 3600 }]; await railPage.goto(`${server.baseUrl}/fixture-host.html?mode=window`, { waitUntil: "networkidle" }); const dismissFrame = await walletFrame(railPage); await dismissFrame.locator(".wallet-account").waitFor({ state: "visible" }); From f5e777dbdd70ced2fd7b93130a7d27ddc5d63f56 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 04:02:56 -0500 Subject: [PATCH 105/139] docs(wallet): state relay backend precedence and dismissal ownership --- docs/WALLET_PROVIDER.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index cf0723ebc..90c3bd024 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -275,8 +275,8 @@ transaction can complete once within 24 hours after expiry, in the same Runtime session. Wallet keeps an approved connector transaction in its request list. Its owner can use Reject in Wallet, System or Inbox to dismiss it in a later Runtime session and release its approval slot. Connector calls and completion -keep their original session binding. Reject does not cancel a phone transaction. An unfinished -prompt expires after the grace period; other connectors keep their normal TTL. +keep their original session binding. Reject does not cancel a phone transaction. +An unfinished prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; the hash alone does not prove that it matches the approved payload. A completion error keeps the @@ -307,9 +307,10 @@ rechecks the launch and owner on each heartbeat and outbound frame, authenticate relay TLS, and limits frames and sockets. It reaches only `relay.walletconnect.org` and `relay.walletconnect.com` on TLS port 443 through a local Exit backend and its separate adapter and relay sockets. When Browser's -local Exit helper starts successfully, Browser's existing backends keep first -match and its wildcard backend carries the relay. When that helper stays stopped -or fails to start, WalletConnect's own relay-only backend takes first match for +local Exit helper starts successfully, the first matching existing backend takes +precedence; the default Browser wildcard therefore carries the relay. WalletConnect's +backend handles requests those backends do not match. When the Browser helper stays +stopped or fails to start, WalletConnect's relay-only backend takes first match for these two TLS hosts. Retained Browser backends keep their order and matching for other traffic, including on older linux-amd64 Homes with a wildcard Browser config. Runtime validates the merged configuration with From 8ca1e7a57a60c3fde719117c60533dad0b4548a4 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 04:10:35 -0500 Subject: [PATCH 106/139] test(walletconnect): prove web policy before managed CLI startup --- scripts/home-frontdoor-smoke.sh | 5 +++-- scripts/local-carrier-setup-smoke.sh | 5 +++-- scripts/walletconnect-installed-policy-smoke.mjs | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/scripts/home-frontdoor-smoke.sh b/scripts/home-frontdoor-smoke.sh index 600e72bc1..d6a15abd1 100755 --- a/scripts/home-frontdoor-smoke.sh +++ b/scripts/home-frontdoor-smoke.sh @@ -409,6 +409,9 @@ do exit 1 fi done +# Prove the web Home before the CLI starts its own managed Runtime. +node "${ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "$ROOT/elastos/target/debug/elastos" "$HOME_DIR/xdg-data/elastos" "$HOME_DIR" + mv "$INSTALLED_HOME_CLI_DIR" "${INSTALLED_HOME_CLI_DIR}.installed" echo "[home-frontdoor] prove current source elastos + current source Home CLI component against clean-home data" @@ -544,6 +547,4 @@ run_repeated_action_case() PY test -x "$INSTALLED_HOME_CLI_DIR/bin/home-cli" cmp "$HOME_CLI_RENDERER" "$INSTALLED_HOME_CLI_DIR/bin/home-cli" -node "${ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "$ROOT/elastos/target/debug/elastos" "$HOME_DIR/xdg-data/elastos" "$HOME_DIR" - echo "[home-frontdoor] OK" diff --git a/scripts/local-carrier-setup-smoke.sh b/scripts/local-carrier-setup-smoke.sh index 2b5d94fd6..89bafc4b9 100755 --- a/scripts/local-carrier-setup-smoke.sh +++ b/scripts/local-carrier-setup-smoke.sh @@ -649,6 +649,9 @@ do fi done +# Prove the web Home before the CLI starts its own managed Runtime. +node "${REPO_ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "${ELASTOS_BIN}" "${DATA_DIR}" "${TEST_ROOT}" + STATUS_OUT="${TEST_ROOT}/home-status.txt" test -x "${DATA_DIR}/capsules/home-cli/bin/home-cli" cmp "$HOME_CLI_RENDERER" "${DATA_DIR}/capsules/home-cli/bin/home-cli" @@ -673,8 +676,6 @@ grep -q "Home CLI /" "${HOME_OUT}" || { exit 1 } -node "${REPO_ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "${ELASTOS_BIN}" "${DATA_DIR}" "${TEST_ROOT}" - echo "[local-carrier-setup] OK" echo "[local-carrier-setup] temp data dir: ${DATA_DIR}" echo "[local-carrier-setup] runtime log: ${LOG_PATH}" diff --git a/scripts/walletconnect-installed-policy-smoke.mjs b/scripts/walletconnect-installed-policy-smoke.mjs index 5e22d3267..dd41a65ab 100644 --- a/scripts/walletconnect-installed-policy-smoke.mjs +++ b/scripts/walletconnect-installed-policy-smoke.mjs @@ -30,7 +30,7 @@ const env = { ...process.env, HOME: home, XDG_DATA_HOME: dirname(data), ELASTOS_ delete env.ELASTOS_WALLETCONNECT_PROJECT_FILE; delete env.ELASTOS_WALLETCONNECT_PROJECT_ID; const log = await open(join(home, "walletconnect-installed-policy.log"), "w", 0o600); -const runtime = spawn(binary, ["serve", "--addr", `127.0.0.1:${port}`], { env, stdio: ["ignore", log.fd, log.fd] }); +const runtime = spawn(binary, ["gateway", "--addr", `127.0.0.1:${port}`], { env, stdio: ["ignore", log.fd, log.fd] }); const stopped = new Promise(resolve => runtime.once("exit", resolve)); let browser; const project = join(home, "walletconnect-test-project"); From 98e7774df45c4ecb010e303852cc70f6c039a5e0 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 04:44:24 -0500 Subject: [PATCH 107/139] test(walletconnect): wait for the Home gateway health route --- scripts/walletconnect-installed-policy-smoke.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/walletconnect-installed-policy-smoke.mjs b/scripts/walletconnect-installed-policy-smoke.mjs index dd41a65ab..bd2cee6fe 100644 --- a/scripts/walletconnect-installed-policy-smoke.mjs +++ b/scripts/walletconnect-installed-policy-smoke.mjs @@ -38,7 +38,8 @@ try { const deadline = Date.now() + 60000; for (;;) { assert(runtime.exitCode === null, "owned Runtime remains running"); - try { if ((await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(1000) })).ok) break; } catch {} + // The Home gateway exposes /healthz; /api/health belongs to serve. + try { if ((await fetch(`${base}/healthz`, { signal: AbortSignal.timeout(1000) })).ok) break; } catch {} assert(Date.now() < deadline, "owned Runtime reaches health readiness"); await delay(100); } From 0d93404be16dec7025e5dd7d58b9630142f3d283 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 05:29:26 -0500 Subject: [PATCH 108/139] fix(home): refuse unconfigured connector before package repair --- docs/WALLET_PROVIDER.md | 5 +- .../src/api/gateway_home_runtime.rs | 9 ++++ .../api/gateway_tests/wallet/connectors.rs | 49 +++++++++++++++++++ .../walletconnect-installed-policy-smoke.mjs | 2 +- 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 90c3bd024..0ff01a1cb 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -273,8 +273,9 @@ A returned transaction hash is passed to Runtime once even if the account, network or expiry changed during the phone prompt. An approved WalletConnect transaction can complete once within 24 hours after expiry, in the same Runtime session. Wallet keeps an approved connector transaction in its request list. -Its owner can use Reject in Wallet, System or Inbox to dismiss it in a later -Runtime session and release its approval slot. Connector calls and completion +Its owner can use Reject in Wallet to dismiss it in a later Runtime session and +release its approval slot. Runtime also accepts this rejection from System and +Inbox. Connector calls and completion keep their original session binding. Reject does not cancel a phone transaction. An unfinished prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index ffc67ff94..6b5f7c719 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -38,6 +38,15 @@ pub(super) async fn home_launch( )); } + // Configuration owns connector availability. Refuse a hidden connector before + // package repair, which cannot make an unconfigured connector launchable. + ensure_wallet_connector_configured(&state.data_dir, target).map_err(|_| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({ "error": "Home target not found" })), + ) + })?; + let mut target_summary = home_launch_target_for_platform(&state.data_dir, target, platform); if target_summary.is_none() || state.data_dir.join("capsules").join(target).exists() { ensure_home_target_package(&state.data_dir, target, target_summary.is_none()) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 32078cd20..0fa323398 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -515,6 +515,55 @@ async fn test_walletconnect_connector_requires_pinned_config() { ); } +#[tokio::test] +async fn test_home_refuses_unconfigured_walletconnect_before_package_repair() { + let dir = tempfile::tempdir().unwrap(); + write_test_browser_capsule( + dir.path(), + WALLET_WALLETCONNECT_CAPSULE_ID, + "app", + "WalletConnect", + None, + ); + // An unavailable repair manifest must not turn a configuration refusal into + // a package-repair error. Configured local capsules still launch normally. + std::fs::write( + dir.path().join("components.json"), + b"invalid repair manifest", + ) + .unwrap(); + let app = gateway_router(test_state(dir.path())); + for configured in [false, true] { + if configured { + seed_walletconnect_connector_config(dir.path()); + } + let response = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/apps/home/launch") + .header(HOST, "localhost:61180") + .header("origin", "http://localhost:61180") + .header("sec-fetch-site", "same-origin") + .header("x-elastos-home-token", home_app_token(dir.path())) + .header(CONTENT_TYPE, "application/json") + .body(Body::from(r#"{"target":"wallet-walletconnect"}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + if configured { + StatusCode::OK + } else { + StatusCode::NOT_FOUND + } + ); + } +} + #[test] fn test_marketplace_lists_walletconnect_only_once_its_config_is_pinned() { let dir = tempfile::tempdir().unwrap(); diff --git a/scripts/walletconnect-installed-policy-smoke.mjs b/scripts/walletconnect-installed-policy-smoke.mjs index bd2cee6fe..7e956b7fc 100644 --- a/scripts/walletconnect-installed-policy-smoke.mjs +++ b/scripts/walletconnect-installed-policy-smoke.mjs @@ -109,7 +109,7 @@ try { if (!configured) assert.equal(row, undefined, "unconfigured connector stays hidden"); const launched = await launch("wallet-walletconnect"); assert.equal(launched.status === 200, configured, "Home launches only configured connector"); - if (!configured) assert(launched.status >= 400 && launched.status < 500, "Home refuses unconfigured launch"); + if (!configured) assert(launched.status >= 400 && launched.status < 500, `Home refuses unconfigured launch: status ${launched.status}, body ${JSON.stringify(launched.body)}`); } await policy(false); // A disposable project file exercises operator configuration without relay access. From f2df1985bc82f8733633ea025a5e55708f321be6 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 05:46:57 -0500 Subject: [PATCH 109/139] test(home): describe the seeded connector repair fixture --- .../src/api/gateway_home_runtime.rs | 4 ++-- .../src/api/gateway_tests/wallet/connectors.rs | 16 ++-------------- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index 6b5f7c719..cb6645197 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -38,8 +38,8 @@ pub(super) async fn home_launch( )); } - // Configuration owns connector availability. Refuse a hidden connector before - // package repair, which cannot make an unconfigured connector launchable. + // Configuration owns connector availability. Refuse a hidden connector + // before package repair. ensure_wallet_connector_configured(&state.data_dir, target).map_err(|_| { ( StatusCode::NOT_FOUND, diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 0fa323398..df1e79962 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -518,20 +518,8 @@ async fn test_walletconnect_connector_requires_pinned_config() { #[tokio::test] async fn test_home_refuses_unconfigured_walletconnect_before_package_repair() { let dir = tempfile::tempdir().unwrap(); - write_test_browser_capsule( - dir.path(), - WALLET_WALLETCONNECT_CAPSULE_ID, - "app", - "WalletConnect", - None, - ); - // An unavailable repair manifest must not turn a configuration refusal into - // a package-repair error. Configured local capsules still launch normally. - std::fs::write( - dir.path().join("components.json"), - b"invalid repair manifest", - ) - .unwrap(); + // The seeded connector row has no repair platform. Configuration refusal + // still returns 404, while a configured local capsule launches normally. let app = gateway_router(test_state(dir.path())); for configured in [false, true] { if configured { From 96ed059d1f0ce75dbd8e8abbd3ee7fc53ee0e049 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 05:48:51 -0500 Subject: [PATCH 110/139] test(install): stage the current source Home in its own fixture --- scripts/home-frontdoor-smoke.sh | 63 ++++++++++++++++++++++++++-- scripts/local-carrier-setup-smoke.sh | 9 ++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/scripts/home-frontdoor-smoke.sh b/scripts/home-frontdoor-smoke.sh index d6a15abd1..89cf9a340 100755 --- a/scripts/home-frontdoor-smoke.sh +++ b/scripts/home-frontdoor-smoke.sh @@ -31,6 +31,7 @@ SOURCE_WALLET_METAMASK_DIR="$ROOT/capsules/wallet-metamask" SOURCE_WALLET_UNISAT_DIR="$ROOT/capsules/wallet-unisat" SOURCE_WALLET_WALLETCONNECT_DIR="$ROOT/capsules/wallet-walletconnect" SOURCE_COMPONENTS_MANIFEST="$ROOT/components.json" +BOOTSTRAP_HOME_DIR="${HOME_DIR}/bootstrap-install" SOURCE_RUNTIME_HOME="${HOME_DIR}/source-runtime" SOURCE_RUNTIME_XDG="${SOURCE_RUNTIME_HOME}/xdg-data" SOURCE_RUNTIME_DATA_DIR="${SOURCE_RUNTIME_XDG}/elastos" @@ -140,6 +141,8 @@ cargo build --manifest-path "$ROOT/capsules/did-provider/Cargo.toml" --release > cargo build --manifest-path "$ROOT/capsules/chain-provider/Cargo.toml" --release >/dev/null cargo build --manifest-path "$ROOT/capsules/net-provider/Cargo.toml" --release >/dev/null cargo build --manifest-path "$ROOT/capsules/exit-provider/Cargo.toml" --release >/dev/null +cargo build --manifest-path "$ROOT/capsules/ipfs-provider/Cargo.toml" --release >/dev/null +cargo build --manifest-path "$ROOT/capsules/model-provider/Cargo.toml" --release >/dev/null cargo build --manifest-path "$ROOT/capsules/browser-engine-adapter/Cargo.toml" --release >/dev/null cargo build --manifest-path "$ROOT/elastos/tools/browser-local-exit/Cargo.toml" --release >/dev/null cargo build --manifest-path "$ROOT/capsules/webspace-provider/Cargo.toml" --release >/dev/null @@ -172,6 +175,8 @@ for capsule in \ home-cli \ home-gui \ archive-manager \ + assistant \ + chat-room \ browser \ system \ services \ @@ -192,9 +197,12 @@ echo "[home-frontdoor] stage source-local trusted source" SOURCE_API_PORT="$(free_port)" SETUP_PLATFORM="$(host_platform)" mkdir -p "$SOURCE_RUNTIME_DATA_DIR/bin" +export KUBO_CACHE_DIR="${KUBO_CACHE_DIR:-${HOME_DIR}/kubo-cache}" +"$ROOT/scripts/seed-kubo-cache.sh" "$KUBO_CACHE_DIR" "$SOURCE_RUNTIME_DATA_DIR" "$SETUP_PLATFORM" +install -m 600 "$ROOT/model-catalog.json" "$SOURCE_RUNTIME_DATA_DIR/model-catalog.json" install -m 755 "$ROOT/elastos/target/release/localhost-provider" "$SOURCE_RUNTIME_DATA_DIR/bin/localhost-provider" -COMPONENTS_SRC="$SOURCE_COMPONENTS_MANIFEST" COMPONENTS_DEST="$SOURCE_RUNTIME_DATA_DIR/components.json" DATA_DIR="$SOURCE_RUNTIME_DATA_DIR" PUBLISHER_ROOT="$SOURCE_RUNTIME_DATA_DIR/ElastOS/SystemServices/Publisher" SETUP_PLATFORM="$SETUP_PLATFORM" SHELL_BIN="$ROOT/elastos/target/release/shell" LOCALHOST_PROVIDER_BIN="$ROOT/elastos/target/release/localhost-provider" DID_PROVIDER_BIN="$ROOT/capsules/did-provider/target/release/did-provider" CHAIN_PROVIDER_BIN="$ROOT/capsules/chain-provider/target/release/chain-provider" NET_PROVIDER_BIN="$ROOT/capsules/net-provider/target/release/net-provider" EXIT_PROVIDER_BIN="$ROOT/capsules/exit-provider/target/release/exit-provider" BROWSER_ENGINE_ADAPTER_BIN="$ROOT/capsules/browser-engine-adapter/target/release/browser-engine-adapter" BROWSER_LOCAL_EXIT_BIN="$ROOT/elastos/tools/browser-local-exit/target/release/browser-local-exit" WEBSPACE_PROVIDER_BIN="$ROOT/capsules/webspace-provider/target/release/webspace-provider" WALLET_PROVIDER_BIN="$ROOT/capsules/wallet-provider/target/release/wallet-provider" OBJECT_PROVIDER_BIN="$ROOT/capsules/object-provider/target/release/object-provider" CONTENT_BLOCK_GRAPH_PROVIDER_BIN="$ROOT/capsules/content-block-graph-provider/target/release/content-block-graph-provider" HOME_CLI_DIR="$SOURCE_HOME_CLI_DIR" HOME_CAPSULE_DIR="$SOURCE_HOME_DIR" HOME_GUI_CAPSULE_DIR="$SOURCE_HOME_GUI_DIR" SYSTEM_CAPSULE_DIR="$SOURCE_SYSTEM_DIR" SERVICES_CAPSULE_DIR="$SOURCE_SERVICES_DIR" PEOPLE_CAPSULE_DIR="$SOURCE_PEOPLE_DIR" BROWSER_CAPSULE_DIR="$SOURCE_BROWSER_DIR" DOCUMENTS_CAPSULE_DIR="$SOURCE_DOCUMENTS_DIR" LIBRARY_CAPSULE_DIR="$SOURCE_LIBRARY_DIR" MARKETPLACE_CAPSULE_DIR="$SOURCE_MARKETPLACE_DIR" ARCHIVE_MANAGER_CAPSULE_DIR="$SOURCE_ARCHIVE_MANAGER_DIR" INBOX_CAPSULE_DIR="$SOURCE_INBOX_DIR" WALLET_CAPSULE_DIR="$SOURCE_WALLET_DIR" WALLET_METAMASK_CAPSULE_DIR="$SOURCE_WALLET_METAMASK_DIR" WALLET_UNISAT_CAPSULE_DIR="$SOURCE_WALLET_UNISAT_DIR" WALLET_WALLETCONNECT_CAPSULE_DIR="$SOURCE_WALLET_WALLETCONNECT_DIR" python3 - <<'PY2' +COMPONENTS_SRC="$SOURCE_COMPONENTS_MANIFEST" COMPONENTS_DEST="$SOURCE_RUNTIME_DATA_DIR/components.json" DATA_DIR="$SOURCE_RUNTIME_DATA_DIR" PUBLISHER_ROOT="$SOURCE_RUNTIME_DATA_DIR/ElastOS/SystemServices/Publisher" SETUP_PLATFORM="$SETUP_PLATFORM" SHELL_BIN="$ROOT/elastos/target/release/shell" LOCALHOST_PROVIDER_BIN="$ROOT/elastos/target/release/localhost-provider" DID_PROVIDER_BIN="$ROOT/capsules/did-provider/target/release/did-provider" CHAIN_PROVIDER_BIN="$ROOT/capsules/chain-provider/target/release/chain-provider" NET_PROVIDER_BIN="$ROOT/capsules/net-provider/target/release/net-provider" EXIT_PROVIDER_BIN="$ROOT/capsules/exit-provider/target/release/exit-provider" IPFS_PROVIDER_BIN="$ROOT/capsules/ipfs-provider/target/release/ipfs-provider" MODEL_PROVIDER_BIN="$ROOT/capsules/model-provider/target/release/model-provider" BROWSER_ENGINE_ADAPTER_BIN="$ROOT/capsules/browser-engine-adapter/target/release/browser-engine-adapter" BROWSER_LOCAL_EXIT_BIN="$ROOT/elastos/tools/browser-local-exit/target/release/browser-local-exit" WEBSPACE_PROVIDER_BIN="$ROOT/capsules/webspace-provider/target/release/webspace-provider" WALLET_PROVIDER_BIN="$ROOT/capsules/wallet-provider/target/release/wallet-provider" OBJECT_PROVIDER_BIN="$ROOT/capsules/object-provider/target/release/object-provider" CONTENT_BLOCK_GRAPH_PROVIDER_BIN="$ROOT/capsules/content-block-graph-provider/target/release/content-block-graph-provider" HOME_CLI_DIR="$SOURCE_HOME_CLI_DIR" HOME_CAPSULE_DIR="$SOURCE_HOME_DIR" HOME_GUI_CAPSULE_DIR="$SOURCE_HOME_GUI_DIR" SYSTEM_CAPSULE_DIR="$SOURCE_SYSTEM_DIR" SERVICES_CAPSULE_DIR="$SOURCE_SERVICES_DIR" PEOPLE_CAPSULE_DIR="$SOURCE_PEOPLE_DIR" BROWSER_CAPSULE_DIR="$SOURCE_BROWSER_DIR" DOCUMENTS_CAPSULE_DIR="$SOURCE_DOCUMENTS_DIR" LIBRARY_CAPSULE_DIR="$SOURCE_LIBRARY_DIR" MARKETPLACE_CAPSULE_DIR="$SOURCE_MARKETPLACE_DIR" ARCHIVE_MANAGER_CAPSULE_DIR="$SOURCE_ARCHIVE_MANAGER_DIR" INBOX_CAPSULE_DIR="$SOURCE_INBOX_DIR" WALLET_CAPSULE_DIR="$SOURCE_WALLET_DIR" WALLET_METAMASK_CAPSULE_DIR="$SOURCE_WALLET_METAMASK_DIR" WALLET_UNISAT_CAPSULE_DIR="$SOURCE_WALLET_UNISAT_DIR" WALLET_WALLETCONNECT_CAPSULE_DIR="$SOURCE_WALLET_WALLETCONNECT_DIR" python3 - <<'PY2' import hashlib import json import os @@ -208,6 +216,7 @@ publisher_root = pathlib.Path(os.environ["PUBLISHER_ROOT"]) artifacts_dir = publisher_root / "artifacts" artifacts_dir.mkdir(parents=True, exist_ok=True) platform = os.environ["SETUP_PLATFORM"] +data_dir = pathlib.Path(os.environ["DATA_DIR"]) manifest = json.loads(components_src.read_text()) @@ -225,6 +234,8 @@ mapping = { "chain-provider": pathlib.Path(os.environ["CHAIN_PROVIDER_BIN"]), "net-provider": pathlib.Path(os.environ["NET_PROVIDER_BIN"]), "exit-provider": pathlib.Path(os.environ["EXIT_PROVIDER_BIN"]), + "ipfs-provider": pathlib.Path(os.environ["IPFS_PROVIDER_BIN"]), + "model-provider": pathlib.Path(os.environ["MODEL_PROVIDER_BIN"]), "browser-engine-adapter": pathlib.Path(os.environ["BROWSER_ENGINE_ADAPTER_BIN"]), "browser-local-exit": pathlib.Path(os.environ["BROWSER_LOCAL_EXIT_BIN"]), "webspace-provider": pathlib.Path(os.environ["WEBSPACE_PROVIDER_BIN"]), @@ -252,6 +263,20 @@ shutil.copyfile(os.environ["MEDIA_TOOLS_ARCHIVE"], media_archive) media_info["checksum"] = "sha256:" + hashlib.sha256(media_archive.read_bytes()).hexdigest() media_info["size"] = media_archive.stat().st_size +# Use the same licensed Kubo capsule as the Carrier-only setup fixture. +cache = pathlib.Path(os.environ["KUBO_CACHE_DIR"]) +receipt = json.loads((data_dir / "receipts/kubo-build.json").read_bytes()) +kubo_archive = artifacts_dir / receipt["release_path"] +shutil.copyfile(cache / "capsules" / receipt["release_path"], kubo_archive) +if "sha256:" + hashlib.sha256(kubo_archive.read_bytes()).hexdigest() != receipt["checksum"]: + raise SystemExit("Kubo capsule differs from its build receipt") +kubo_info = platform_info("kubo") +kubo_info.update({key: receipt[key] for key in ("checksum", "size", "release_path", "extract_path", "install_path")}) +kubo_info.pop("strategy", None) +manifest["external"]["kubo"]["capsule_metadata"] = { + "role": "content", "type": "data", "install_path": "capsules/kubo", + "platforms": {platform: receipt["capsule_metadata"]}} + def write_capsule_archive(name, capsule_dir): capsule_manifest = json.loads((capsule_dir / "capsule.json").read_text()) entrypoint = capsule_manifest.get("entrypoint") @@ -297,6 +322,8 @@ browser_capsules = { "library": pathlib.Path(os.environ["LIBRARY_CAPSULE_DIR"]), "marketplace": pathlib.Path(os.environ["MARKETPLACE_CAPSULE_DIR"]), "archive-manager": pathlib.Path(os.environ["ARCHIVE_MANAGER_CAPSULE_DIR"]), + "assistant": components_src.parent / "capsules/assistant", + "chat-room": components_src.parent / "capsules/chat-room", "wallet": pathlib.Path(os.environ["WALLET_CAPSULE_DIR"]), "wallet-metamask": pathlib.Path(os.environ["WALLET_METAMASK_CAPSULE_DIR"]), "wallet-unisat": pathlib.Path(os.environ["WALLET_UNISAT_CAPSULE_DIR"]), @@ -305,6 +332,15 @@ browser_capsules = { for name, capsule_dir in browser_capsules.items(): write_capsule_archive(name, capsule_dir) +# Keep this fixture aligned with the actual default profile, without a second list. +for name in manifest["profiles"]["home"]["components"]: + info = platform_info(name) + archive = artifacts_dir / info["release_path"] + if not archive.is_file() or info.get("size", 0) != archive.stat().st_size: + raise SystemExit(f"default Home fixture artifact missing or stale: {name}") + if info.get("checksum") != "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest(): + raise SystemExit(f"default Home fixture checksum differs: {name}") + components_dest.parent.mkdir(parents=True, exist_ok=True) components_dest.write_text(json.dumps(manifest, indent=2) + "\n") PY2 @@ -340,7 +376,28 @@ if [[ -z "$SOURCE_CONNECT_TICKET" || -z "$SOURCE_NODE_ID" ]]; then exit 1 fi -HOME="$HOME_DIR" XDG_DATA_HOME="$HOME_DIR/xdg-data" ELASTOS_PUBLISHER_GATEWAY="$PUBLISHER_GATEWAY" ELASTOS_MAINTAINER_DID="$MAINTAINER_DID" ELASTOS_SOURCE_CONNECT_TICKET="$SOURCE_CONNECT_TICKET" ELASTOS_PUBLISHER_NODE_ID="$SOURCE_NODE_ID" bash "$ROOT/scripts/install.sh" >/tmp/elastos-home-frontdoor-install.log +# Keep the published signed bootstrap separate from the current unsigned source +# fixture. Runtime admits each with its own existing installation rules. +mkdir -p "$BOOTSTRAP_HOME_DIR" +HOME="$BOOTSTRAP_HOME_DIR" XDG_DATA_HOME="$BOOTSTRAP_HOME_DIR/xdg-data" ELASTOS_PUBLISHER_GATEWAY="$PUBLISHER_GATEWAY" ELASTOS_MAINTAINER_DID="$MAINTAINER_DID" bash "$ROOT/scripts/install.sh" >"$HOME_DIR/bootstrap-install.log" + +mkdir -p "$HOME_DIR/xdg-data/elastos/bin" +install -m 700 "$ROOT/elastos/target/release/localhost-provider" "$HOME_DIR/xdg-data/elastos/bin/localhost-provider" +install -m 600 "$ROOT/model-catalog.json" "$HOME_DIR/xdg-data/elastos/model-catalog.json" +SOURCE_CONNECT_TICKET="$SOURCE_CONNECT_TICKET" SOURCE_NODE_ID="$SOURCE_NODE_ID" SOURCE_DATA="$HOME_DIR/xdg-data/elastos" python3 - <<'PY2' +import json +import os +from pathlib import Path +# Source-checkout setup has no installed signed release or consumed installation. +# The Carrier-only smoke uses the same explicit trusted-source contract. +source = {"name": "default", "publisher_dids": ["did:key:home-frontdoor-fixture"], + "channel": "stable", "discovery_uri": "elastos://source/stable/home-frontdoor-fixture", + "connect_ticket": os.environ["SOURCE_CONNECT_TICKET"], + "publisher_node_id": os.environ["SOURCE_NODE_ID"], "ipns_name": "", "gateways": [], + "install_path": "", "installed_version": "", "head_cid": ""} +(Path(os.environ["SOURCE_DATA"]) / "sources.json").write_text(json.dumps({ + "schema": "elastos.trusted-sources/v1", "default_source": "default", "sources": [source]}) + "\n") +PY2 if [[ ! -f "$SOURCE_COMPONENTS_MANIFEST" ]]; then echo "[home-frontdoor] source components manifest missing: $SOURCE_COMPONENTS_MANIFEST" >&2 @@ -351,7 +408,7 @@ echo "[home-frontdoor] setup home profile" cp "$SOURCE_RUNTIME_DATA_DIR/components.json" "$HOME_DIR/xdg-data/elastos/components.json" # A source-manifest setup manages collaboration itself: a pinned release network in # components.json is neither required beside the manifest nor joined (live Community). -HOME="$HOME_DIR" XDG_DATA_HOME="$HOME_DIR/xdg-data" ELASTOS_COLLABORATION_STARTUP_MODE=isolated ELASTOS_COMPONENTS_MANIFEST="$SOURCE_RUNTIME_DATA_DIR/components.json" "$ROOT/elastos/target/debug/elastos" setup --profile home >/tmp/elastos-home-frontdoor-setup.log +HOME="$HOME_DIR" XDG_DATA_HOME="$HOME_DIR/xdg-data" ELASTOS_COLLABORATION_STARTUP_MODE=isolated ELASTOS_COMPONENTS_MANIFEST="$SOURCE_RUNTIME_DATA_DIR/components.json" "$ROOT/elastos/target/debug/elastos" setup --profile home 2>&1 | tee "$HOME_DIR/setup.log" INSTALLED_HOME_CLI_DIR="$HOME_DIR/xdg-data/elastos/capsules/home-cli" if [[ ! -d "$INSTALLED_HOME_CLI_DIR" ]]; then diff --git a/scripts/local-carrier-setup-smoke.sh b/scripts/local-carrier-setup-smoke.sh index 89bafc4b9..bc2c4a55c 100755 --- a/scripts/local-carrier-setup-smoke.sh +++ b/scripts/local-carrier-setup-smoke.sh @@ -409,6 +409,15 @@ browser_capsules = { for name, capsule_dir in browser_capsules.items(): write_capsule_archive(name, capsule_dir) +# Keep this fixture aligned with the actual default profile, without a second list. +for name in manifest["profiles"]["home"]["components"]: + info = platform_info(name) + archive = artifacts_dir / info["release_path"] + if not archive.is_file() or info.get("size", 0) != archive.stat().st_size: + raise SystemExit(f"default Home fixture artifact missing or stale: {name}") + if info.get("checksum") != "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest(): + raise SystemExit(f"default Home fixture checksum differs: {name}") + components_dest.parent.mkdir(parents=True, exist_ok=True) components_dest.write_text(json.dumps(manifest, indent=2) + "\n") PY From 342fb1ce90c0545bbcc920db205470fc92f56062 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 05:59:22 -0500 Subject: [PATCH 111/139] test(home): prove explicit setup repair of a missing CLI renderer --- scripts/home-frontdoor-smoke.sh | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/scripts/home-frontdoor-smoke.sh b/scripts/home-frontdoor-smoke.sh index 89cf9a340..3cf443668 100755 --- a/scripts/home-frontdoor-smoke.sh +++ b/scripts/home-frontdoor-smoke.sh @@ -380,6 +380,7 @@ fi # fixture. Runtime admits each with its own existing installation rules. mkdir -p "$BOOTSTRAP_HOME_DIR" HOME="$BOOTSTRAP_HOME_DIR" XDG_DATA_HOME="$BOOTSTRAP_HOME_DIR/xdg-data" ELASTOS_PUBLISHER_GATEWAY="$PUBLISHER_GATEWAY" ELASTOS_MAINTAINER_DID="$MAINTAINER_DID" bash "$ROOT/scripts/install.sh" >"$HOME_DIR/bootstrap-install.log" +test -x "$BOOTSTRAP_HOME_DIR/.local/bin/elastos" mkdir -p "$HOME_DIR/xdg-data/elastos/bin" install -m 700 "$ROOT/elastos/target/release/localhost-provider" "$HOME_DIR/xdg-data/elastos/bin/localhost-provider" @@ -446,6 +447,12 @@ for installed in \ "$HOME_DIR/xdg-data/elastos/bin/browser-engine-adapter" \ "$HOME_DIR/xdg-data/elastos/bin/browser-local-exit" \ "$HOME_DIR/xdg-data/elastos/bin/object-provider" \ + "$HOME_DIR/xdg-data/elastos/bin/kubo" \ + "$HOME_DIR/xdg-data/elastos/capsules/kubo/capsule.json" \ + "$HOME_DIR/xdg-data/elastos/bin/ipfs-provider" \ + "$HOME_DIR/xdg-data/elastos/bin/model-provider" \ + "$HOME_DIR/xdg-data/elastos/capsules/assistant/browser/index.html" \ + "$HOME_DIR/xdg-data/elastos/capsules/chat-room/browser/index.html" \ "$HOME_DIR/xdg-data/elastos/bin/wallet-provider" do if [[ ! -f "$installed" ]]; then @@ -471,8 +478,8 @@ node "${ROOT}/scripts/walletconnect-installed-policy-smoke.mjs" "$ROOT/elastos/t mv "$INSTALLED_HOME_CLI_DIR" "${INSTALLED_HOME_CLI_DIR}.installed" -echo "[home-frontdoor] prove current source elastos + current source Home CLI component against clean-home data" -HOME_DIR="$HOME_DIR" ROOT="$ROOT" SOURCE_COMPONENTS_MANIFEST="$SOURCE_COMPONENTS_MANIFEST" python3 - <<'PY' +echo "[home-frontdoor] prove Home CLI refusal, setup repair, and navigation" +HOME_DIR="$HOME_DIR" ROOT="$ROOT" SOURCE_COMPONENTS_MANIFEST="$SOURCE_RUNTIME_DATA_DIR/components.json" python3 - <<'PY' import os import pty import select @@ -544,6 +551,25 @@ def shutdown(master: int, proc: subprocess.Popen) -> None: finally: os.close(master) +def run_missing_renderer_and_repair_case() -> None: + # Runtime reports an incomplete Home. Setup owns restoring the installed + # renderer; a launch does not fetch executable code as a fallback. + master, proc = launch_pty() + try: + output = read_until( + "missing renderer", master, + lambda text: "Home CLI native renderer missing" in text, 10.0, + ) + if "Run the installer again to repair Home" not in output or proc.wait(timeout=5) == 0: + raise SystemExit(f"missing renderer: expected repair refusal:\n{output}") + finally: + shutdown(master, proc) + repair_env = env.copy() + repair_env["ELASTOS_COMPONENTS_MANIFEST"] = os.environ["SOURCE_COMPONENTS_MANIFEST"] + repair_env["ELASTOS_COLLABORATION_STARTUP_MODE"] = "isolated" + subprocess.run([cmd[0], "setup", "--profile", "home"], env=repair_env, + check=True, timeout=120) + def run_repeated_action_case() -> None: # Two actions in a row must keep Home open (the second one used to quit # with "provider localhost/delete failed [403 Forbidden]"). @@ -599,6 +625,7 @@ def run_navigation_case() -> None: finally: shutdown(master, proc) +run_missing_renderer_and_repair_case() run_navigation_case() run_repeated_action_case() PY From 154bc462aeefb9879ee16c00ed22ca4dda1bc3e2 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 06:12:56 -0500 Subject: [PATCH 112/139] test(home): wait for the current CLI frame during refresh --- scripts/home-frontdoor-smoke.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/home-frontdoor-smoke.sh b/scripts/home-frontdoor-smoke.sh index 3cf443668..60934bde7 100755 --- a/scripts/home-frontdoor-smoke.sh +++ b/scripts/home-frontdoor-smoke.sh @@ -573,13 +573,14 @@ def run_missing_renderer_and_repair_case() -> None: def run_repeated_action_case() -> None: # Two actions in a row must keep Home open (the second one used to quit # with "provider localhost/delete failed [403 Forbidden]"). + home_tab = "\x1b[30;46;1m Home \x1b[0m" master, proc = launch_pty() try: - read_until("repeat", master, lambda text: "ElastOS Home" in text, 10.0) + read_until("repeat", master, lambda text: home_tab in text and "Keys:" in text, 10.0) for attempt in (1, 2): send(master, b"r", 0.5) - screen = read_until("repeat", master, lambda text: "ElastOS Home" in text, 8.0) - if proc.poll() is not None or "ElastOS Home" not in screen or "Error:" in screen: + screen = read_until("repeat", master, lambda text: home_tab in text and "Keys:" in text, 8.0) + if proc.poll() is not None or home_tab not in screen or "Error:" in screen: raise SystemExit(f"repeat: Home did not stay open after action {attempt}:\n{screen}") finally: shutdown(master, proc) From 27c8074b6c0392a9d0aedca8addb1ca3902758fc Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 21:33:08 -0500 Subject: [PATCH 113/139] fix(wallet): scope unfinished sends and show dismissed receipts --- capsules/wallet/browser/wallet-activity.js | 9 +++++--- scripts/wallet-approved-dismissal.test.mjs | 24 +++++++++++++++++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/capsules/wallet/browser/wallet-activity.js b/capsules/wallet/browser/wallet-activity.js index 94a2cd920..468b2effb 100644 --- a/capsules/wallet/browser/wallet-activity.js +++ b/capsules/wallet/browser/wallet-activity.js @@ -26,11 +26,11 @@ export function createWalletActivity({ activityNode, textNode }) { } export function pendingRequests(requests) { - // An approved connector send still needs its receipt or explicit dismissal. + // WalletConnect keeps an approved send through its receipt grace period. return requests.filter((request) => readText(request.status) === "pending" || (readText(request.status) === "approved" && readText(request.intent) === "transaction_intent" - && Boolean(readText(request.connector_id)))); + && readText(request.connector_id) === "wallet-walletconnect")); } export function activityTime(request) { @@ -47,6 +47,9 @@ export function activityIcon(request) { export function activityTitle(request) { const status = readText(request.status); const capsule = readText(request.capsule_id) || "Capsule"; + if (request.transaction_hash && status === "rejected" && request.approved_at) { + return `${capsule} · Dismissed here; still sent from wallet`; + } if (request.transaction_hash) { return `${capsule} · Sent transaction`; } @@ -54,7 +57,7 @@ export function activityTitle(request) { return `${capsule} · Approved ${requestTitle(request)}`; } if (status === "rejected") { - if (request.intent === "transaction_intent" && readText(request.connector_id)) { + if (request.intent === "transaction_intent" && request.approved_at && readText(request.connector_id)) { return `${capsule} · Dismissed transaction request`; } return `${capsule} · Rejected ${requestTitle(request)}`; diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs index 200573b07..83fc46d28 100644 --- a/scripts/wallet-approved-dismissal.test.mjs +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createWalletRequests } from "../capsules/wallet/browser/wallet-requests.js"; -import { activityTitle } from "../capsules/wallet/browser/wallet-activity.js"; +import { activityTitle, activitySubtitle, pendingRequests } from "../capsules/wallet/browser/wallet-activity.js"; class Element { children = []; dataset = {}; hidden = false; textContent = ""; @@ -19,12 +19,12 @@ test("Wallet dismisses earlier-session connector sends without another approval" const previous = globalThis.document; globalThis.document = { createElement: tag => new Element(tag) }; t.after(() => { globalThis.document = previous; }); - for (const connector of ["wallet-walletconnect", "wallet-metamask"]) { + for (const connector of ["wallet-walletconnect"]) { const now = Math.floor(Date.now() / 1000); const expires = connector === "wallet-walletconnect" ? now - 13 * 3600 : now + 300; let request = { request_id: "approval:abandoned", status: "approved", intent: "transaction_intent", connector_id: connector, capsule_id: "browser", address: `0x${"12".repeat(20)}`, - created_at: expires - 300, expires_at: expires, reason: "Send transaction" }; + approved_at: expires - 290, created_at: expires - 300, expires_at: expires, reason: "Send transaction" }; const root = new Element("section"), panel = new Element("section"), calls = [], messages = []; let refuse = true; const requests = createWalletRequests({ requestsNode: root, requestsPanelNode: panel, @@ -65,3 +65,21 @@ test("Wallet dismisses earlier-session connector sends without another approval" assert.match(activityTitle(request), /Dismissed transaction request/); } }); + +test("only WalletConnect unfinished approved sends enter the request list and badge", () => { + const approved = { status: "approved", intent: "transaction_intent", approved_at: 10 }; + for (const connector_id of ["wallet-metamask", "wallet-unisat", "wallet-walletconnect"]) { + const request = { ...approved, connector_id }; + assert.equal(pendingRequests([request]).length, connector_id === "wallet-walletconnect" ? 1 : 0); + assert.equal(pendingRequests([{ ...request, status: "pending" }]).length, 1); + } +}); + +test("Activity distinguishes pending rejection, approved dismissal and a late wallet send", () => { + const request = { status: "rejected", intent: "transaction_intent", connector_id: "wallet-walletconnect", capsule_id: "browser" }; + assert.match(activityTitle(request), /Rejected/); + assert.match(activityTitle({ ...request, approved_at: 10 }), /Dismissed transaction request/); + const late = { ...request, approved_at: 10, transaction_hash: `0x${"a".repeat(64)}` }; + assert.match(activityTitle(late), /Dismissed here.*still sent from wallet/); + assert.match(activitySubtitle(late), /tx 0xaaaa/); +}); From b46409f35562320d1009b7d94a1e1e8f2033537d Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 21:38:28 -0500 Subject: [PATCH 114/139] fix(wallet): preserve approval state in gateway responses --- .../crates/elastos-server/src/api/gateway.rs | 1 + .../elastos-server/src/api/gateway_models.rs | 2 + .../api/gateway_tests/support_providers.rs | 32 ++++++++- .../src/api/gateway_tests/wallet/inbox.rs | 69 +++++++++++++++++++ .../src/api/gateway_wallet_approvals.rs | 1 + 5 files changed, 104 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway.rs b/elastos/crates/elastos-server/src/api/gateway.rs index 89e8ff35d..a91860531 100644 --- a/elastos/crates/elastos-server/src/api/gateway.rs +++ b/elastos/crates/elastos-server/src/api/gateway.rs @@ -1478,6 +1478,7 @@ fn inbox_error_response(err: anyhow::Error) -> Response { } else if text.contains("unknown inbox action") || text.contains("Open Wallet") || text.contains("is not pending") + || text.contains("cannot be rejected") || text.contains("is no longer pending") || text.contains("changed before Inbox approval") || text.contains("service access request") diff --git a/elastos/crates/elastos-server/src/api/gateway_models.rs b/elastos/crates/elastos-server/src/api/gateway_models.rs index b477df956..354ce9dab 100644 --- a/elastos/crates/elastos-server/src/api/gateway_models.rs +++ b/elastos/crates/elastos-server/src/api/gateway_models.rs @@ -653,6 +653,8 @@ struct SystemWalletApprovalSummary { #[serde(skip_serializing_if = "Option::is_none")] completed_at: Option, #[serde(skip_serializing_if = "Option::is_none")] + approved_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] transaction_hash: Option, } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs index 05de4f977..3a6aac8b9 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs @@ -6199,6 +6199,13 @@ impl MockWalletProvider { "message": "wallet approval request not found" })); }; + if approval["status"] != "pending" { + return Ok(json!({ + "status": "error", + "code": "invalid_request", + "message": "wallet approval request cannot be rejected" + })); + } approval["status"] = serde_json::Value::String("rejected".to_string()); Ok(json!({ "status": "ok", @@ -6227,7 +6234,7 @@ impl MockWalletProvider { return Ok(json!({ "status": "error", "code": "invalid_request", - "message": "wallet approval request is not pending" + "message": "wallet approval request cannot be rejected" })); } if !approval @@ -6586,3 +6593,26 @@ impl MockWalletProvider { } } } + +pub(super) fn seed_walletconnect_connector_config(data_dir: &std::path::Path) { + let sdk = b"// pinned test WalletConnect SDK asset\n"; + let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); + std::fs::create_dir_all(sdk_path.parent().unwrap()).unwrap(); + std::fs::write(&sdk_path, sdk).unwrap(); + let sdk_sha256 = format!("{:x}", Sha256::digest(sdk)); + + let config_path = data_dir.join(WALLETCONNECT_CONFIG_PATH); + std::fs::create_dir_all(config_path.parent().unwrap()).unwrap(); + std::fs::write( + config_path, + serde_json::to_vec(&json!({ + "schema": WALLETCONNECT_CONFIG_SCHEMA, + "project_id": "test_walletconnect_project", + "sdk_package": WALLETCONNECT_SDK_PACKAGE, + "sdk_version": "1.0.0", + "sdk_sha256": sdk_sha256 + })) + .unwrap(), + ) + .unwrap(); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs index 66f51e83f..e61988ee5 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs @@ -889,3 +889,72 @@ async fn test_btc_wallet_approval_journey_reviews_in_inbox_and_signs() { .unwrap_or_default() .starts_with("did:key:")); } + +#[tokio::test] +async fn test_inbox_reject_resolved_wallet_request_returns_bad_request() { + let dir = tempfile::tempdir().unwrap(); + let authority = passkey_authority(dir.path()); + let token = app_token_for_authority(dir.path(), INBOX_CAPSULE_ID, &authority); + let provider = MockWalletProvider { + challenges: TokioMutex::default(), + bitcoin_challenges: TokioMutex::default(), + accounts: TokioMutex::default(), + approvals: TokioMutex::new(vec![json!({ + "request_id": "wallet-approval:resolved", + "principal_id": authority.principal_id, + "status": "completed", + "intent": "transaction_intent", "requested_by_actor":"browser", + "resource":"elastos://transaction", "reason":"Sent", "account_id":"fixture", + "address":"0xabc", "created_at":10, "expires_at":20 + })]), + defaults: TokioMutex::default(), + }; + let state = wallet_test_state_with_provider(dir.path(), provider).await; + let app = gateway_router(state); + let response = app + .oneshot( + test_browser_request("localhost:61180", "null") + .method("POST") + .uri("/api/apps/inbox/actions") + .header("x-elastos-home-token", token) + .header(CONTENT_TYPE, "application/json") + .body(Body::from( + r#"{"action_id":"wallet-reject-request:wallet-approval:resolved"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert!(String::from_utf8(body.to_vec()) + .unwrap() + .contains("cannot be rejected")); +} + +#[test] +fn test_wallet_activity_summary_preserves_approval_and_late_receipt() { + let mut request = json!({"request_id":"fixture", "status":"rejected", "intent":"transaction_intent", + "requested_by_actor":"browser", "resource":"elastos://transaction", "reason":"Dismissed", + "account_id":"fixture", "address":"0xabc", "created_at":10, "expires_at":20, + "connector_id":"wallet-walletconnect"}); + assert!( + serde_json::to_value(system_wallet_approval_summary(&request).unwrap()) + .unwrap() + .get("approved_at") + .is_none() + ); + request["approved_at"] = json!(15); + request["completed_at"] = json!(25); + request["signed_result"] = json!({"transaction_hash":format!("0x{}", "a".repeat(64))}); + let summary = serde_json::to_value(system_wallet_approval_summary(&request).unwrap()).unwrap(); + assert_eq!(summary["status"], "rejected"); + assert_eq!(summary["approved_at"], 15); + assert_eq!(summary["completed_at"], 25); + assert_eq!( + summary["transaction_hash"], + request["signed_result"]["transaction_hash"] + ); +} diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index b868d3dfd..c571c1515 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -539,6 +539,7 @@ pub(in crate::api::gateway) fn system_wallet_approval_summary( .and_then(|value| value.get("completed_at")) .and_then(|value| value.as_u64()) }), + approved_at: value.get("approved_at").and_then(|value| value.as_u64()), transaction_hash: signed_result .and_then(|value| value.get("transaction_hash")) .and_then(|value| value.as_str()) From d21140a82a7dd89571c50e5a3d2adada6c7f8f52 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 21:38:28 -0500 Subject: [PATCH 115/139] fix(wallet): restrict dismissal and retain one late send receipt --- capsules/wallet-provider/src/approval.rs | 19 ++- .../src/tests/approvals/transactions.rs | 158 +++++++++++++++--- .../api/gateway_tests/wallet/connectors.rs | 35 +--- .../api/gateway_tests/wallet/walletconnect.rs | 2 +- .../src/api/gateway_wallet_connectors.rs | 7 +- 5 files changed, 170 insertions(+), 51 deletions(-) diff --git a/capsules/wallet-provider/src/approval.rs b/capsules/wallet-provider/src/approval.rs index cfc7fd09e..e11f8e16d 100644 --- a/capsules/wallet-provider/src/approval.rs +++ b/capsules/wallet-provider/src/approval.rs @@ -416,7 +416,7 @@ impl WalletProvider { "wallet approval request belongs to a different connector", ); } - if request.status != ApprovalStatus::Pending && !approved_connector_transaction { + if request.status != ApprovalStatus::Pending && !owner_dismissal { return Response::error( "invalid_request", "wallet approval request cannot be rejected", @@ -593,7 +593,15 @@ impl WalletProvider { if request.status == ApprovalStatus::Expired { return Response::error("invalid_request", "wallet approval request expired"); } - if request.status != ApprovalStatus::Approved { + let late_transaction_receipt = request.status == ApprovalStatus::Rejected + && request.approved_at.is_some() + && request.intent == "transaction_intent" + && request.connector_id.as_deref() == Some("wallet-walletconnect") + && request.signed_result.is_none() + && request.expires_at.saturating_add( + elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS, + ) > now; + if request.status != ApprovalStatus::Approved && !late_transaction_receipt { return Response::error( "invalid_request", "wallet approval request must be approved before completion", @@ -821,8 +829,11 @@ impl WalletProvider { completed_at: now, }; let request = &mut self.store.approval_requests[request_index]; - request.status = ApprovalStatus::Completed; - request.resolved_at = Some(now); + // A late phone receipt records the send while preserving the owner's dismissal. + if request.status != ApprovalStatus::Rejected { + request.status = ApprovalStatus::Completed; + request.resolved_at = Some(now); + } request.completed_at = Some(now); request.signature_receipt = Some(receipt.clone()); request.signed_result = signed_result; diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 330e63b3b..5c574fa63 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -234,7 +234,7 @@ fn validated_chain_outcome_projection_is_exact_and_idempotent() { #[test] fn transaction_intent_validates_payload_and_allows_external_handoff() { for connector in ["wallet-metamask", "wallet-walletconnect"] { - external_transaction_handoff_with_expiry(connector, None); + external_transaction_handoff_with_expiry(connector, None, false); } } @@ -242,12 +242,18 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { fn approved_connector_transaction_can_be_rejected_and_releases_its_slot() { for actor in ["wallet", "system", "inbox"] { for connector in ["wallet-metamask", "wallet-walletconnect"] { - external_transaction_handoff_with_expiry(connector, Some(actor)); + for same_session in [false, true] { + external_transaction_handoff_with_expiry(connector, Some(actor), same_session); + } } } } -fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Option<&str>) { +fn external_transaction_handoff_with_expiry( + connector: &str, + dismiss_actor: Option<&str>, + same_session: bool, +) { let dir = tempfile::tempdir().unwrap(); let mut provider = init_provider(dir.path()); let principal_id = "person:local:alice"; @@ -316,7 +322,11 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Opti let (request_id, payload_hash) = match invoke_wallet( &mut provider, principal_id, - "system", + if dismiss_actor.is_some() { + "browser" + } else { + "system" + }, WalletProviderOperationV2::RequestApproval { account_id: external_account_id.clone(), chain_namespace: "eip155:20".into(), @@ -438,6 +448,8 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Opti for context in [ wallet_context_in_session(principal_id, connector, "session:replacement"), wallet_context_in_session(principal_id, "browser", "session:replacement"), + wallet_context(principal_id, connector), + wallet_context(principal_id, "browser"), wallet_context("person:local:bob", "wallet"), wallet_context(principal_id, "wallet-unisat"), ] { @@ -487,7 +499,11 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Opti matches!(invoke_wallet(&mut provider, principal_id, "system", next()), Response::Error { ref code, .. } if code == "approval_limit_reached") ); - let context = wallet_context_in_session(principal_id, actor, "session:replacement"); + let context = if same_session { + wallet_context(principal_id, actor) + } else { + wallet_context_in_session(principal_id, actor, "session:replacement") + }; let response = invoke_wallet_with_context(&mut provider, &context, reject()); assert!(matches!(response, Response::Ok { .. }), "{response:?}"); let rejected = provider @@ -506,23 +522,127 @@ fn external_transaction_handoff_with_expiry(connector: &str, dismiss_actor: Opti invoke_wallet(&mut provider, principal_id, "wallet", reject()), Response::Error { .. } )); - assert!(matches!( - invoke_wallet( - &mut provider, - principal_id, - connector, - WalletProviderOperationV2::CompleteConnectorHandoff { - request_id, + let dismissed = provider + .store + .approval_requests + .iter() + .find(|r| r.request_id == request_id) + .unwrap() + .clone(); + let complete = || WalletProviderOperationV2::CompleteConnectorHandoff { + request_id: request_id.clone(), + payload_hash: payload_hash.clone(), + signature: None, + signature_type: None, + public_key: None, + signer: external_address.into(), + transaction_hash: Some(format!("0x{}", "a".repeat(64))), + }; + if connector == "wallet-walletconnect" { + for (who, session) in [ + ("person:local:bob", "session:test"), + (principal_id, "session:replacement"), + ] { + let context = wallet_context_in_session(who, connector, session); + assert!(matches!( + invoke_wallet_with_context(&mut provider, &context, complete()), + Response::Error { .. } + )); + } + for field in ["payload", "signer", "signature"] { + let mut operation = complete(); + if let WalletProviderOperationV2::CompleteConnectorHandoff { payload_hash, - signature: None, - signature_type: None, - public_key: None, - signer: external_address.into(), - transaction_hash: Some(format!("0x{}", "a".repeat(64))), + signer, + transaction_hash, + signature, + signature_type, + .. + } = &mut operation + { + match field { + "payload" => *payload_hash = format!("0x{}", "b".repeat(64)), + "signer" => *signer = format!("0x{}", "4".repeat(40)), + "signature" => { + *transaction_hash = None; + *signature = Some(format!("0x{}", "a".repeat(130))); + *signature_type = Some("personal_sign".into()); + } + _ => unreachable!(), + } } + assert!( + matches!( + invoke_wallet(&mut provider, principal_id, connector, operation), + Response::Error { .. } + ), + "{field}" + ); + } + assert!(matches!( + invoke_wallet(&mut provider, principal_id, "wallet-metamask", complete()), + Response::Error { .. } + )); + for (approved_at, expires_at) in + [(None, now + 300), (dismissed.approved_at, now - grace)] + { + let request = provider + .store + .approval_requests + .iter_mut() + .find(|r| r.request_id == request_id) + .unwrap(); + request.approved_at = approved_at; + request.expires_at = expires_at; + assert!(matches!( + invoke_wallet(&mut provider, principal_id, connector, complete()), + Response::Error { .. } + )); + } + *provider + .store + .approval_requests + .iter_mut() + .find(|r| r.request_id == request_id) + .unwrap() = dismissed.clone(); + let response = invoke_wallet(&mut provider, principal_id, connector, complete()); + assert!( + matches!(response, Response::Ok { .. }), + "late receipt: {response:?}" + ); + let stored = provider + .store + .approval_requests + .iter() + .find(|r| r.request_id == request_id) + .unwrap(); + assert_eq!(stored.status, ApprovalStatus::Rejected); + assert_eq!(stored.resolved_at, dismissed.resolved_at); + assert_eq!(stored.rejection_reason, dismissed.rejection_reason); + assert_eq!( + stored.signed_result.as_ref().unwrap()["transaction_hash"], + format!("0x{}", "a".repeat(64)) + ); + assert!(stored.completed_at.is_some()); + assert!(!approval_authority_is_active(stored, now_ts())); + let saved = load_store(provider.store_path.as_ref().unwrap()).unwrap(); + assert_eq!( + saved + .approval_requests + .iter() + .find(|r| r.request_id == request_id) + .unwrap() + .status, + ApprovalStatus::Rejected + ); + } + assert!( + matches!( + invoke_wallet(&mut provider, principal_id, connector, complete()), + Response::Error { .. } ), - Response::Error { .. } - )); + "one receipt only; other connectors keep their TTL" + ); return; } let transaction_hash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index df1e79962..986bce43b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -755,29 +755,6 @@ async fn test_metamask_connector_config_returns_runtime_evm_chain_metadata() { assert!(json.get("walletconnect").is_none()); } -pub(super) fn seed_walletconnect_connector_config(data_dir: &std::path::Path) { - let sdk = b"// pinned test WalletConnect SDK asset\n"; - let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); - std::fs::create_dir_all(sdk_path.parent().unwrap()).unwrap(); - std::fs::write(&sdk_path, sdk).unwrap(); - let sdk_sha256 = format!("{:x}", Sha256::digest(sdk)); - - let config_path = data_dir.join(WALLETCONNECT_CONFIG_PATH); - std::fs::create_dir_all(config_path.parent().unwrap()).unwrap(); - std::fs::write( - config_path, - serde_json::to_vec(&json!({ - "schema": WALLETCONNECT_CONFIG_SCHEMA, - "project_id": "test_walletconnect_project", - "sdk_package": WALLETCONNECT_SDK_PACKAGE, - "sdk_version": "1.0.0", - "sdk_sha256": sdk_sha256 - })) - .unwrap(), - ) - .unwrap(); -} - #[tokio::test] async fn test_metamask_connector_lists_external_wallet_accounts() { let dir = tempfile::tempdir().unwrap(); @@ -1349,6 +1326,10 @@ async fn test_metamask_connector_completes_external_wallet_handoff() { async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding() { for case in [ "valid", + "dismissed", + "dismissed-pending", + "dismissed-outside-grace", + "dismissed-recorded", "hash-text", "hash-short", "hash-nonhex", @@ -1373,12 +1354,14 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding let payload = format!("0x{}", "ab".repeat(32)); let provider = Arc::new(RecordingWalletProvider::new(MockWalletProvider { approvals: TokioMutex::new(vec![json!({ - "request_id":"wallet-approval:wc-complete", "status":if case == "pending" { "pending" } else { "approved" }, + "request_id":"wallet-approval:wc-complete", "status":if case == "pending" { "pending" } else if case.starts_with("dismissed") { "rejected" } else { "approved" }, "intent":"transaction_intent", "requested_by_actor":"documents", "resource":"elastos://transaction", "reason":"Fixture", "account_id":"fixture-account", "address":address, "proof_type":"siwe", "chain_namespace":"eip155:20", "connector_id":if case == "connector" { WALLET_METAMASK_CAPSULE_ID } else { WALLET_WALLETCONNECT_CAPSULE_ID }, "principal_id":if case == "principal" { "other-principal" } else { &owner.principal_id }, - "payload_hash":payload, "created_at":now_ts(), "expires_at":if case == "expired" { now_ts()-1 } else if case == "outside-grace" { now_ts()-elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS } else { now_ts()+600 }, + "approved_at":if case == "dismissed-pending" { None } else { Some(now_ts()-60) }, + "signed_result":if case == "dismissed-recorded" { json!({"transaction_hash":"recorded"}) } else { Value::Null }, + "payload_hash":payload, "created_at":now_ts(), "expires_at":if matches!(case, "expired" | "dismissed") { now_ts()-1 } else if matches!(case, "outside-grace" | "dismissed-outside-grace") { now_ts()-elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS } else { now_ts()+600 }, })]), ..Default::default() })); @@ -1399,7 +1382,7 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding .header("x-elastos-home-token", &connector).header(CONTENT_TYPE, "application/json") .body(Body::from(body.to_string())).unwrap()).await.unwrap(); let operations = provider.recorded_v2_operation_kinds().await; - if matches!(case, "valid" | "expired") { + if matches!(case, "valid" | "expired" | "dismissed") { assert_eq!(response.status(), StatusCode::OK, "{case}"); assert!(operations.contains(&WalletOperationKind::CompleteConnectorHandoff)); let requests = provider.requests.lock().await; diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs index 1cfa3fa9f..987384b1b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/walletconnect.rs @@ -96,7 +96,7 @@ impl Fixture { }) .unwrap(); let owner = passkey_authority(data.path()); - super::connectors::seed_walletconnect_connector_config(data.path()); + seed_walletconnect_connector_config(data.path()); let connector = projection_launch_token_for_authority_context( data.path(), WALLET_WALLETCONNECT_CAPSULE_ID, diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 5acfe26f4..413633abc 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -385,10 +385,15 @@ async fn walletconnect_request_binding( .as_array() .and_then(|requests| requests.iter().find(|r| r["request_id"] == request_id)) .ok_or_else(|| anyhow::anyhow!("WalletConnect approval request not found"))?; + let late_transaction_receipt = status == "approved" + && request["status"] == "rejected" + && request["approved_at"].as_u64().is_some() + && request["intent"] == "transaction_intent" + && request["signed_result"].is_null(); anyhow::ensure!( request["principal_id"].as_str() == Some(authority.verified_context().principal_id()) && request["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID - && request["status"] == status + && (request["status"] == status || late_transaction_receipt) && (request["expires_at"].as_u64().is_some_and(|expiry| expiry > now_ts()) // The phone can return a sent transaction after the approval TTL. // Approved state still binds its one completion to the same payload. From a08f39e05f9978068af97846f2d2379e3785dd6a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 21:38:28 -0500 Subject: [PATCH 116/139] fix(walletconnect): preserve Exit routing on refresh --- .../src/api/gateway_home_system.rs | 39 ++++++++++-- .../src/api/gateway_tests/home_system.rs | 57 +++++++++++++++++ .../elastos-server/src/setup/walletconnect.rs | 62 ++++++++++++++++++- 3 files changed, 152 insertions(+), 6 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_system.rs b/elastos/crates/elastos-server/src/api/gateway_home_system.rs index c9471ee9c..bec46872f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_system.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_system.rs @@ -4074,11 +4074,23 @@ fn home_services_stage_exit_config( Ok(file) } -fn home_services_refresh_exit_config( +pub(in crate::api::gateway) fn home_services_refresh_exit_config( + data_dir: &std::path::Path, + platform: &str, registry: &elastos_runtime::provider::ProviderRegistry, config: &serde_json::Value, ) -> anyhow::Result<()> { - let request_id = hex::encode(Sha256::digest(serde_json::to_vec(config)?)); + let walletconnect = crate::setup::walletconnect::local_exit(data_dir, platform); + let browser_running = walletconnect.is_some() + && tokio::runtime::Handle::current().block_on( + crate::setup::walletconnect::browser_helper_running(config, platform), + ); + let config = crate::setup::walletconnect::exit_config( + config.clone(), + walletconnect.as_ref().map(|(_, provider)| provider), + browser_running, + ); + let request_id = hex::encode(Sha256::digest(serde_json::to_vec(&config)?)); let request = serde_json::json!({"op":"refresh_config", "request_id":request_id, "config":config}); let result = tokio::runtime::Handle::current().block_on(async { @@ -4112,10 +4124,22 @@ fn home_services_commit_exit_config( .map(serde_json::from_slice) .transpose()? .unwrap_or_else(|| serde_json::json!({})); - if let Err(error) = home_services_refresh_exit_config(registry, config) { + if let Err(error) = home_services_refresh_exit_config( + data_dir, + &crate::setup::detect_platform(), + registry, + config, + ) { // A missing/malformed ACK may follow application. Retain the durable // pending decision and explicitly report an unconfirmed compensation. - if home_services_refresh_exit_config(registry, &previous_config).is_err() { + if home_services_refresh_exit_config( + data_dir, + &crate::setup::detect_platform(), + registry, + &previous_config, + ) + .is_err() + { anyhow::bail!("Exit activation and provider rollback remain unconfirmed"); } return Err(error); @@ -4138,7 +4162,12 @@ fn home_services_commit_exit_config( } else { Ok(()) }; - let provider_restored = home_services_refresh_exit_config(registry, &previous_config); + let provider_restored = home_services_refresh_exit_config( + data_dir, + &crate::setup::detect_platform(), + registry, + &previous_config, + ); if restored.is_err() || provider_restored.is_err() { anyhow::bail!("Exit activation rollback remains unconfirmed"); } diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs b/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs index aaae088b6..1010c3dff 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs @@ -13513,3 +13513,60 @@ async fn a_published_file_is_served_only_to_the_publishers_contacts() { crate::library::withdraw_cid_for_test(bob_dir.path(), &cid); assert!(!read(device(&alice), cid, Some(&network)).await); } + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_exit_refresh_keeps_walletconnect_and_rechecks_browser_helper() { + let dir = tempfile::tempdir().unwrap(); + seed_walletconnect_connector_config(dir.path()); + let relay = dir.path().join("browser.sock"); + let config = json!({"backends":[{ + "id":"source-home-browser-exit", "kind":"stream_relay", "allowed_hosts":["*"], + "relay_ipc":{"kind":"unix_socket","path":relay}, + "adapter_ipc":{"kind":"unix_socket","path":dir.path().join("adapter.sock")} + }]}); + let registry = Arc::new(elastos_runtime::provider::ProviderRegistry::new()); + let provider = Arc::new(ServicesExitProvider::default()); + registry + .register_sub_provider("exit", provider.clone()) + .await + .unwrap(); + // Each refresh uses the same durable config: stopped, running, then stopped. + for running in [false, true, false] { + let listener = running.then(|| std::os::unix::net::UnixListener::bind(&relay).unwrap()); + let registry = registry.clone(); + let data = dir.path().to_path_buf(); + let config = config.clone(); + tokio::task::spawn_blocking(move || { + home_services_refresh_exit_config(&data, "darwin-arm64", ®istry, &config) + }) + .await + .unwrap() + .unwrap(); + let applied = provider.applied.lock().await.clone(); + assert_eq!(applied["backends"].as_array().unwrap().len(), 2); + assert_eq!( + applied["backends"][usize::from(running)]["id"], + "walletconnect-local-exit" + ); + let parsed = exit_provider::parse_config(applied).unwrap(); + let target = url::Url::parse("tls://relay.walletconnect.org:443").unwrap(); + assert_eq!( + parsed + .backends + .iter() + .find(|backend| backend.allows_target(&target)) + .unwrap() + .id, + if running { + "source-home-browser-exit" + } else { + "walletconnect-local-exit" + } + ); + drop(listener); + if running { + std::fs::remove_file(&relay).unwrap(); + } + } +} diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs index a2e24cb35..0ac2453c2 100644 --- a/elastos/crates/elastos-server/src/setup/walletconnect.rs +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -57,12 +57,44 @@ pub fn merge_exit_config( if browser_helper_running { backends.push(managed.clone()); } else { - backends.insert(0, managed.clone()); + let browser = backends + .iter() + .position(|backend| backend["id"] == "source-home-browser-exit") + .unwrap_or(backends.len()); + backends.insert(browser, managed.clone()); } exit_provider::parse_config(existing.clone()).map_err(anyhow::Error::msg)?; Ok(existing) } +/// Refresh checks the relay used by the generated Browser backend at that moment. +/// Owner backends retain their position regardless of Browser helper state. +pub async fn browser_helper_running(config: &serde_json::Value, platform: &str) -> bool { + if !super::browser_available(platform) { + return false; + } + #[cfg(unix)] + if let Some(path) = config["backends"] + .as_array() + .and_then(|backends| { + backends + .iter() + .find(|backend| backend["id"] == "source-home-browser-exit") + }) + .and_then(|backend| backend["relay_ipc"]["path"].as_str()) + { + return matches!( + tokio::time::timeout( + std::time::Duration::from_millis(250), + tokio::net::UnixStream::connect(path), + ) + .await, + Ok(Ok(_)) + ); + } + false +} + /// A refused WalletConnect addition leaves the owner's Exit selection intact. pub fn exit_config( existing: serde_json::Value, @@ -151,6 +183,34 @@ mod tests { ); assert!(merge_exit_config(serde_json::json!({"backends":false}), Some(&wc), true).is_err()); } + #[test] + fn owner_local_backend_keeps_first_match_with_browser_stopped() { + let config = serde_json::json!({"backends":[ + {"id":"owner-local", "kind":"stream_relay", "allowed_hosts":["*"]}, + {"id":"source-home-browser-exit", "kind":"stream_relay", "allowed_hosts":["*"]} + ]}); + let wc = serde_json::json!({"backends":[{"id":"walletconnect-local-exit", "kind":"stream_relay", "allowed_hosts":["relay.walletconnect.org"]}]}); + for running in [false, true] { + let merged = merge_exit_config(config.clone(), Some(&wc), running).unwrap(); + let parsed = exit_provider::parse_config(merged.clone()).unwrap(); + assert_eq!(parsed.backends[0].id, "owner-local"); + let target = url::Url::parse("tls://relay.walletconnect.org:443").unwrap(); + assert_eq!( + parsed + .backends + .iter() + .find(|b| b.allows_target(&target)) + .unwrap() + .id, + "owner-local" + ); + assert_eq!( + merged["backends"][if running { 2 } else { 1 }]["id"], + "walletconnect-local-exit" + ); + } + } + #[test] fn walletconnect_refused_merge_preserves_browser_exit_and_matching_order() { let browser = serde_json::json!({"backends":[{"id":"browser", "kind":"stream_relay", "allowed_hosts":["*"]}]}); From 46e543f4954f64979b5d235557794c9a3c7cb9cc Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 21:38:28 -0500 Subject: [PATCH 117/139] fix(home): verify connector SDK off the async handler --- .../elastos-server/src/api/gateway_home_runtime.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index cb6645197..70fb3707e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -40,7 +40,14 @@ pub(super) async fn home_launch( // Configuration owns connector availability. Refuse a hidden connector // before package repair. - ensure_wallet_connector_configured(&state.data_dir, target).map_err(|_| { + let data = state.data_dir.clone(); + let connector_target = target.to_string(); + tokio::task::spawn_blocking(move || { + ensure_wallet_connector_configured(&data, &connector_target) + }) + .await + .unwrap_or_else(|error| Err(error.into())) + .map_err(|_| { ( StatusCode::NOT_FOUND, Json(serde_json::json!({ "error": "Home target not found" })), From 6d1288967468a29b6cde437897ca9f52b127d323 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 21:38:28 -0500 Subject: [PATCH 118/139] test(wallet): cover dismissed receipts and connector badge scope --- docs/WALLET_PROVIDER.md | 16 +++++++++++----- scripts/wallet-product-layout-smoke.mjs | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 0ff01a1cb..0193f0898 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -272,11 +272,15 @@ it again supplies recovery instructions and keeps the send control disabled. A returned transaction hash is passed to Runtime once even if the account, network or expiry changed during the phone prompt. An approved WalletConnect transaction can complete once within 24 hours after expiry, in the same Runtime -session. Wallet keeps an approved connector transaction in its request list. +session. Wallet keeps an approved WalletConnect transaction in its request list. Its owner can use Reject in Wallet to dismiss it in a later Runtime session and release its approval slot. Runtime also accepts this rejection from System and -Inbox. Connector calls and completion -keep their original session binding. Reject does not cancel a phone transaction. +Inbox. These owner surfaces can dismiss an approved send in the same session or +a later session. The connector and requesting app keep their original authority. +Completion keeps its original session binding. Reject does not cancel a phone transaction. +Runtime records one hash returned within the same grace period after dismissal, +with the normal completion bindings. The request stays dismissed; Activity shows +that it was dismissed here and still sent from the wallet, with the hash. An unfinished prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; @@ -311,8 +315,10 @@ a local Exit backend and its separate adapter and relay sockets. When Browser's local Exit helper starts successfully, the first matching existing backend takes precedence; the default Browser wildcard therefore carries the relay. WalletConnect's backend handles requests those backends do not match. When the Browser helper stays -stopped or fails to start, WalletConnect's relay-only backend takes first match for -these two TLS hosts. Retained Browser backends keep their order and matching for +stopped or fails to start, WalletConnect's relay-only backend precedes the generated +Browser backend for these two TLS hosts. Operator backends keep their order and +first match. Exit configuration refresh uses the same merge and checks the Browser +relay helper at that moment. Retained Browser backends keep their matching for other traffic, including on older linux-amd64 Homes with a wildcard Browser config. Runtime validates the merged configuration with exit-provider's parser and keeps the existing Exit configuration if the addition diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 04ae1dbe6..8ec518364 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -865,11 +865,13 @@ async function run() { await assertNoErrors(railPage, server, "rail"); server.state.approvals = [{ ...railFixtureState.approvals[0], request_id: "approved-send", status: "approved", intent: "transaction_intent", connector_id: "wallet-walletconnect", + approved_at: Math.floor(Date.now() / 1000) - 13 * 3600 - 290, created_at: Math.floor(Date.now() / 1000) - 13 * 3600 - 300, expires_at: Math.floor(Date.now() / 1000) - 13 * 3600 }]; await railPage.goto(`${server.baseUrl}/fixture-host.html?mode=window`, { waitUntil: "networkidle" }); const dismissFrame = await walletFrame(railPage); await dismissFrame.locator(".wallet-account").waitFor({ state: "visible" }); + assert(await dismissFrame.locator("#wallet-approvals-badge").textContent() === "1", "WalletConnect unfinished send counts in Activity"); await dismissFrame.locator("#wallet-activity-open").click(); const approvedCard = dismissFrame.locator('[data-wallet-request-id="approved-send"]'); await approvedCard.waitFor({ state: "visible" }); @@ -879,6 +881,24 @@ async function run() { await approvedCard.waitFor({ state: "detached" }); assert(server.state.rejectBodies.length === 1, "one dismissal reaches Runtime"); assert((await dismissFrame.locator("#wallet-status").textContent()).startsWith("Request dismissed."), "person sees dismissal confirmation"); + server.state.approvals[0].transaction_hash = `0x${"a".repeat(64)}`; + await railPage.reload({ waitUntil: "networkidle" }); + const lateFrame = await walletFrame(railPage); + await lateFrame.locator(".wallet-account").waitFor({ state: "visible" }); + await lateFrame.locator("#wallet-activity-open").click(); + const lateRow = lateFrame.locator(".wallet-activity-row"); + assert(await lateRow.count() === 1, "late receipt stays on one Activity line"); + assert((await lateRow.textContent()).includes("Dismissed here; still sent from wallet"), "late receipt explains the dismissed send"); + assert((await lateRow.textContent()).includes("tx 0xaaaa"), "late receipt shows its hash"); + for (const connector_id of ["wallet-metamask", "wallet-unisat"]) { + server.state.approvals = [{ ...server.state.approvals[0], status: "approved", connector_id, transaction_hash: undefined }]; + await railPage.reload({ waitUntil: "networkidle" }); + const otherFrame = await walletFrame(railPage); + await otherFrame.locator(".wallet-account").waitFor({ state: "visible" }); + assert(await otherFrame.locator("#wallet-approvals-badge").isHidden(), `${connector_id} keeps the normal Activity badge`); + await otherFrame.locator("#wallet-activity-open").click(); + assert(await otherFrame.locator('[data-wallet-request-id="approved-send"]').count() === 0, `${connector_id} stays out of the pending list`); + } await assertNoErrors(railPage, server, "dismissal"); console.log("Wallet approved-send dismissal PASS: visible recovery card, Reject, one Runtime request, removed after refresh"); await railPage.close(); From 409b99b0b53c758ffabe1311bd605fa5333f9c8c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 22:16:08 -0500 Subject: [PATCH 119/139] fix(wallet): keep the full late receipt hash visible --- capsules/wallet/browser/style.css | 2 ++ capsules/wallet/browser/wallet-activity.js | 3 ++- scripts/wallet-approved-dismissal.test.mjs | 2 +- scripts/wallet-product-layout-smoke.mjs | 9 +++++++-- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/capsules/wallet/browser/style.css b/capsules/wallet/browser/style.css index 7393ac0a3..74ed10129 100644 --- a/capsules/wallet/browser/style.css +++ b/capsules/wallet/browser/style.css @@ -1728,6 +1728,8 @@ html[data-wallet-presentation="rail"] .wallet-drawer { } .wallet-activity-row > div { + min-width: 0; + overflow-wrap: anywhere; display: grid; gap: 2px; } diff --git a/capsules/wallet/browser/wallet-activity.js b/capsules/wallet/browser/wallet-activity.js index 468b2effb..3cd1965c3 100644 --- a/capsules/wallet/browser/wallet-activity.js +++ b/capsules/wallet/browser/wallet-activity.js @@ -74,7 +74,8 @@ export function activitySubtitle(request) { parts.push(shortAddress(request.address)); } if (request.transaction_hash) { - parts.push(`tx ${shortAddress(request.transaction_hash)}`); + const dismissed = request.status === "rejected" && request.approved_at; + parts.push(`tx ${dismissed ? readText(request.transaction_hash) : shortAddress(request.transaction_hash)}`); } else if (request.reason) { parts.push(readText(request.reason)); } diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs index 83fc46d28..d8336cc2a 100644 --- a/scripts/wallet-approved-dismissal.test.mjs +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -81,5 +81,5 @@ test("Activity distinguishes pending rejection, approved dismissal and a late wa assert.match(activityTitle({ ...request, approved_at: 10 }), /Dismissed transaction request/); const late = { ...request, approved_at: 10, transaction_hash: `0x${"a".repeat(64)}` }; assert.match(activityTitle(late), /Dismissed here.*still sent from wallet/); - assert.match(activitySubtitle(late), /tx 0xaaaa/); + assert(activitySubtitle(late).includes(late.transaction_hash)); }); diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 8ec518364..7786bab84 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -889,9 +889,14 @@ async function run() { const lateRow = lateFrame.locator(".wallet-activity-row"); assert(await lateRow.count() === 1, "late receipt stays on one Activity line"); assert((await lateRow.textContent()).includes("Dismissed here; still sent from wallet"), "late receipt explains the dismissed send"); - assert((await lateRow.textContent()).includes("tx 0xaaaa"), "late receipt shows its hash"); + assert((await lateRow.textContent()).includes(server.state.approvals[0].transaction_hash), "late receipt keeps the full hash available"); + await railPage.setViewportSize({ width: 390, height: 844 }); + const lateBounds = await lateRow.evaluate(row => ({ right: row.getBoundingClientRect().right, width: window.innerWidth, scroll: document.documentElement.scrollWidth })); + assert(lateBounds.right <= lateBounds.width && lateBounds.scroll <= lateBounds.width, "full late hash fits the phone Activity row"); + await screenshot(lateFrame, join(tempDir, "wallet-late-receipt-phone.png")); + await railPage.setViewportSize({ width: 640, height: 900 }); for (const connector_id of ["wallet-metamask", "wallet-unisat"]) { - server.state.approvals = [{ ...server.state.approvals[0], status: "approved", connector_id, transaction_hash: undefined }]; + server.state.approvals = [{ ...server.state.approvals[0], status: "approved", connector_id, expires_at: Math.floor(Date.now() / 1000) + 300, transaction_hash: undefined }]; await railPage.reload({ waitUntil: "networkidle" }); const otherFrame = await walletFrame(railPage); await otherFrame.locator(".wallet-account").waitFor({ state: "visible" }); From abb375d81bab9355007de9613b9b985c25f93bad Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 14 Nov 2026 23:22:47 -0500 Subject: [PATCH 120/139] test(inbox): preserve approved-send dismissal in the provider fixture --- .../api/gateway_tests/support_providers.rs | 5 +- .../src/api/gateway_tests/wallet/inbox.rs | 88 ++++++++++--------- 2 files changed, 52 insertions(+), 41 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs index 3a6aac8b9..1e95e5406 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs @@ -6199,7 +6199,10 @@ impl MockWalletProvider { "message": "wallet approval request not found" })); }; - if approval["status"] != "pending" { + let approved_send = approval["status"] == "approved" + && approval["intent"] == "transaction_intent" + && approval["connector_id"].as_str().is_some(); + if approval["status"] != "pending" && !approved_send { return Ok(json!({ "status": "error", "code": "invalid_request", diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs index e61988ee5..db17190b2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs @@ -892,46 +892,54 @@ async fn test_btc_wallet_approval_journey_reviews_in_inbox_and_signs() { #[tokio::test] async fn test_inbox_reject_resolved_wallet_request_returns_bad_request() { - let dir = tempfile::tempdir().unwrap(); - let authority = passkey_authority(dir.path()); - let token = app_token_for_authority(dir.path(), INBOX_CAPSULE_ID, &authority); - let provider = MockWalletProvider { - challenges: TokioMutex::default(), - bitcoin_challenges: TokioMutex::default(), - accounts: TokioMutex::default(), - approvals: TokioMutex::new(vec![json!({ - "request_id": "wallet-approval:resolved", - "principal_id": authority.principal_id, - "status": "completed", - "intent": "transaction_intent", "requested_by_actor":"browser", - "resource":"elastos://transaction", "reason":"Sent", "account_id":"fixture", - "address":"0xabc", "created_at":10, "expires_at":20 - })]), - defaults: TokioMutex::default(), - }; - let state = wallet_test_state_with_provider(dir.path(), provider).await; - let app = gateway_router(state); - let response = app - .oneshot( - test_browser_request("localhost:61180", "null") - .method("POST") - .uri("/api/apps/inbox/actions") - .header("x-elastos-home-token", token) - .header(CONTENT_TYPE, "application/json") - .body(Body::from( - r#"{"action_id":"wallet-reject-request:wallet-approval:resolved"}"#, - )) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::BAD_REQUEST); - let body = axum::body::to_bytes(response.into_body(), usize::MAX) - .await - .unwrap(); - assert!(String::from_utf8(body.to_vec()) - .unwrap() - .contains("cannot be rejected")); + for (status, expected) in [ + ("completed", StatusCode::BAD_REQUEST), + ("approved", StatusCode::OK), + ] { + let dir = tempfile::tempdir().unwrap(); + let authority = passkey_authority(dir.path()); + let token = app_token_for_authority(dir.path(), INBOX_CAPSULE_ID, &authority); + let provider = MockWalletProvider { + challenges: TokioMutex::default(), + bitcoin_challenges: TokioMutex::default(), + accounts: TokioMutex::default(), + approvals: TokioMutex::new(vec![json!({ + "request_id": "wallet-approval:resolved", + "principal_id": authority.principal_id, + "status": status, + "connector_id":"wallet-walletconnect", "approved_at":now_ts()-1, + "intent": "transaction_intent", "requested_by_actor":"browser", + "resource":"elastos://transaction", "reason":"Sent", "account_id":"fixture", + "address":"0xabc", "created_at":now_ts()-2, "expires_at":now_ts()+300 + })]), + defaults: TokioMutex::default(), + }; + let state = wallet_test_state_with_provider(dir.path(), provider).await; + let app = gateway_router(state); + let response = app + .oneshot( + test_browser_request("localhost:61180", "null") + .method("POST") + .uri("/api/apps/inbox/actions") + .header("x-elastos-home-token", token) + .header(CONTENT_TYPE, "application/json") + .body(Body::from( + r#"{"action_id":"wallet-reject-request:wallet-approval:resolved"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), expected, "{status}"); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + if expected == StatusCode::BAD_REQUEST { + assert!(String::from_utf8(body.to_vec()) + .unwrap() + .contains("cannot be rejected")); + } + } } #[test] From 27ea863b07b4bae06d551720b04030bb668dc26e Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 00:29:51 -0500 Subject: [PATCH 121/139] test(wallet): measure phone receipts after the drawer opens --- scripts/wallet-product-layout-smoke.mjs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 7786bab84..4ea8cff3d 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -544,6 +544,7 @@ async function run() { const tempDir = await mkdtemp(join(tmpdir(), "wallet-uiux-")); const desktopShot = join(tempDir, "wallet-desktop-1280x900.png"); const narrowShot = join(tempDir, "wallet-narrow-640x900.png"); + const latePhoneShot = join(tempDir, "wallet-late-receipt-phone.png"); const browser = await chromium.launch({ ...productSmokeLaunchOptions(), headless: true, @@ -882,6 +883,7 @@ async function run() { assert(server.state.rejectBodies.length === 1, "one dismissal reaches Runtime"); assert((await dismissFrame.locator("#wallet-status").textContent()).startsWith("Request dismissed."), "person sees dismissal confirmation"); server.state.approvals[0].transaction_hash = `0x${"a".repeat(64)}`; + server.state.approvals[0].completed_at = Math.floor(Date.now() / 1000); await railPage.reload({ waitUntil: "networkidle" }); const lateFrame = await walletFrame(railPage); await lateFrame.locator(".wallet-account").waitFor({ state: "visible" }); @@ -891,9 +893,13 @@ async function run() { assert((await lateRow.textContent()).includes("Dismissed here; still sent from wallet"), "late receipt explains the dismissed send"); assert((await lateRow.textContent()).includes(server.state.approvals[0].transaction_hash), "late receipt keeps the full hash available"); await railPage.setViewportSize({ width: 390, height: 844 }); + await lateFrame.locator("#wallet-activity-drawer").evaluate(async drawer => { + await Promise.all(drawer.getAnimations().map(animation => animation.finished)); + }); const lateBounds = await lateRow.evaluate(row => ({ right: row.getBoundingClientRect().right, width: window.innerWidth, scroll: document.documentElement.scrollWidth })); - assert(lateBounds.right <= lateBounds.width && lateBounds.scroll <= lateBounds.width, "full late hash fits the phone Activity row"); - await screenshot(lateFrame, join(tempDir, "wallet-late-receipt-phone.png")); + assert(lateBounds.right <= lateBounds.width && lateBounds.scroll <= lateBounds.width, "full late hash fits the phone Activity row", lateBounds); + await screenshot(lateFrame, latePhoneShot); + console.log(`Wallet late receipt phone PASS: ${JSON.stringify(lateBounds)}`); await railPage.setViewportSize({ width: 640, height: 900 }); for (const connector_id of ["wallet-metamask", "wallet-unisat"]) { server.state.approvals = [{ ...server.state.approvals[0], status: "approved", connector_id, expires_at: Math.floor(Date.now() / 1000) + 300, transaction_hash: undefined }]; @@ -908,7 +914,7 @@ async function run() { console.log("Wallet approved-send dismissal PASS: visible recovery card, Reject, one Runtime request, removed after refresh"); await railPage.close(); - console.log(`wallet-product-layout-smoke: OK\n${desktopShot}\n${narrowShot}`); + console.log(`wallet-product-layout-smoke: OK\n${desktopShot}\n${narrowShot}\n${latePhoneShot}`); } finally { await browser.close().catch(() => {}); await server.close().catch(() => {}); From 6cb263b5fa00a12787bf97b0c9d8f57ea3220e07 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:21:32 -0500 Subject: [PATCH 122/139] fix(wallet): preserve approved MetaMask sends on stale rejection --- capsules/wallet-provider/src/approval.rs | 2 +- .../src/tests/approvals/transactions.rs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/capsules/wallet-provider/src/approval.rs b/capsules/wallet-provider/src/approval.rs index e11f8e16d..e981f81a7 100644 --- a/capsules/wallet-provider/src/approval.rs +++ b/capsules/wallet-provider/src/approval.rs @@ -399,7 +399,7 @@ impl WalletProvider { }; let approved_connector_transaction = request.status == ApprovalStatus::Approved && request.intent == "transaction_intent" - && request.connector_id.is_some(); + && request.connector_id.as_deref() == Some("wallet-walletconnect"); // Dismissal grants no signing authority. The request's person may clear // an approved external send from an owner surface after signing in again. let owner_dismissal = diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 5c574fa63..bb87546e1 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -241,7 +241,7 @@ fn transaction_intent_validates_payload_and_allows_external_handoff() { #[test] fn approved_connector_transaction_can_be_rejected_and_releases_its_slot() { for actor in ["wallet", "system", "inbox"] { - for connector in ["wallet-metamask", "wallet-walletconnect"] { + for connector in ["wallet-walletconnect"] { for same_session in [false, true] { external_transaction_handoff_with_expiry(connector, Some(actor), same_session); } @@ -357,6 +357,11 @@ fn external_transaction_handoff_with_expiry( } other => panic!("expected external transaction approval request, got {other:?}"), }; + // The owner has a pending card before the connector approves it. + let pending_card = invoke_wallet(&mut provider, principal_id, "wallet", + WalletProviderOperationV2::ListApprovals { include_resolved: false }); + assert!(matches!(pending_card, Response::Ok { data: Some(ref data) } + if data["approval_requests"].as_array().unwrap().iter().any(|r| r["request_id"] == request_id))); if let Some(actor) = dismiss_actor { let context = wallet_context_in_session(principal_id, actor, "session:replacement"); assert!( @@ -398,6 +403,15 @@ fn external_transaction_handoff_with_expiry( .find(|r| r.request_id == request_id) .unwrap() .clone(); + if connector == "wallet-metamask" { + for actor in ["wallet", "system", "inbox"] { + let rejected = invoke_wallet(&mut provider, principal_id, actor, + WalletProviderOperationV2::RejectApproval { + request_id: request_id.clone(), reason: "Reject from stale pending card".into(), + }); + assert!(matches!(rejected, Response::Error { .. }), "stale {actor} card must preserve MetaMask completion: {rejected:?}"); + } + } let now = now_ts(); let grace = elastos_wallet_contract::WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS; for (elapsed, expected) in [ From 8e4a8ef4c51e4ccb9a908e82a8f1a71b845badff Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:28:09 -0500 Subject: [PATCH 123/139] fix(wallet): distinguish dismissal and late wallet sends --- .../browser/wallet-walletconnect.js | 2 +- .../browser/walletconnect-client.mjs | 5 ++-- capsules/wallet/browser/wallet-activity.js | 5 ++-- capsules/wallet/browser/wallet-requests.js | 10 +++---- capsules/wallet/browser/wallet.js | 2 +- .../elastos-server/src/api/gateway_inbox.rs | 22 +++++++++++--- .../elastos-server/src/api/gateway_models.rs | 2 ++ .../api/gateway_tests/support_providers.rs | 6 ++-- .../api/gateway_tests/wallet/connectors.rs | 29 +++++++++++++++++++ .../src/api/gateway_tests/wallet/inbox.rs | 3 ++ .../src/api/gateway_wallet_approvals.rs | 27 +++++++++++++---- scripts/lib/walletconnect-capsule-fixture.mjs | 2 +- scripts/wallet-approved-dismissal.test.mjs | 10 ++++--- scripts/wallet-product-layout-smoke.mjs | 8 ++--- scripts/walletconnect-capsule.test.mjs | 8 +++++ 15 files changed, 110 insertions(+), 31 deletions(-) diff --git a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js index 6c7de6c55..c31b5f457 100644 --- a/capsules/wallet-walletconnect/browser/wallet-walletconnect.js +++ b/capsules/wallet-walletconnect/browser/wallet-walletconnect.js @@ -215,7 +215,7 @@ async function onRequestClick(event) { const result = await requestCapsuleWalletEffect({ kind: "approve", approvalRequestId }); watchConnection(); showStatus( - result.effect === "transaction" ? "Transaction sent." : "Request signed.", + result.message || (result.effect === "transaction" ? "Transaction sent." : "Request signed."), "success", ); notifyHomeSummaryChanged(); diff --git a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs index 7ac23b749..46ede697f 100644 --- a/capsules/wallet-walletconnect/browser/walletconnect-client.mjs +++ b/capsules/wallet-walletconnect/browser/walletconnect-client.mjs @@ -110,9 +110,10 @@ export function createWalletConnectClient({ api, origin, loadAdapter = () => imp const hash = await provider.request({method:'eth_sendTransaction',params:[transaction]},expiry); if (typeof hash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(hash)) throw new Error('Wallet returned an invalid transaction hash. The wallet may have sent it. Check your wallet before sending again.'); // A returned hash is retained even if the account, network or expiry changed while sending. - try { await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,transaction_hash:hash})}); } + let receipt; + try { receipt = await api(`${path}/complete`,{method:'POST',body:JSON.stringify({payload_hash:handoff.payload_hash,signer,transaction_hash:hash})}); } catch { throw new Error(`Wallet returned transaction hash ${hash}. Runtime could not confirm it. Keep this hash and check it before sending again.`); } - return {status:'completed',effect:'transaction'}; + return {status:receipt.receipt_status || 'completed',effect:'transaction',message:receipt.receipt_status === 'sent_after_dismissal' ? 'Request dismissed. Transaction sent from wallet.' : 'Transaction sent.'}; } if (handoff.signature_type !== 'personal_sign' || typeof handoff.message !== 'string') throw new Error('Runtime returned an invalid signature request.'); const method = 'personal_sign'; diff --git a/capsules/wallet/browser/wallet-activity.js b/capsules/wallet/browser/wallet-activity.js index 3cd1965c3..459ae3016 100644 --- a/capsules/wallet/browser/wallet-activity.js +++ b/capsules/wallet/browser/wallet-activity.js @@ -39,7 +39,8 @@ export function activityTime(request) { export function activityIcon(request) { const status = readText(request.status); - if (status === "completed") return "✓"; + if (request.transaction_hash || status === "completed") return "✓"; + if (status === "rejected" && request.approved_at) return "·"; if (status === "rejected" || status === "expired") return "×"; return "!"; } @@ -48,7 +49,7 @@ export function activityTitle(request) { const status = readText(request.status); const capsule = readText(request.capsule_id) || "Capsule"; if (request.transaction_hash && status === "rejected" && request.approved_at) { - return `${capsule} · Dismissed here; still sent from wallet`; + return `${capsule} · Sent from wallet after request was dismissed`; } if (request.transaction_hash) { return `${capsule} · Sent transaction`; diff --git a/capsules/wallet/browser/wallet-requests.js b/capsules/wallet/browser/wallet-requests.js index 843941c36..a5e109841 100644 --- a/capsules/wallet/browser/wallet-requests.js +++ b/capsules/wallet/browser/wallet-requests.js @@ -1,4 +1,4 @@ -import { pendingRequests } from "./wallet-activity.js?v=wallet-20260523a"; +import { pendingRequests } from "./wallet-activity.js?v=wallet-20261115a"; import { isBitcoinProofRequest, isManagedRequest, @@ -64,7 +64,7 @@ export function createWalletRequests({ main.append(accountAccessReview); } if (approvedTransaction) { - main.append(textNode("small", "Check your connected wallet before sending again. Reject dismisses this request; it does not cancel a transaction in your wallet.")); + main.append(textNode("small", "Check your connected wallet before sending again. Dismiss closes this request; it does not cancel a transaction in your wallet.")); } card.append(main); @@ -86,7 +86,7 @@ export function createWalletRequests({ } else if (connectorId === "wallet-metamask") { actions.append(actionButton("Open MetaMask", "walletOpenMethod", connectorId)); } - const reject = actionButton("Reject", "walletRequestReject", requestId, true); + const reject = actionButton(approvedTransaction ? "Dismiss" : "Reject", "walletRequestReject", requestId, true); if (approvedTransaction) reject.dataset.walletApprovedTransaction = "true"; actions.append(reject); card.append(actions); @@ -181,12 +181,12 @@ export function createWalletRequests({ return; } setBusy(button, true); - showStatus("Rejecting request.", "muted"); + showStatus(button.dataset.walletApprovedTransaction === "true" ? "Dismissing request." : "Rejecting request.", "muted"); try { await fetchJson(`/api/apps/wallet/wallet/approvals/${encodeURIComponent(requestId)}/reject`, { method: "POST", headers: shellHeaders({ "content-type": "application/json" }), - body: JSON.stringify({ reason: "Rejected in Wallet" }), + body: JSON.stringify({ reason: button.dataset.walletApprovedTransaction === "true" ? "Dismissed in Wallet" : "Rejected in Wallet" }), }); showStatus(button.dataset.walletApprovedTransaction === "true" ? "Request dismissed. Check your connected wallet before sending again." diff --git a/capsules/wallet/browser/wallet.js b/capsules/wallet/browser/wallet.js index d47d38428..ab473a822 100644 --- a/capsules/wallet/browser/wallet.js +++ b/capsules/wallet/browser/wallet.js @@ -1,4 +1,4 @@ -import { createWalletActivity } from "./wallet-activity.js?v=wallet-20260523a"; +import { createWalletActivity } from "./wallet-activity.js?v=wallet-20261115a"; import { createWalletApi, readHomeOrigin, diff --git a/elastos/crates/elastos-server/src/api/gateway_inbox.rs b/elastos/crates/elastos-server/src/api/gateway_inbox.rs index f70493dca..8e606154e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_inbox.rs @@ -510,7 +510,7 @@ async fn dispatch_inbox_action( return Ok(outcome.message); } if let Some(request_id) = action_id.strip_prefix("wallet-reject-request:") { - runtime_wallet_data( + let rejected = runtime_wallet_data( state, authority, elastos_wallet_contract::WalletProviderOperationV2::RejectApproval { @@ -519,19 +519,33 @@ async fn dispatch_inbox_action( }, ) .await?; + let dismissed = rejected["approval_request"]["approved_at"] + .as_u64() + .is_some() + && rejected["approval_request"]["intent"] == "transaction_intent" + && rejected["approval_request"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID; append_wallet_approval_audit( data_dir, WalletApprovalAuditInput { capsule_id: INBOX_CAPSULE_ID, - event_type: "wallet.approval.rejected", + event_type: if dismissed { + "wallet.approval.dismissed" + } else { + "wallet.approval.rejected" + }, principal_id: &context.principal_id, session_id: &context.session_id, request_id, - result: "rejected", + result: if dismissed { "dismissed" } else { "rejected" }, reason: "Wallet approval rejected through Runtime authority", }, )?; - return Ok("Rejected wallet request.".to_string()); + return Ok(if dismissed { + "Request dismissed. Check your connected wallet before sending again." + } else { + "Rejected wallet request." + } + .to_string()); } if let Some(request_id) = action_id.strip_prefix("capability-approve-request:") { return approve_runtime_capability_request(data_dir, request_id).await; diff --git a/elastos/crates/elastos-server/src/api/gateway_models.rs b/elastos/crates/elastos-server/src/api/gateway_models.rs index 354ce9dab..21f0c34e0 100644 --- a/elastos/crates/elastos-server/src/api/gateway_models.rs +++ b/elastos/crates/elastos-server/src/api/gateway_models.rs @@ -623,6 +623,8 @@ struct SystemWalletDefaultSummary { #[derive(Debug, Clone, Default, Serialize)] struct SystemWalletApprovalsSummary { + #[serde(skip_serializing_if = "Option::is_none")] + receipt_status: Option, available: bool, pending_count: usize, approval_requests: Vec, diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs index 1e95e5406..49acd21ab 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/support_providers.rs @@ -6201,7 +6201,7 @@ impl MockWalletProvider { }; let approved_send = approval["status"] == "approved" && approval["intent"] == "transaction_intent" - && approval["connector_id"].as_str().is_some(); + && approval["connector_id"] == "wallet-walletconnect"; if approval["status"] != "pending" && !approved_send { return Ok(json!({ "status": "error", @@ -6399,7 +6399,9 @@ impl MockWalletProvider { "message": "wallet approval request belongs to a different connector" })); } - approval["status"] = serde_json::Value::String("completed".to_string()); + if approval["status"] != "rejected" { + approval["status"] = serde_json::Value::String("completed".to_string()); + } if approval.get("intent").and_then(|value| value.as_str()) == Some("transaction_intent") { diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 986bce43b..52d2cb00e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -1385,6 +1385,35 @@ async fn test_walletconnect_capsule_completion_enforces_hash_and_request_binding if matches!(case, "valid" | "expired" | "dismissed") { assert_eq!(response.status(), StatusCode::OK, "{case}"); assert!(operations.contains(&WalletOperationKind::CompleteConnectorHandoff)); + let response_body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let response_json: Value = serde_json::from_slice(&response_body).unwrap(); + assert_eq!( + response_json["receipt_status"], + if case == "dismissed" { + "sent_after_dismissal" + } else { + "completed" + } + ); + let auth = crate::auth::load_auth_state(dir.path()).unwrap(); + let event = auth + .audit + .iter() + .find(|event| { + event.challenge_id.as_deref() == Some("wallet-approval:wc-complete") + && event.event_type != "wallet.approval.approved" + }) + .unwrap(); + assert_eq!( + event.event_type, + if case == "dismissed" { + "wallet.approval.sent_after_dismissal" + } else { + "wallet.approval.completed" + } + ); let requests = provider.requests.lock().await; let forwarded = requests .iter() diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs index db17190b2..1a9d23f48 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs @@ -934,6 +934,9 @@ async fn test_inbox_reject_resolved_wallet_request_returns_bad_request() { let body = axum::body::to_bytes(response.into_body(), usize::MAX) .await .unwrap(); + if status == "approved" { + assert!(String::from_utf8_lossy(&body).contains("Request dismissed.")); + } if expected == StatusCode::BAD_REQUEST { assert!(String::from_utf8(body.to_vec()) .unwrap() diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index c571c1515..8cbf682fd 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -301,7 +301,7 @@ pub(in crate::api::gateway) async fn complete_external_wallet_approval( capsule_id: &str, audit_reason: &str, ) -> anyhow::Result { - runtime_wallet_data( + let completed = runtime_wallet_data( state, authority, elastos_wallet_contract::WalletProviderOperationV2::CompleteConnectorHandoff { @@ -315,19 +315,35 @@ pub(in crate::api::gateway) async fn complete_external_wallet_approval( }, ) .await?; + let late_receipt = completed["approval_request"]["status"] == "rejected"; + let receipt_status = if late_receipt { + "sent_after_dismissal" + } else { + "completed" + }; append_wallet_approval_audit( &state.data_dir, WalletApprovalAuditInput { capsule_id, - event_type: "wallet.approval.completed", + event_type: if late_receipt { + "wallet.approval.sent_after_dismissal" + } else { + "wallet.approval.completed" + }, principal_id: &context.principal_id, session_id: &context.session_id, request_id, - result: "completed", - reason: audit_reason, + result: receipt_status, + reason: if late_receipt { + "Request dismissed. Transaction sent from wallet." + } else { + audit_reason + }, }, )?; - Ok(system_wallet_approvals_summary(state, authority, false).await) + let mut summary = system_wallet_approvals_summary(state, authority, false).await; + summary.receipt_status = Some(receipt_status.to_string()); + Ok(summary) } pub(in crate::api::gateway) async fn pending_wallet_approval_request( @@ -377,6 +393,7 @@ pub(in crate::api::gateway) async fn system_wallet_approvals_summary( .count(); SystemWalletApprovalsSummary { available: true, + receipt_status: None, pending_count, approval_requests, handoff: None, diff --git a/scripts/lib/walletconnect-capsule-fixture.mjs b/scripts/lib/walletconnect-capsule-fixture.mjs index 26ac07457..d8dd6f858 100644 --- a/scripts/lib/walletconnect-capsule-fixture.mjs +++ b/scripts/lib/walletconnect-capsule-fixture.mjs @@ -35,7 +35,7 @@ export async function exerciseWalletConnect(scenario='valid') { binding:{principal_id:'fixture',requested_by_actor:'documents',account_id:'fixture-account',chain_namespace:'eip155:20',payload_hash:payloadHash, expires_at:scenario==='expired'?1:Math.floor(clock()/1000)+lifetime}}; if(path.endsWith('/complete')){const body=JSON.parse(input.body);assert.equal(body.payload_hash,payloadHash);assert.equal(body.signer,address); - if(scenario==='completion-refused')throw new Error('Completion refused');return {};} + if(scenario==='completion-refused')throw new Error('Completion refused');return {receipt_status:scenario==='dismissed-during-send'?'sent_after_dismissal':'completed'};} throw new Error('Unexpected Runtime resource'); }; const client=createWalletConnectClient({api,origin:'http://localhost:61180',clearMemory:()=>{memoryCleared=true;}, diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs index d8336cc2a..f326e4480 100644 --- a/scripts/wallet-approved-dismissal.test.mjs +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createWalletRequests } from "../capsules/wallet/browser/wallet-requests.js"; -import { activityTitle, activitySubtitle, pendingRequests } from "../capsules/wallet/browser/wallet-activity.js"; +import { activityTitle, activitySubtitle, activityIcon, pendingRequests } from "../capsules/wallet/browser/wallet-activity.js"; class Element { children = []; dataset = {}; hidden = false; textContent = ""; @@ -21,7 +21,7 @@ test("Wallet dismisses earlier-session connector sends without another approval" t.after(() => { globalThis.document = previous; }); for (const connector of ["wallet-walletconnect"]) { const now = Math.floor(Date.now() / 1000); - const expires = connector === "wallet-walletconnect" ? now - 13 * 3600 : now + 300; + const expires = now - 13 * 3600; let request = { request_id: "approval:abandoned", status: "approved", intent: "transaction_intent", connector_id: connector, capsule_id: "browser", address: `0x${"12".repeat(20)}`, approved_at: expires - 290, created_at: expires - 300, expires_at: expires, reason: "Send transaction" }; @@ -47,7 +47,7 @@ test("Wallet dismisses earlier-session connector sends without another approval" ]) assert.deepEqual(requests.pendingWalletRequests([other]), []); requests.renderRequests(requests.pendingWalletRequests([request])); const buttons = descendants(root).filter(node => node.tagName === "button"); - assert.deepEqual(buttons.map(button => button.textContent), ["Reject"], "approved sends offer dismissal without another send"); + assert.deepEqual(buttons.map(button => button.textContent), ["Dismiss"], "approved sends offer dismissal without another send"); assert(descendants(root).some(node => node.textContent.includes("does not cancel"))); await requests.onRequestClick({ target: buttons[0] }); assert.equal(root.children.length, 1, "a refused dismissal keeps its recovery card"); @@ -80,6 +80,8 @@ test("Activity distinguishes pending rejection, approved dismissal and a late wa assert.match(activityTitle(request), /Rejected/); assert.match(activityTitle({ ...request, approved_at: 10 }), /Dismissed transaction request/); const late = { ...request, approved_at: 10, transaction_hash: `0x${"a".repeat(64)}` }; - assert.match(activityTitle(late), /Dismissed here.*still sent from wallet/); + assert.match(activityTitle(late), /Sent from wallet after request was dismissed/); + assert.equal(activityIcon(late), "✓"); + assert.equal(activityIcon({ ...request, approved_at: 10 }), "·"); assert(activitySubtitle(late).includes(late.transaction_hash)); }); diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 4ea8cff3d..363089850 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -877,8 +877,8 @@ async function run() { const approvedCard = dismissFrame.locator('[data-wallet-request-id="approved-send"]'); await approvedCard.waitFor({ state: "visible" }); assert((await approvedCard.textContent()).includes("does not cancel"), "dismissal explains ownership of the wallet transaction"); - assert(await approvedCard.getByRole("button").count() === 1, "approved send offers Reject without another approval"); - await approvedCard.getByRole("button", { name: "Reject", exact: true }).click(); + assert(await approvedCard.getByRole("button").count() === 1, "approved send offers Dismiss without another approval"); + await approvedCard.getByRole("button", { name: "Dismiss", exact: true }).click(); await approvedCard.waitFor({ state: "detached" }); assert(server.state.rejectBodies.length === 1, "one dismissal reaches Runtime"); assert((await dismissFrame.locator("#wallet-status").textContent()).startsWith("Request dismissed."), "person sees dismissal confirmation"); @@ -890,7 +890,7 @@ async function run() { await lateFrame.locator("#wallet-activity-open").click(); const lateRow = lateFrame.locator(".wallet-activity-row"); assert(await lateRow.count() === 1, "late receipt stays on one Activity line"); - assert((await lateRow.textContent()).includes("Dismissed here; still sent from wallet"), "late receipt explains the dismissed send"); + assert((await lateRow.textContent()).includes("Sent from wallet after request was dismissed"), "late receipt explains the dismissed send"); assert((await lateRow.textContent()).includes(server.state.approvals[0].transaction_hash), "late receipt keeps the full hash available"); await railPage.setViewportSize({ width: 390, height: 844 }); await lateFrame.locator("#wallet-activity-drawer").evaluate(async drawer => { @@ -911,7 +911,7 @@ async function run() { assert(await otherFrame.locator('[data-wallet-request-id="approved-send"]').count() === 0, `${connector_id} stays out of the pending list`); } await assertNoErrors(railPage, server, "dismissal"); - console.log("Wallet approved-send dismissal PASS: visible recovery card, Reject, one Runtime request, removed after refresh"); + console.log("Wallet approved-send dismissal PASS: visible recovery card, Dismiss, one Runtime request, removed after refresh"); await railPage.close(); console.log(`wallet-product-layout-smoke: OK\n${desktopShot}\n${narrowShot}\n${latePhoneShot}`); diff --git a/scripts/walletconnect-capsule.test.mjs b/scripts/walletconnect-capsule.test.mjs index 29f8e3e28..4c0514605 100644 --- a/scripts/walletconnect-capsule.test.mjs +++ b/scripts/walletconnect-capsule.test.mjs @@ -64,3 +64,11 @@ test('a stalled old SDK disconnect cannot block a new storage generation',async for(const scenario of ['numeric-chain','numeric-chain-link'])test(`capsule accepts the pinned SDK numeric chain for ${scenario}`,async()=>{const r=await exerciseWalletConnect(scenario);assert.equal(r.error,undefined);assert.equal(r.result.status,scenario.endsWith('link')?'linked':'completed');}); for(const value of [0,-1,1.5,9007199254740992,'20','0x0','0x20000000000000',null])test(`capsule refuses invalid chain ${JSON.stringify(value)} before authority changes`,async()=>{const r=await exerciseWalletConnect('invalid-chain:'+JSON.stringify(value));assert.match(r.error,/invalid chain/);assert.equal(r.routes.filter(c=>c.path.endsWith('/approve')||c.path.endsWith('/verify')).length,0);}); + +test('late send reports dismissal without claiming completion',async()=>{ + const r=await exerciseWalletConnect('dismissed-during-send'); + assert.equal(r.error,undefined); + assert.equal(r.result.status,'sent_after_dismissal'); + assert.equal(r.result.message,'Request dismissed. Transaction sent from wallet.'); + assert.equal(completed(r).length,1); +}); From b1284fa1ce30ff97860d68a38f783c52aae81224 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:31:32 -0500 Subject: [PATCH 124/139] style(wallet): format the stale-card regression --- .../src/tests/approvals/transactions.rs | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index bb87546e1..5a18c6797 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -358,8 +358,14 @@ fn external_transaction_handoff_with_expiry( other => panic!("expected external transaction approval request, got {other:?}"), }; // The owner has a pending card before the connector approves it. - let pending_card = invoke_wallet(&mut provider, principal_id, "wallet", - WalletProviderOperationV2::ListApprovals { include_resolved: false }); + let pending_card = invoke_wallet( + &mut provider, + principal_id, + "wallet", + WalletProviderOperationV2::ListApprovals { + include_resolved: false, + }, + ); assert!(matches!(pending_card, Response::Ok { data: Some(ref data) } if data["approval_requests"].as_array().unwrap().iter().any(|r| r["request_id"] == request_id))); if let Some(actor) = dismiss_actor { @@ -405,11 +411,19 @@ fn external_transaction_handoff_with_expiry( .clone(); if connector == "wallet-metamask" { for actor in ["wallet", "system", "inbox"] { - let rejected = invoke_wallet(&mut provider, principal_id, actor, + let rejected = invoke_wallet( + &mut provider, + principal_id, + actor, WalletProviderOperationV2::RejectApproval { - request_id: request_id.clone(), reason: "Reject from stale pending card".into(), - }); - assert!(matches!(rejected, Response::Error { .. }), "stale {actor} card must preserve MetaMask completion: {rejected:?}"); + request_id: request_id.clone(), + reason: "Reject from stale pending card".into(), + }, + ); + assert!( + matches!(rejected, Response::Error { .. }), + "stale {actor} card must preserve MetaMask completion: {rejected:?}" + ); } } let now = now_ts(); From 06f9115ba33ebe4d69b1169913dd159c11f44884 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:31:32 -0500 Subject: [PATCH 125/139] test(wallet): run receipt layout proof in the product browser suite --- .../wallet-walletconnect/browser/index.html | 2 +- capsules/wallet/browser/index.html | 2 +- capsules/wallet/browser/wallet.js | 2 +- docs/WALLET_PROVIDER.md | 25 ++++++++++++++----- justfile | 1 + 5 files changed, 23 insertions(+), 9 deletions(-) diff --git a/capsules/wallet-walletconnect/browser/index.html b/capsules/wallet-walletconnect/browser/index.html index c60499929..941d3cf29 100644 --- a/capsules/wallet-walletconnect/browser/index.html +++ b/capsules/wallet-walletconnect/browser/index.html @@ -39,6 +39,6 @@

Approval requests

- + diff --git a/capsules/wallet/browser/index.html b/capsules/wallet/browser/index.html index 916b358bb..9921d6fc6 100644 --- a/capsules/wallet/browser/index.html +++ b/capsules/wallet/browser/index.html @@ -186,6 +186,6 @@

Recent activity

- + diff --git a/capsules/wallet/browser/wallet.js b/capsules/wallet/browser/wallet.js index ab473a822..031ee093f 100644 --- a/capsules/wallet/browser/wallet.js +++ b/capsules/wallet/browser/wallet.js @@ -30,7 +30,7 @@ import { import { createWalletFlows } from "./wallet-flows.js?v=wallet-20260819c"; import { createWalletCreateAccountFlow } from "./wallet-create-account-flow.js?v=wallet-20260711b"; import { createWalletReceiveFlow } from "./wallet-receive-flow.js?v=wallet-20260523a"; -import { createWalletRequests } from "./wallet-requests.js?v=wallet-20260731a"; +import { createWalletRequests } from "./wallet-requests.js?v=wallet-20261115a"; import { createWalletSendFlow } from "./wallet-send-flow.js?v=wallet-20260711b"; import { createWalletStateLoader } from "./wallet-state.js?v=wallet-20260819f"; import { createWalletPreferences } from "./wallet-preferences.js?v=wallet-20260819d"; diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index 0193f0898..cb835290f 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -244,6 +244,15 @@ storage, and signed runtime audit scaffolding. An approval that expires before managed signing or external handoff completion fails closed instead of becoming a stale signing authority. +SDK availability checks share a verified-result cache. Async HTTP handlers run +verification in the blocking pool. Synchronous package inventory checks also +hash on a worker, and wait for a cold verification. The cache checks the current +config on each admission. A changed pinned digest, SDK size, modification time, +or file identity invalidates the entry; Unix identity includes device, inode, +and change time. Missing or invalid files fail closed. Runtime restart clears +the cache, and it retains at most 16 SDK paths. Existing admitted relay frames +keep their original admission; new admissions check the current files. + WalletConnect is a dedicated connector capsule (`wallet-walletconnect`). The reviewed Reown SDK and its bundled QR renderer run only in that capsule's opaque sandboxed frame. `wallet-provider` owns proof verification, linked accounts, @@ -273,14 +282,18 @@ A returned transaction hash is passed to Runtime once even if the account, network or expiry changed during the phone prompt. An approved WalletConnect transaction can complete once within 24 hours after expiry, in the same Runtime session. Wallet keeps an approved WalletConnect transaction in its request list. -Its owner can use Reject in Wallet to dismiss it in a later Runtime session and -release its approval slot. Runtime also accepts this rejection from System and -Inbox. These owner surfaces can dismiss an approved send in the same session or -a later session. The connector and requesting app keep their original authority. -Completion keeps its original session binding. Reject does not cancel a phone transaction. +Its owner can use Dismiss in Wallet to close it and release its approval slot, +in the same Runtime session or a later session. System and Inbox list pending +requests only. Runtime accepts dismissal through their owner-authorized actions +if a pending card remains on screen after WalletConnect approves the send. +The connector and requesting app keep their original authority. The requesting +app keeps its rejection after dismissal. Completion keeps its original session +binding. Dismiss does not cancel a phone transaction. Runtime records one hash returned within the same grace period after dismissal, with the normal completion bindings. The request stays dismissed; Activity shows -that it was dismissed here and still sent from the wallet, with the hash. +"Sent from wallet after request was dismissed" with the hash and a sent mark. +Runtime logs `wallet.approval.sent_after_dismissal` for this receipt, and the +connector reports "Request dismissed. Transaction sent from wallet." An unfinished prompt expires after the grace period; other connectors keep their normal TTL. Runtime checks the returned transaction hash's format only. The phone wallet confirms the transaction; diff --git a/justfile b/justfile index 878d272fb..079165f58 100644 --- a/justfile +++ b/justfile @@ -218,6 +218,7 @@ product-ui-source: node --test scripts/chat-room-reconnect.test.mjs product-ui-browser: + node scripts/wallet-product-layout-smoke.mjs node scripts/assistant-reply-layout-browser-smoke.mjs node scripts/people-product-layout-smoke.mjs node scripts/inbox-product-layout-smoke.mjs From 6ba77f77881348722f8a7c10a0924831c99fda51 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:35:21 -0500 Subject: [PATCH 126/139] fix(walletconnect): show the late-send receipt in the connector note --- .../elastos-server/src/api/gateway_wallet_connectors.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 413633abc..94382ad79 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -227,7 +227,13 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_complete( .await { Ok(mut summary) => { - summary.note = Some(format!("Signed by {connector_label}.")); + summary.note = Some( + if summary.receipt_status.as_deref() == Some("sent_after_dismissal") { + "Request dismissed. Transaction sent from wallet.".to_string() + } else { + format!("Signed by {connector_label}.") + }, + ); Json(summary).into_response() } Err(err) => system_error_response(err), From 6e667334ee7ef38a7368e764c4bc7b5180b38585 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:35:21 -0500 Subject: [PATCH 127/139] fix(walletconnect): cache SDK verification off async threads --- .../elastos-server/src/api/auth_gateway.rs | 16 +- .../src/api/browser_capsules.rs | 6 +- .../crates/elastos-server/src/api/gateway.rs | 4 +- .../src/api/gateway_home_runtime.rs | 21 +- .../src/api/gateway_home_wallet_connector.rs | 44 +++- .../elastos-server/src/api/gateway_wallet.rs | 4 +- .../src/api/gateway_wallet_accounts.rs | 8 +- .../src/api/gateway_wallet_connectors.rs | 236 ++++++++++++++++-- .../src/api/gateway_walletconnect.rs | 7 +- 9 files changed, 286 insertions(+), 60 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 7cd4e9589..d667568fa 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -3611,17 +3611,17 @@ impl std::fmt::Display for WalletConnectorBridgeRequired { impl std::error::Error for WalletConnectorBridgeRequired {} -fn require_wallet_link_context( +async fn require_wallet_link_context( state: &GatewayState, headers: &HeaderMap, ) -> anyhow::Result { let authority = super::gateway::walletconnect_connector_launch_authority(&state.data_dir, headers) .map_err(|_| anyhow::Error::new(WalletConnectorBridgeRequired))?; - verified_wallet_link_context(state, WALLET_WALLETCONNECT_CAPSULE_ID, authority) + verified_wallet_link_context(state, WALLET_WALLETCONNECT_CAPSULE_ID, authority).await } -pub(in crate::api) fn verified_wallet_link_context( +pub(in crate::api) async fn verified_wallet_link_context( state: &GatewayState, app: &str, authority: RuntimeWalletAuthority, @@ -3639,7 +3639,7 @@ pub(in crate::api) fn verified_wallet_link_context( proof_binding_id: verified.proof_binding_id().map(ToString::to_string), grant_id: verified.grant_id().to_string(), }; - super::gateway::ensure_wallet_connector_configured(&state.data_dir, app)?; + super::gateway::ensure_wallet_connector_configured_async(&state.data_dir, app).await?; if context.proof_binding_id.is_none() { anyhow::bail!("missing proof-bound auth session"); } @@ -4112,7 +4112,7 @@ async fn evm_challenge_inner( headers: &HeaderMap, input: EvmChallengeRequest, ) -> anyhow::Result { - let link = require_wallet_link_context(state, headers)?; + let link = require_wallet_link_context(state, headers).await?; evm_challenge_for_wallet_link(state, headers, input, link).await } @@ -4182,7 +4182,7 @@ async fn evm_verify_inner( headers: &HeaderMap, input: EvmVerifyRequest, ) -> anyhow::Result { - let link = require_wallet_link_context(state, headers)?; + let link = require_wallet_link_context(state, headers).await?; evm_verify_for_wallet_link(state, input, link).await } @@ -4362,7 +4362,7 @@ async fn btc_challenge_inner( headers: &HeaderMap, input: BtcChallengeRequest, ) -> anyhow::Result { - let link = require_wallet_link_context(state, headers)?; + let link = require_wallet_link_context(state, headers).await?; btc_challenge_for_wallet_link(state, headers, input, link).await } @@ -4435,7 +4435,7 @@ async fn btc_verify_inner( headers: &HeaderMap, input: BtcVerifyRequest, ) -> anyhow::Result { - let link = require_wallet_link_context(state, headers)?; + let link = require_wallet_link_context(state, headers).await?; btc_verify_for_wallet_link(state, input, link).await } diff --git a/elastos/crates/elastos-server/src/api/browser_capsules.rs b/elastos/crates/elastos-server/src/api/browser_capsules.rs index 50fd22d2a..37454af8e 100644 --- a/elastos/crates/elastos-server/src/api/browser_capsules.rs +++ b/elastos/crates/elastos-server/src/api/browser_capsules.rs @@ -212,7 +212,11 @@ async fn serve_browser_capsule_asset( requested_path: Option<&str>, raw_query: Option<&str>, ) -> Response { - if !capsule_is_offered(data_dir, app) { + if app == "services" + || super::gateway::ensure_wallet_connector_configured_async(data_dir, app) + .await + .is_err() + { return (StatusCode::NOT_FOUND, "Browser capsule not found").into_response(); } diff --git a/elastos/crates/elastos-server/src/api/gateway.rs b/elastos/crates/elastos-server/src/api/gateway.rs index a91860531..2698c0df1 100644 --- a/elastos/crates/elastos-server/src/api/gateway.rs +++ b/elastos/crates/elastos-server/src/api/gateway.rs @@ -221,8 +221,10 @@ pub use gateway_server::GatewayCollaborationContext; use gateway_site::*; pub(super) use gateway_site::{content_type, validate_file_path}; use gateway_transaction_effects::*; -pub(crate) use gateway_wallet::ensure_wallet_connector_configured; use gateway_wallet::*; +pub(crate) use gateway_wallet::{ + ensure_wallet_connector_configured, ensure_wallet_connector_configured_async, +}; /// A capsule this Home does not offer is absent everywhere: not served, not /// launchable and not in the catalog. Services is hidden until sharing moves diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index 70fb3707e..d29fa6f93 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -40,19 +40,14 @@ pub(super) async fn home_launch( // Configuration owns connector availability. Refuse a hidden connector // before package repair. - let data = state.data_dir.clone(); - let connector_target = target.to_string(); - tokio::task::spawn_blocking(move || { - ensure_wallet_connector_configured(&data, &connector_target) - }) - .await - .unwrap_or_else(|error| Err(error.into())) - .map_err(|_| { - ( - StatusCode::NOT_FOUND, - Json(serde_json::json!({ "error": "Home target not found" })), - ) - })?; + ensure_wallet_connector_configured_async(&state.data_dir, target) + .await + .map_err(|_| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({ "error": "Home target not found" })), + ) + })?; let mut target_summary = home_launch_target_for_platform(&state.data_dir, target, platform); if target_summary.is_none() || state.data_dir.join("capsules").join(target).exists() { diff --git a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs index d4940567a..73cbb968c 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_wallet_connector.rs @@ -126,7 +126,9 @@ pub(super) async fn home_wallet_connector_evm_link_challenge( &input.connector_id, &input.connector_token, WALLET_METAMASK_CAPSULE_ID, - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -134,7 +136,9 @@ pub(super) async fn home_wallet_connector_evm_link_challenge( &state, &input.connector_id, authority.wallet, - ) { + ) + .await + { Ok(link) => link, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -172,7 +176,9 @@ pub(super) async fn home_wallet_connector_evm_link_verify( &input.connector_id, &input.connector_token, WALLET_METAMASK_CAPSULE_ID, - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -180,7 +186,9 @@ pub(super) async fn home_wallet_connector_evm_link_verify( &state, &input.connector_id, authority.wallet, - ) { + ) + .await + { Ok(link) => link, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -217,7 +225,9 @@ pub(super) async fn home_wallet_connector_bitcoin_link_challenge( &input.connector_id, &input.connector_token, WALLET_UNISAT_CAPSULE_ID, - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -225,7 +235,9 @@ pub(super) async fn home_wallet_connector_bitcoin_link_challenge( &state, &input.connector_id, authority.wallet, - ) { + ) + .await + { Ok(link) => link, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -263,7 +275,9 @@ pub(super) async fn home_wallet_connector_bitcoin_link_verify( &input.connector_id, &input.connector_token, WALLET_UNISAT_CAPSULE_ID, - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -271,7 +285,9 @@ pub(super) async fn home_wallet_connector_bitcoin_link_verify( &state, &input.connector_id, authority.wallet, - ) { + ) + .await + { Ok(link) => link, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -314,7 +330,9 @@ pub(super) async fn home_wallet_connector_approval_handoff( &input.connector_id, &input.connector_token, input.connector_id.as_str(), - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -382,7 +400,9 @@ pub(super) async fn home_wallet_connector_approval_complete( &input.connector_id, &input.connector_token, input.connector_id.as_str(), - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return home_wallet_connector_authority_error_response(err), }; @@ -416,7 +436,7 @@ pub(super) async fn home_wallet_connector_approval_complete( } } -fn require_home_wallet_connector_authority( +async fn require_home_wallet_connector_authority( state: &GatewayState, headers: &HeaderMap, schema: &str, @@ -432,7 +452,7 @@ fn require_home_wallet_connector_authority( { anyhow::bail!("Home wallet-connector actor mismatch"); } - ensure_wallet_connector_configured(&state.data_dir, connector_id)?; + ensure_wallet_connector_configured_async(&state.data_dir, connector_id).await?; let home = require_home_runtime_wallet_authority(&state.data_dir, headers)?; let connector_launch = diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet.rs b/elastos/crates/elastos-server/src/api/gateway_wallet.rs index b13fce4df..e8c65244b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet.rs @@ -16,7 +16,9 @@ mod gateway_wallet_send; pub(in crate::api::gateway) use gateway_wallet_accounts::*; pub(in crate::api::gateway) use gateway_wallet_app::*; pub(in crate::api::gateway) use gateway_wallet_approvals::*; -pub(crate) use gateway_wallet_connectors::ensure_wallet_connector_configured; pub(in crate::api::gateway) use gateway_wallet_connectors::*; +pub(crate) use gateway_wallet_connectors::{ + ensure_wallet_connector_configured, ensure_wallet_connector_configured_async, +}; pub(in crate::api::gateway) use gateway_wallet_prices::*; pub(in crate::api::gateway) use gateway_wallet_send::*; diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs index cd33662bf..8aed74ddf 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_accounts.rs @@ -319,16 +319,18 @@ pub(in crate::api::gateway) async fn wallet_app_summary( "id": WALLET_CAPSULE_ID, "title": "Wallet", }, - "approval_methods": wallet_approval_methods_summary(&state.data_dir), + "approval_methods": wallet_approval_methods_summary(&state.data_dir).await, "wallet_accounts": wallet_accounts, "wallet_approvals": wallet_approvals, })) .into_response() } -fn wallet_approval_methods_summary(data_dir: &FsPath) -> serde_json::Value { +async fn wallet_approval_methods_summary(data_dir: &FsPath) -> serde_json::Value { let walletconnect_available = - ensure_wallet_connector_configured(data_dir, WALLET_WALLETCONNECT_CAPSULE_ID).is_ok(); + ensure_wallet_connector_configured_async(data_dir, WALLET_WALLETCONNECT_CAPSULE_ID) + .await + .is_ok(); serde_json::json!({ "schema": "elastos.wallet.approval-methods/v1", "metamask": { diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 94382ad79..7fd16082b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -9,7 +9,9 @@ pub(in crate::api::gateway) async fn wallet_connector_config( &state.data_dir, &headers, wallet_connector.as_str(), - ) { + ) + .await + { Ok(context) => context, Err(err) => return system_error_response(err), }; @@ -57,7 +59,9 @@ pub(in crate::api::gateway) async fn wallet_connector_accounts( &state.data_dir, &headers, wallet_connector.as_str(), - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return system_error_response(err), }; @@ -79,7 +83,9 @@ pub(in crate::api::gateway) async fn wallet_connector_approvals( &state.data_dir, &headers, wallet_connector.as_str(), - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return system_error_response(err), }; @@ -116,7 +122,9 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_approve( &state.data_dir, &headers, wallet_connector.as_str(), - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return system_error_response(err), }; @@ -179,7 +187,9 @@ pub(in crate::api::gateway) async fn wallet_connector_approval_complete( &state.data_dir, &headers, wallet_connector.as_str(), - ) { + ) + .await + { Ok(authority) => authority, Err(err) => return system_error_response(err), }; @@ -252,7 +262,7 @@ fn require_capsule_owned_connector_effects(connector_id: &str) -> anyhow::Result anyhow::bail!("unknown wallet connector capsule") } -pub(in crate::api::gateway) fn require_wallet_connector_launch_context( +pub(in crate::api::gateway) async fn require_wallet_connector_launch_context( data_dir: &FsPath, headers: &HeaderMap, connector_id: &str, @@ -260,7 +270,7 @@ pub(in crate::api::gateway) fn require_wallet_connector_launch_context( if !is_wallet_connector_capsule_id(connector_id) { anyhow::bail!("unknown wallet connector capsule"); } - ensure_wallet_connector_configured(data_dir, connector_id)?; + ensure_wallet_connector_configured_async(data_dir, connector_id).await?; if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { Ok( gateway_walletconnect::connector_launch_authority(data_dir, headers)? @@ -271,7 +281,7 @@ pub(in crate::api::gateway) fn require_wallet_connector_launch_context( } } -pub(in crate::api::gateway) fn require_wallet_connector_launch_authority( +pub(in crate::api::gateway) async fn require_wallet_connector_launch_authority( data_dir: &FsPath, headers: &HeaderMap, connector_id: &str, @@ -279,7 +289,7 @@ pub(in crate::api::gateway) fn require_wallet_connector_launch_authority( if !is_wallet_connector_capsule_id(connector_id) { anyhow::bail!("unknown wallet connector capsule"); } - ensure_wallet_connector_configured(data_dir, connector_id)?; + ensure_wallet_connector_configured_async(data_dir, connector_id).await?; if connector_id == WALLET_WALLETCONNECT_CAPSULE_ID { gateway_walletconnect::connector_launch_authority(data_dir, headers) } else { @@ -294,6 +304,54 @@ pub(in crate::api::gateway) fn require_wallet_app_launch_authority( require_runtime_wallet_authority(data_dir, headers, &[WALLET_CAPSULE_ID]) } +// Async callers use this entry point. Other targets retain their direct path. +pub(crate) async fn ensure_wallet_connector_configured_async( + data_dir: &FsPath, + connector_id: &str, +) -> anyhow::Result<()> { + if connector_id != WALLET_WALLETCONNECT_CAPSULE_ID { + return Ok(()); + } + let data = data_dir.to_path_buf(); + tokio::task::spawn_blocking(move || { + ensure_wallet_connector_configured(&data, WALLET_WALLETCONNECT_CAPSULE_ID) + }) + .await? +} + +#[derive(Clone, PartialEq, Eq)] +struct WalletConnectSdkStamp { + len: u64, + modified: Option, + #[cfg(unix)] + identity: (u64, u64, i64, i64), +} + +fn walletconnect_sdk_stamp(path: &FsPath) -> anyhow::Result { + let metadata = std::fs::symlink_metadata(path)?; + anyhow::ensure!( + metadata.is_file() && metadata.len() <= 8 * 1024 * 1024, + "WalletConnect connector requires a bounded regular SDK file" + ); + Ok(WalletConnectSdkStamp { + len: metadata.len(), + modified: metadata.modified().ok(), + #[cfg(unix)] + identity: { + use std::os::unix::fs::MetadataExt; + ( + metadata.dev(), + metadata.ino(), + metadata.ctime(), + metadata.ctime_nsec(), + ) + }, + }) +} + +// Synchronous inventory/setup callers share this cache with HTTP admissions. +// A miss hashes on a worker, including when a synchronous inventory is built +// by an async caller. HTTP callers also yield while the worker finishes. pub(crate) fn ensure_wallet_connector_configured( data_dir: &FsPath, connector_id: &str, @@ -303,16 +361,46 @@ pub(crate) fn ensure_wallet_connector_configured( } let config = load_walletconnect_connector_config(data_dir)?; validate_walletconnect_connector_config(&config)?; - let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); - let bytes = - gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)?.ok_or_else(|| { - anyhow::anyhow!("WalletConnect connector is not configured: pinned SDK asset missing") - })?; - let digest = format!("{:x}", Sha256::digest(&bytes)); + let stamp = walletconnect_sdk_stamp(&sdk_path)?; + type SdkCache = std::collections::BTreeMap; + static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + let mut cache = CACHE + .get_or_init(Default::default) + .lock() + .map_err(|_| anyhow::anyhow!("WalletConnect SDK verification cache unavailable"))?; + if cache + .get(&sdk_path) + .is_some_and(|entry| entry == &(stamp.clone(), config.sdk_sha256.clone())) + { + return Ok(()); + } + // Keep the bounded read and hash off Runtime's async threads, also for the + // synchronous package inventory API. Only successful checks enter the cache. + let digest = std::thread::scope(|scope| { + scope + .spawn(|| -> anyhow::Result { + #[cfg(test)] + sdk_verification_tests::record_read(&sdk_path); + let bytes = gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)? + .ok_or_else(|| anyhow::anyhow!("WalletConnect pinned SDK asset missing"))?; + Ok(format!("{:x}", Sha256::digest(&bytes))) + }) + .join() + .map_err(|_| anyhow::anyhow!("WalletConnect SDK verification worker failed"))? + })?; + anyhow::ensure!( + stamp == walletconnect_sdk_stamp(&sdk_path)?, + "WalletConnect SDK changed during verification" + ); if !digest.eq_ignore_ascii_case(config.sdk_sha256.trim()) { anyhow::bail!("WalletConnect connector is not configured: pinned SDK hash mismatch"); } + // Runtime normally has one data root. Bound retained fixture/retired roots. + if cache.len() >= 16 { + cache.clear(); + } + cache.insert(sdk_path, (stamp, config.sdk_sha256)); Ok(()) } @@ -444,3 +532,121 @@ fn validate_walletconnect_handoff( ); Ok(()) } + +#[cfg(test)] +mod sdk_verification_tests { + use super::*; + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + use std::thread::ThreadId; + + type Reads = HashMap>; + static READS: OnceLock> = OnceLock::new(); + pub(super) fn record_read(path: &FsPath) { + READS + .get_or_init(Default::default) + .lock() + .unwrap() + .entry(path.to_path_buf()) + .or_default() + .push(std::thread::current().id()); + } + fn reads(path: &FsPath) -> Vec { + READS + .get_or_init(Default::default) + .lock() + .unwrap() + .get(path) + .cloned() + .unwrap_or_default() + } + fn fixture() -> (tempfile::TempDir, PathBuf, PathBuf, serde_json::Value) { + let dir = tempfile::tempdir().unwrap(); + let sdk = dir.path().join(WALLETCONNECT_SDK_PATH); + let config = dir.path().join(WALLETCONNECT_CONFIG_PATH); + std::fs::create_dir_all(sdk.parent().unwrap()).unwrap(); + std::fs::create_dir_all(config.parent().unwrap()).unwrap(); + std::fs::write(&sdk, b"fixture-sdk").unwrap(); + let value = serde_json::json!({"schema":WALLETCONNECT_CONFIG_SCHEMA, + "project_id":"fixture-project", "sdk_package":WALLETCONNECT_SDK_PACKAGE, + "sdk_version":"1.0.0", "sdk_sha256":format!("{:x}",Sha256::digest(b"fixture-sdk"))}); + std::fs::write(&config, value.to_string()).unwrap(); + (dir, sdk, config, value) + } + + #[tokio::test] + async fn walletconnect_sdk_cache_reuses_verification_and_invalidates_files_and_pin() { + let (dir, sdk, config, mut value) = fixture(); + let check = || { + ensure_wallet_connector_configured_async(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID) + }; + check().await.unwrap(); + check().await.unwrap(); + assert_eq!( + reads(&sdk).len(), + 1, + "unchanged requests reuse the verified SDK" + ); + // Same length and restored mtime still invalidate through ctime on Unix. + let modified = std::fs::metadata(&sdk).unwrap().modified().unwrap(); + std::fs::write(&sdk, b"tampered!!!").unwrap(); + std::fs::File::options() + .write(true) + .open(&sdk) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(modified)) + .unwrap(); + assert!( + check().await.is_err(), + "same-size tampering invalidates the cache" + ); + assert_eq!(reads(&sdk).len(), 2); + std::fs::write(&sdk, b"fixture-sdk").unwrap(); + check().await.unwrap(); + let replacement = sdk.with_extension("replacement"); + std::fs::write(&replacement, b"tampered!!!").unwrap(); + std::fs::rename(&replacement, &sdk).unwrap(); + assert!( + check().await.is_err(), + "file replacement invalidates the cache" + ); + std::fs::write(&sdk, b"fixture-sdk").unwrap(); + check().await.unwrap(); + value["sdk_sha256"] = serde_json::json!("00".repeat(32)); + std::fs::write(&config, value.to_string()).unwrap(); + assert!( + check().await.is_err(), + "a different pinned digest invalidates the cache" + ); + std::fs::remove_file(&sdk).unwrap(); + assert!( + check().await.is_err(), + "a missing SDK invalidates the cache" + ); + } + + #[tokio::test] + async fn walletconnect_sdk_hash_runs_off_the_async_thread_for_sync_inventory_too() { + let (dir, sdk, _, _) = fixture(); + ensure_wallet_connector_configured(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID).unwrap(); + assert_ne!(reads(&sdk)[0], std::thread::current().id()); + } + + #[test] + fn other_targets_need_neither_a_runtime_nor_a_blocking_pool_hop() { + use std::future::Future; + use std::task::{Context, Poll, Waker}; + for target in ["wallet-metamask", "wallet-unisat", "browser", "chat-room"] { + let mut future = std::pin::pin!(ensure_wallet_connector_configured_async( + FsPath::new("absent-fixture"), + target + )); + assert!(matches!( + future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())), + Poll::Ready(Ok(())) + )); + } + } +} diff --git a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs index 0c9cba295..945fbad3d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs +++ b/elastos/crates/elastos-server/src/api/gateway_walletconnect.rs @@ -388,12 +388,7 @@ fn ensure_consent_request( } async fn verify_sdk(state: &GatewayState) -> anyhow::Result<()> { - let data = state.data_dir.clone(); - tokio::task::spawn_blocking(move || { - ensure_wallet_connector_configured(&data, WALLET_WALLETCONNECT_CAPSULE_ID) - }) - .await??; - Ok(()) + ensure_wallet_connector_configured_async(&state.data_dir, WALLET_WALLETCONNECT_CAPSULE_ID).await } pub(in crate::api) fn connector_launch_authority( From e5772eaa502b44fdea76edaaf340a908c5442e29 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 05:52:44 -0500 Subject: [PATCH 128/139] fix(walletconnect): preserve missing SDK configuration errors --- .../src/api/gateway_tests/wallet/connectors.rs | 16 +++++++++++++++- .../src/api/gateway_wallet_connectors.rs | 17 ++++++++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs index 52d2cb00e..34c2f46d9 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/connectors.rs @@ -633,10 +633,11 @@ async fn test_walletconnect_connector_config_returns_pinned_sdk_contract() { let app = gateway_router(wallet_test_state_with_provider(dir.path(), provider).await); let response = app + .clone() .oneshot( test_browser_request("localhost:61180", "null") .uri("/api/apps/wallet-walletconnect/wallet/config") - .header("x-elastos-home-token", token) + .header("x-elastos-home-token", &token) .body(Body::empty()) .unwrap(), ) @@ -664,6 +665,19 @@ async fn test_walletconnect_connector_config_returns_pinned_sdk_contract() { assert_eq!(json["evm_chains"][0]["chainName"], "Elastos Smart Chain"); assert_eq!(json["evm_chains"][1]["chainId"], "0x2105"); assert_eq!(json["evm_chains"][1]["chainName"], "Base"); + // A valid launch with a removed SDK retains the configuration error response. + std::fs::remove_file(dir.path().join(WALLETCONNECT_SDK_PATH)).unwrap(); + let missing = app + .oneshot( + test_browser_request("localhost:61180", "null") + .uri("/api/apps/wallet-walletconnect/wallet/config") + .header("x-elastos-home-token", &token) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(missing.status(), StatusCode::BAD_REQUEST); } #[tokio::test] diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 7fd16082b..dde3c7807 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -328,7 +328,13 @@ struct WalletConnectSdkStamp { } fn walletconnect_sdk_stamp(path: &FsPath) -> anyhow::Result { - let metadata = std::fs::symlink_metadata(path)?; + let metadata = std::fs::symlink_metadata(path).map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + anyhow::anyhow!("WalletConnect connector is not configured: pinned SDK asset missing") + } else { + error.into() + } + })?; anyhow::ensure!( metadata.is_file() && metadata.len() <= 8 * 1024 * 1024, "WalletConnect connector requires a bounded regular SDK file" @@ -589,6 +595,8 @@ mod sdk_verification_tests { ); // Same length and restored mtime still invalidate through ctime on Unix. let modified = std::fs::metadata(&sdk).unwrap().modified().unwrap(); + // Allow coarse filesystem change clocks to advance before restoring mtime. + tokio::time::sleep(std::time::Duration::from_millis(20)).await; std::fs::write(&sdk, b"tampered!!!").unwrap(); std::fs::File::options() .write(true) @@ -619,9 +627,12 @@ mod sdk_verification_tests { "a different pinned digest invalidates the cache" ); std::fs::remove_file(&sdk).unwrap(); + let missing = check().await.unwrap_err(); assert!( - check().await.is_err(), - "a missing SDK invalidates the cache" + missing + .to_string() + .contains("WalletConnect connector is not configured: pinned SDK asset missing"), + "missing SDK keeps the configuration error response: {missing}" ); } From 5492badaebc097e7ef4d78522bd3de984cab9cda Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 09:54:57 -0500 Subject: [PATCH 129/139] fix(wallet): show the current dismissal result for stale cards --- capsules/wallet/browser/wallet-requests.js | 6 ++---- .../src/api/gateway_wallet_approvals.rs | 11 ++++++++-- scripts/wallet-approved-dismissal.test.mjs | 20 +++++++++++++++++++ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/capsules/wallet/browser/wallet-requests.js b/capsules/wallet/browser/wallet-requests.js index a5e109841..3a0427e51 100644 --- a/capsules/wallet/browser/wallet-requests.js +++ b/capsules/wallet/browser/wallet-requests.js @@ -183,14 +183,12 @@ export function createWalletRequests({ setBusy(button, true); showStatus(button.dataset.walletApprovedTransaction === "true" ? "Dismissing request." : "Rejecting request.", "muted"); try { - await fetchJson(`/api/apps/wallet/wallet/approvals/${encodeURIComponent(requestId)}/reject`, { + const result = await fetchJson(`/api/apps/wallet/wallet/approvals/${encodeURIComponent(requestId)}/reject`, { method: "POST", headers: shellHeaders({ "content-type": "application/json" }), body: JSON.stringify({ reason: button.dataset.walletApprovedTransaction === "true" ? "Dismissed in Wallet" : "Rejected in Wallet" }), }); - showStatus(button.dataset.walletApprovedTransaction === "true" - ? "Request dismissed. Check your connected wallet before sending again." - : "Request rejected.", "success"); + showStatus(result?.note || "Request rejected.", "success"); notifyHomeSummaryChanged(); await refreshWalletState(); } catch (error) { diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index 8cbf682fd..364a5d841 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -59,7 +59,10 @@ pub(in crate::api::gateway) async fn reject_wallet_approval_request( ) .await { - Ok(_) => { + Ok(rejected) => { + let dismissed = rejected["approval_request"]["approved_at"].as_u64().is_some() + && rejected["approval_request"]["intent"] == "transaction_intent" + && rejected["approval_request"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID; let _ = append_wallet_approval_audit( &state.data_dir, WalletApprovalAuditInput { @@ -72,7 +75,11 @@ pub(in crate::api::gateway) async fn reject_wallet_approval_request( reason: "Wallet approval rejected through Runtime authority", }, ); - Json(system_wallet_approvals_summary(state, authority, false).await).into_response() + let mut summary = system_wallet_approvals_summary(state, authority, false).await; + if dismissed { + summary.note = Some("Request dismissed. Check your connected wallet before sending again.".to_string()); + } + Json(summary).into_response() } Err(err) => system_error_response(err), } diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs index f326e4480..87ab3482f 100644 --- a/scripts/wallet-approved-dismissal.test.mjs +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -33,6 +33,7 @@ test("Wallet dismisses earlier-session connector sends without another approval" calls.push({ path, input }); if (refuse) throw new Error("Runtime refused dismissal"); request = { ...request, status: "rejected" }; + return { note: "Request dismissed. Check your connected wallet before sending again." }; }, notifyHomeSummaryChanged() {}, openApprovalMethod() { assert.fail("dismissal opens no signer"); }, @@ -85,3 +86,22 @@ test("Activity distinguishes pending rejection, approved dismissal and a late wa assert.equal(activityIcon({ ...request, approved_at: 10 }), "·"); assert(activitySubtitle(late).includes(late.transaction_hash)); }); + +// The server may approve a pending card before its Reject click arrives. +for (const dismissed of [false, true]) test(`Wallet uses the current rejection result (dismissed=${dismissed})`, async () => { + const messages = []; + const requests = createWalletRequests({ + fetchJson: async () => ({ note: dismissed + ? "Request dismissed. Check your connected wallet before sending again." + : null }), + shellHeaders: headers => headers, + showStatus: message => messages.push(message), + notifyHomeSummaryChanged() {}, refreshWalletState: async () => {}, + }); + const button = new Element("button"); + button.dataset.walletRequestReject = "approval:stale"; + await requests.onRequestClick({ target: button }); + assert.equal(messages.at(-1), dismissed + ? "Request dismissed. Check your connected wallet before sending again." + : "Request rejected."); +}); From 225d87f03fd9b10b75a838057337fc464c39ee15 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 09:57:04 -0500 Subject: [PATCH 130/139] test(wallet): run the Wallet layout smoke last --- justfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/justfile b/justfile index 079165f58..560ebce64 100644 --- a/justfile +++ b/justfile @@ -218,7 +218,6 @@ product-ui-source: node --test scripts/chat-room-reconnect.test.mjs product-ui-browser: - node scripts/wallet-product-layout-smoke.mjs node scripts/assistant-reply-layout-browser-smoke.mjs node scripts/people-product-layout-smoke.mjs node scripts/inbox-product-layout-smoke.mjs @@ -235,6 +234,7 @@ product-ui-browser: node scripts/system-window-policy-browser-smoke.mjs node scripts/chat-room-configured-layout-smoke.mjs node scripts/home-phone-layout-smoke.mjs + node scripts/wallet-product-layout-smoke.mjs # Real source Home headers and app scripts in Chromium and WebKit. # On the Mac, run under the shared lease: elastos-heavy just product-ui-capsule-browser. From a87343b4ecbe6c1b7c148b4ab17408864ba10e8f Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:16:55 -0500 Subject: [PATCH 131/139] test(walletconnect): isolate SDK cache reuse from other Homes --- .../src/api/gateway_wallet_connectors.rs | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index dde3c7807..d401652f4 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -355,6 +355,8 @@ fn walletconnect_sdk_stamp(path: &FsPath) -> anyhow::Result; + // Synchronous inventory/setup callers share this cache with HTTP admissions. // A miss hashes on a worker, including when a synchronous inventory is built // by an async caller. HTTP callers also yield while the worker finishes. @@ -365,14 +367,19 @@ pub(crate) fn ensure_wallet_connector_configured( if connector_id != WALLET_WALLETCONNECT_CAPSULE_ID { return Ok(()); } + static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + ensure_wallet_connector_configured_with_cache(data_dir, CACHE.get_or_init(Default::default)) +} + +fn ensure_wallet_connector_configured_with_cache( + data_dir: &FsPath, + cache: &std::sync::Mutex, +) -> anyhow::Result<()> { let config = load_walletconnect_connector_config(data_dir)?; validate_walletconnect_connector_config(&config)?; let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); let stamp = walletconnect_sdk_stamp(&sdk_path)?; - type SdkCache = std::collections::BTreeMap; - static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); - let mut cache = CACHE - .get_or_init(Default::default) + let mut cache = cache .lock() .map_err(|_| anyhow::anyhow!("WalletConnect SDK verification cache unavailable"))?; if cache @@ -583,10 +590,15 @@ mod sdk_verification_tests { #[tokio::test] async fn walletconnect_sdk_cache_reuses_verification_and_invalidates_files_and_pin() { let (dir, sdk, config, mut value) = fixture(); - let check = || { - ensure_wallet_connector_configured_async(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID) - }; + let cache = Mutex::default(); + let check = || async { ensure_wallet_connector_configured_with_cache(dir.path(), &cache) }; check().await.unwrap(); + // Other Homes can fill and evict the process-wide cache between checks. + let other_homes: Vec<_> = (0..16).map(|_| fixture()).collect(); + for (other, _, _, _) in &other_homes { + ensure_wallet_connector_configured(other.path(), WALLET_WALLETCONNECT_CAPSULE_ID) + .unwrap(); + } check().await.unwrap(); assert_eq!( reads(&sdk).len(), From ad15ce6f8cca65d1cd9fe0c227cf279a002a66fd Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:16:55 -0500 Subject: [PATCH 132/139] fix(walletconnect): hash inline and recover a poisoned SDK cache --- .../src/api/gateway_wallet_connectors.rs | 37 ++++++++----------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index d401652f4..f9c3e6196 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -358,8 +358,7 @@ fn walletconnect_sdk_stamp(path: &FsPath) -> anyhow::Result; // Synchronous inventory/setup callers share this cache with HTTP admissions. -// A miss hashes on a worker, including when a synchronous inventory is built -// by an async caller. HTTP callers also yield while the worker finishes. +// Callers on the blocking pool hash inline; synchronous setup uses its own thread. pub(crate) fn ensure_wallet_connector_configured( data_dir: &FsPath, connector_id: &str, @@ -381,27 +380,18 @@ fn ensure_wallet_connector_configured_with_cache( let stamp = walletconnect_sdk_stamp(&sdk_path)?; let mut cache = cache .lock() - .map_err(|_| anyhow::anyhow!("WalletConnect SDK verification cache unavailable"))?; + .unwrap_or_else(std::sync::PoisonError::into_inner); if cache .get(&sdk_path) .is_some_and(|entry| entry == &(stamp.clone(), config.sdk_sha256.clone())) { return Ok(()); } - // Keep the bounded read and hash off Runtime's async threads, also for the - // synchronous package inventory API. Only successful checks enter the cache. - let digest = std::thread::scope(|scope| { - scope - .spawn(|| -> anyhow::Result { - #[cfg(test)] - sdk_verification_tests::record_read(&sdk_path); - let bytes = gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)? - .ok_or_else(|| anyhow::anyhow!("WalletConnect pinned SDK asset missing"))?; - Ok(format!("{:x}", Sha256::digest(&bytes))) - }) - .join() - .map_err(|_| anyhow::anyhow!("WalletConnect SDK verification worker failed"))? - })?; + #[cfg(test)] + sdk_verification_tests::record_read(&sdk_path); + let bytes = gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)? + .ok_or_else(|| anyhow::anyhow!("WalletConnect pinned SDK asset missing"))?; + let digest = format!("{:x}", Sha256::digest(&bytes)); anyhow::ensure!( stamp == walletconnect_sdk_stamp(&sdk_path)?, "WalletConnect SDK changed during verification" @@ -648,11 +638,16 @@ mod sdk_verification_tests { ); } - #[tokio::test] - async fn walletconnect_sdk_hash_runs_off_the_async_thread_for_sync_inventory_too() { + #[test] + fn walletconnect_sdk_verification_recovers_a_poisoned_cache_and_hashes_inline() { let (dir, sdk, _, _) = fixture(); - ensure_wallet_connector_configured(dir.path(), WALLET_WALLETCONNECT_CAPSULE_ID).unwrap(); - assert_ne!(reads(&sdk)[0], std::thread::current().id()); + let cache = Mutex::default(); + let _ = std::panic::catch_unwind(|| { + let _guard = cache.lock().unwrap(); + panic!("fixture poisoned cache"); + }); + ensure_wallet_connector_configured_with_cache(dir.path(), &cache).unwrap(); + assert_eq!(reads(&sdk), [std::thread::current().id()]); } #[test] From ff5688730cc21c5dfc5be0b61e8dfc10d50c035a Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:17:15 -0500 Subject: [PATCH 133/139] fix(walletconnect): offload inventory verification and cache hash failures --- docs/WALLET_PROVIDER.md | 7 +- .../src/api/browser_capsules.rs | 14 ++- .../crates/elastos-server/src/api/gateway.rs | 16 +++ .../src/api/gateway_capsule_catalog.rs | 52 ++++++--- .../gateway_capsule_catalog/contract_audit.rs | 6 +- .../api/gateway_capsule_catalog/read_model.rs | 7 ++ .../src/api/gateway_home_external_link.rs | 7 +- .../src/api/gateway_home_runtime.rs | 20 +++- .../src/api/gateway_home_shared_content.rs | 13 ++- .../src/api/gateway_home_system.rs | 34 +++++- .../src/api/gateway_marketplace.rs | 8 +- .../src/api/gateway_wallet_connectors.rs | 110 +++++++++++++++--- .../crates/elastos-server/src/gateway_cmd.rs | 3 +- .../crates/elastos-server/src/server_infra.rs | 3 +- .../elastos-server/src/setup/walletconnect.rs | 9 ++ 15 files changed, 257 insertions(+), 52 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index cb835290f..d9322bf9e 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -245,12 +245,13 @@ managed signing or external handoff completion fails closed instead of becoming a stale signing authority. SDK availability checks share a verified-result cache. Async HTTP handlers run -verification in the blocking pool. Synchronous package inventory checks also -hash on a worker, and wait for a cold verification. The cache checks the current +verification in the blocking pool. Synchronous setup and CLI callers hash inline. Async package inventory and +local Exit callers yield while the blocking pool verifies the SDK. The cache checks the current config on each admission. A changed pinned digest, SDK size, modification time, or file identity invalidates the entry; Unix identity includes device, inode, and change time. Missing or invalid files fail closed. Runtime restart clears -the cache, and it retains at most 16 SDK paths. Existing admitted relay frames +the cache, and it retains at most 16 SDK paths. Matching and mismatched hashes +share the same file-stamp and pin invalidation rules. Existing admitted relay frames keep their original admission; new admissions check the current files. WalletConnect is a dedicated connector capsule (`wallet-walletconnect`). The diff --git a/elastos/crates/elastos-server/src/api/browser_capsules.rs b/elastos/crates/elastos-server/src/api/browser_capsules.rs index 37454af8e..129f7fe88 100644 --- a/elastos/crates/elastos-server/src/api/browser_capsules.rs +++ b/elastos/crates/elastos-server/src/api/browser_capsules.rs @@ -212,11 +212,7 @@ async fn serve_browser_capsule_asset( requested_path: Option<&str>, raw_query: Option<&str>, ) -> Response { - if app == "services" - || super::gateway::ensure_wallet_connector_configured_async(data_dir, app) - .await - .is_err() - { + if !super::gateway::capsule_is_offered_async(data_dir, app).await { return (StatusCode::NOT_FOUND, "Browser capsule not found").into_response(); } @@ -459,6 +455,14 @@ fn home_document_origin(headers: &axum::http::HeaderMap) -> Option { )) } +pub(crate) async fn list_launchable_browser_capsules_async( + data_dir: &Path, +) -> Vec { + let data = data_dir.to_path_buf(); + super::gateway::blocking_capsule_inventory(move || list_launchable_browser_capsules(&data)) + .await +} + pub(crate) fn list_launchable_browser_capsules(data_dir: &Path) -> Vec { list_launchable_browser_capsules_for(data_dir, &crate::setup::detect_platform()) } diff --git a/elastos/crates/elastos-server/src/api/gateway.rs b/elastos/crates/elastos-server/src/api/gateway.rs index 2698c0df1..0877c3611 100644 --- a/elastos/crates/elastos-server/src/api/gateway.rs +++ b/elastos/crates/elastos-server/src/api/gateway.rs @@ -229,6 +229,22 @@ pub(crate) use gateway_wallet::{ /// A capsule this Home does not offer is absent everywhere: not served, not /// launchable and not in the catalog. Services is hidden until sharing moves /// into People; WalletConnect waits for an operator-pinned config. +// Async callers yield while synchronous inventory reads verify pinned assets. +pub(crate) async fn blocking_capsule_inventory( + read: impl FnOnce() -> T + Send + 'static, +) -> T { + tokio::task::spawn_blocking(read) + .await + .expect("capsule inventory worker failed") +} + +pub(crate) async fn capsule_is_offered_async(data_dir: &std::path::Path, name: &str) -> bool { + name != SERVICES_CAPSULE_ID + && ensure_wallet_connector_configured_async(data_dir, name) + .await + .is_ok() +} + pub(crate) fn capsule_is_offered(data_dir: &std::path::Path, name: &str) -> bool { name != SERVICES_CAPSULE_ID && ensure_wallet_connector_configured(data_dir, name).is_ok() } diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs index 9a1368e67..ac40cf06e 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs @@ -16,7 +16,7 @@ use bindings::{ resolve_capsule_method_binding, static_capsule_method_binding, RuntimeCapsuleAffordanceBinding, }; pub(super) use read_model::{ - capsule_catalog_summary, capsule_interface_registry_summary, + capsule_catalog_summary, capsule_catalog_summary_async, capsule_interface_registry_summary, capsule_interface_registry_summary_from_catalog, CapsuleCatalogResponse, CapsuleInterfaceRegistryResponse, }; @@ -34,10 +34,19 @@ pub(super) async fn capsule_catalog( headers: HeaderMap, ) -> Response { let result = async { - let context = require_capsule_catalog_token(&state.data_dir, &headers)?; + let context = { + let data = state.data_dir.clone(); + let headers = headers.clone(); + blocking_capsule_inventory(move || require_capsule_catalog_token(&data, &headers)).await + }?; let catalog = caller_capsule_catalog_summary(&state, &context).await; anyhow::ensure!( - require_capsule_catalog_token(&state.data_dir, &headers)? == context, + { + let data = state.data_dir.clone(); + let headers = headers.clone(); + blocking_capsule_inventory(move || require_capsule_catalog_token(&data, &headers)) + .await + }? == context, "catalog authority changed" ); Ok::<_, anyhow::Error>(catalog) @@ -101,7 +110,7 @@ async fn caller_capsule_catalog_rows( // Catalog trust may be revoked while the provider is answering. Rebuild // its signed rows while retaining ordinary installed app inventory. // Each signed model CID keeps its own admission and offer projection. - let initial = capsule_catalog_summary(&state.data_dir); + let initial = capsule_catalog_summary_async(&state.data_dir).await; let mut projections = Vec::new(); for row in &initial.capsules { if row.model_content.is_some() { @@ -120,7 +129,7 @@ async fn caller_capsule_catalog_rows( } } } - let mut catalog = capsule_catalog_summary(&state.data_dir); + let mut catalog = capsule_catalog_summary_async(&state.data_dir).await; project_model_memory_fit( &mut catalog, elastos_common::host_memory::observe_host_memory(std::env::consts::OS).ok(), @@ -159,7 +168,7 @@ async fn caller_capsule_catalog_rows( #[cfg(not(unix))] { let _ = context; - capsule_catalog_summary(&state.data_dir) + capsule_catalog_summary_async(&state.data_dir).await } } @@ -167,7 +176,11 @@ pub(super) async fn capsule_interfaces( State(state): State, headers: HeaderMap, ) -> Response { - match require_capsule_catalog_token(&state.data_dir, &headers) { + match { + let data = state.data_dir.clone(); + let headers = headers.clone(); + blocking_capsule_inventory(move || require_capsule_catalog_token(&data, &headers)).await + } { Ok(_) => Json( capsule_interface_registry_summary_with_bindings( &state.data_dir, @@ -189,7 +202,7 @@ pub(super) async fn capsule_interface_registry_summary_with_bindings( registry: Option<&elastos_runtime::provider::ProviderRegistry>, ) -> read_model::CapsuleInterfaceRegistryResponse { capsule_interface_registry_summary_with_bindings_from_catalog( - &capsule_catalog_summary(data_dir), + &capsule_catalog_summary_async(data_dir).await, registry, ) .await @@ -252,7 +265,11 @@ pub(super) async fn capsule_interface_invoke( owner: Option>, Json(request): Json, ) -> Response { - let resolved = match resolve_capsule_affordance(&state.data_dir, &request) { + let resolved = match { + let data = state.data_dir.clone(); + let request = request.clone(); + blocking_capsule_inventory(move || resolve_capsule_affordance(&data, &request)).await + } { Ok(resolved) => resolved, Err(err) => { return capsule_invoke_request_error( @@ -405,7 +422,11 @@ pub(super) async fn capsule_interface_invoke( &headers, &[resolved.capsule.as_str()], ); - let method = resolve_capsule_affordance(&state.data_dir, &request); + let method = { + let data = state.data_dir.clone(); + let request = request.clone(); + blocking_capsule_inventory(move || resolve_capsule_affordance(&data, &request)).await + }; if !current.is_ok_and(|(_, current)| current == context) || !method.is_ok_and(|current| { serde_json::to_value(¤t.method).ok() @@ -766,7 +787,7 @@ async fn dispatch_capsule_launch_affordance( )); } - let catalog = capsule_catalog_summary(&state.data_dir); + let catalog = capsule_catalog_summary_async(&state.data_dir).await; let catalog_target = catalog .capsules .iter() @@ -790,7 +811,12 @@ async fn dispatch_capsule_launch_affordance( .launch_target .as_deref() .unwrap_or(catalog_target.name.as_str()); - let target_summary = home_launch_target(&state.data_dir, target_name).ok_or_else(|| { + let target_summary = { + let data = state.data_dir.clone(); + let target = target_name.to_string(); + blocking_capsule_inventory(move || home_launch_target(&data, &target)).await + } + .ok_or_else(|| { ( StatusCode::NOT_FOUND, "target_not_found", @@ -890,7 +916,7 @@ fn capsule_invoke_request_error( .into_response() } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct CapsuleInterfaceInvokeRequest { request_id: String, diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs index c35badee5..cf8117134 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/contract_audit.rs @@ -47,7 +47,7 @@ pub(super) async fn capsule_contract_audit_summary( .union(&installed_active_names) .cloned() .collect::>(); - let catalog = capsule_catalog_summary(data_dir); + let catalog = capsule_catalog_summary_async(data_dir).await; audit_catalog_membership( &active_capsule_names, catalog.capsules.iter().map(|capsule| capsule.name.clone()), @@ -108,7 +108,9 @@ pub(super) async fn capsule_contract_audit_summary( } } - let launch_targets = home_launch_targets(data_dir) + let data = data_dir.to_path_buf(); + let launch_targets = blocking_capsule_inventory(move || home_launch_targets(&data)) + .await .into_iter() .map(|target| (target.target.clone(), target)) .collect::>(); diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs index 0d672f1b3..70b557b64 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs @@ -12,6 +12,13 @@ pub(in crate::api::gateway) const CAPSULE_CATALOG_SCHEMA: &str = "elastos.capsul pub(in crate::api::gateway) const CAPSULE_INTERFACE_REGISTRY_SCHEMA: &str = "elastos.capsules.interfaces/v1"; +pub(in crate::api::gateway) async fn capsule_catalog_summary_async( + data_dir: &std::path::Path, +) -> CapsuleCatalogResponse { + let data = data_dir.to_path_buf(); + blocking_capsule_inventory(move || capsule_catalog_summary(&data)).await +} + pub(in crate::api::gateway) fn capsule_catalog_summary( data_dir: &std::path::Path, ) -> CapsuleCatalogResponse { diff --git a/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs b/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs index 6d8d65862..aa4389bc5 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs @@ -36,7 +36,12 @@ pub(super) async fn home_external_link( ) .into_response(); } - let app = match home_external_link_app(&state.data_dir, &headers, &input.app_token) { + let app = match { + let data = state.data_dir.clone(); + let headers = headers.clone(); + let token = input.app_token.clone(); + blocking_capsule_inventory(move || home_external_link_app(&data, &headers, &token)).await + } { Ok(app) => app, Err(err) => return (StatusCode::FORBIDDEN, err.to_string()).into_response(), }; diff --git a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs index d29fa6f93..96a166499 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_runtime.rs @@ -49,7 +49,15 @@ pub(super) async fn home_launch( ) })?; - let mut target_summary = home_launch_target_for_platform(&state.data_dir, target, platform); + let mut target_summary = { + let data = state.data_dir.clone(); + let target = target.to_string(); + let platform = platform.to_string(); + blocking_capsule_inventory(move || { + home_launch_target_for_platform(&data, &target, &platform) + }) + .await + }; if target_summary.is_none() || state.data_dir.join("capsules").join(target).exists() { ensure_home_target_package(&state.data_dir, target, target_summary.is_none()) .await @@ -59,7 +67,15 @@ pub(super) async fn home_launch( Json(serde_json::json!({ "error": err })), ) })?; - target_summary = home_launch_target_for_platform(&state.data_dir, target, platform); + target_summary = { + let data = state.data_dir.clone(); + let target = target.to_string(); + let platform = platform.to_string(); + blocking_capsule_inventory(move || { + home_launch_target_for_platform(&data, &target, &platform) + }) + .await + }; } let Some(target_summary) = target_summary else { diff --git a/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs b/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs index fbbe25acb..1d1adf262 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_shared_content.rs @@ -378,9 +378,16 @@ pub(super) async fn home_shared_content_check( ) .into_response(); } - let (home, app) = match require_home_token_context(&state.data_dir, &headers).and_then(|home| { - home_external_link_app(&state.data_dir, &headers, &input.app_token).map(|app| (home, app)) - }) { + let data = state.data_dir.clone(); + let request_headers = headers.clone(); + let token = input.app_token.clone(); + let (home, app) = match blocking_capsule_inventory(move || { + require_home_token_context(&data, &request_headers).and_then(|home| { + home_external_link_app(&data, &request_headers, &token).map(|app| (home, app)) + }) + }) + .await + { Ok(found) => found, Err(err) => return (StatusCode::FORBIDDEN, err.to_string()).into_response(), }; diff --git a/elastos/crates/elastos-server/src/api/gateway_home_system.rs b/elastos/crates/elastos-server/src/api/gateway_home_system.rs index bec46872f..60aaef2f2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_system.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_system.rs @@ -448,7 +448,11 @@ pub(super) async fn home_summary( { return home_error_response(err); } - let browser_state = match home_browser_state(&state.data_dir, context) { + let browser_state = match { + let data = state.data_dir.clone(); + let context = context.clone(); + blocking_capsule_inventory(move || home_browser_state(&data, &context)).await + } { Ok(state) => state, Err(err) => return home_error_response(err), }; @@ -475,7 +479,7 @@ pub(super) async fn home_summary( }; let mut notifications = home_state.notifications; - let capsule_catalog = capsule_catalog_summary(&state.data_dir); + let capsule_catalog = capsule_catalog_summary_async(&state.data_dir).await; let active_shell = match home_active_shell_summary_from_catalog( &state.data_dir, context.as_ref(), @@ -6333,7 +6337,11 @@ pub(super) async fn home_browser_state_get( Ok(context) => context, Err(err) => return home_error_response(err), }; - match home_browser_state(&state.data_dir, &context) { + match { + let data = state.data_dir.clone(); + let context = context.clone(); + blocking_capsule_inventory(move || home_browser_state(&data, &context)).await + } { Ok(state) => Json(state).into_response(), Err(err) => home_error_response(err), } @@ -6348,7 +6356,11 @@ pub(super) async fn home_browser_state_update( Ok(context) => context, Err(err) => return home_error_response(err), }; - match home_save_browser_state(&state.data_dir, &context, input) { + match { + let data = state.data_dir.clone(); + let context = context.clone(); + blocking_capsule_inventory(move || home_save_browser_state(&data, &context, input)).await + } { Ok(state) => Json(state).into_response(), Err(err) => gateway_assistant_workspace_v2::migration_error_response(&err) .unwrap_or_else(|| home_error_response(err)), @@ -6360,7 +6372,10 @@ pub(super) async fn home_active_shell_get( headers: HeaderMap, ) -> Response { let context = require_home_active_shell_token_context(&state.data_dir, &headers).ok(); - match home_active_shell_summary(&state.data_dir, context.as_ref()) { + match { + let data = state.data_dir.clone(); + blocking_capsule_inventory(move || home_active_shell_summary(&data, context.as_ref())).await + } { Ok(summary) => Json(summary).into_response(), Err(err) => home_error_response(err), } @@ -6375,7 +6390,14 @@ pub(super) async fn home_active_shell_update( Ok(context) => context, Err(err) => return home_error_response(err), }; - match home_save_active_shell(&state.data_dir, &context, input.active.trim()) { + match { + let data = state.data_dir.clone(); + let context = context.clone(); + blocking_capsule_inventory(move || { + home_save_active_shell(&data, &context, input.active.trim()) + }) + .await + } { Ok(summary) => Json(summary).into_response(), Err(err) => { let text = err.to_string(); diff --git a/elastos/crates/elastos-server/src/api/gateway_marketplace.rs b/elastos/crates/elastos-server/src/api/gateway_marketplace.rs index 809b77411..9200407e3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_marketplace.rs +++ b/elastos/crates/elastos-server/src/api/gateway_marketplace.rs @@ -4,8 +4,12 @@ pub(super) async fn marketplace_catalog( State(state): State, headers: HeaderMap, ) -> Response { - match require_capsule_catalog_token(&state.data_dir, &headers) { - Ok(_) => Json(capsule_catalog_summary(&state.data_dir)).into_response(), + match { + let data = state.data_dir.clone(); + let headers = headers.clone(); + blocking_capsule_inventory(move || require_capsule_catalog_token(&data, &headers)).await + } { + Ok(_) => Json(capsule_catalog_summary_async(&state.data_dir).await).into_response(), Err(err) => ( StatusCode::FORBIDDEN, Json(serde_json::json!({ "error": err.to_string() })), diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index f9c3e6196..58df6a2e7 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -313,10 +313,10 @@ pub(crate) async fn ensure_wallet_connector_configured_async( return Ok(()); } let data = data_dir.to_path_buf(); - tokio::task::spawn_blocking(move || { + blocking_capsule_inventory(move || { ensure_wallet_connector_configured(&data, WALLET_WALLETCONNECT_CAPSULE_ID) }) - .await? + .await } #[derive(Clone, PartialEq, Eq)] @@ -355,7 +355,7 @@ fn walletconnect_sdk_stamp(path: &FsPath) -> anyhow::Result; +type SdkCache = std::collections::BTreeMap; // Synchronous inventory/setup callers share this cache with HTTP admissions. // Callers on the blocking pool hash inline; synchronous setup uses its own thread. @@ -381,12 +381,14 @@ fn ensure_wallet_connector_configured_with_cache( let mut cache = cache .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if cache - .get(&sdk_path) - .is_some_and(|entry| entry == &(stamp.clone(), config.sdk_sha256.clone())) - { - return Ok(()); + let mismatch = + || anyhow::anyhow!("WalletConnect connector is not configured: pinned SDK hash mismatch"); + if let Some((cached_stamp, pin, matches)) = cache.get(&sdk_path) { + if cached_stamp == &stamp && pin == &config.sdk_sha256 { + return if *matches { Ok(()) } else { Err(mismatch()) }; + } } + // Async admissions and inventories already own a blocking-pool worker. #[cfg(test)] sdk_verification_tests::record_read(&sdk_path); let bytes = gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)? @@ -396,15 +398,17 @@ fn ensure_wallet_connector_configured_with_cache( stamp == walletconnect_sdk_stamp(&sdk_path)?, "WalletConnect SDK changed during verification" ); - if !digest.eq_ignore_ascii_case(config.sdk_sha256.trim()) { - anyhow::bail!("WalletConnect connector is not configured: pinned SDK hash mismatch"); - } + let matches = digest.eq_ignore_ascii_case(config.sdk_sha256.trim()); // Runtime normally has one data root. Bound retained fixture/retired roots. if cache.len() >= 16 { cache.clear(); } - cache.insert(sdk_path, (stamp, config.sdk_sha256)); - Ok(()) + cache.insert(sdk_path, (stamp, config.sdk_sha256, matches)); + if matches { + Ok(()) + } else { + Err(mismatch()) + } } pub(in crate::api::gateway) fn load_walletconnect_connector_config( @@ -650,6 +654,86 @@ mod sdk_verification_tests { assert_eq!(reads(&sdk), [std::thread::current().id()]); } + #[tokio::test] + async fn walletconnect_inventories_hash_on_the_blocking_pool() { + for source in ["catalog", "launcher", "local-exit"] { + let (dir, sdk, _, _) = fixture(); + // A declared app makes both inventory entrypoints exercise availability. + std::fs::write(dir.path().join("components.json"), serde_json::json!({ + "external": { "wallet-walletconnect": { "install_path": "capsules/wallet-walletconnect", "platforms": {} } }, + "capsules": {}, "profiles": {} + }).to_string()).unwrap(); + let capsule = dir.path().join("capsules/wallet-walletconnect"); + std::fs::write( + capsule.join("capsule.json"), + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../capsules/wallet-walletconnect/capsule.json" + )), + ) + .unwrap(); + std::fs::create_dir_all(capsule.join("browser")).unwrap(); + std::fs::write(capsule.join("browser/index.html"), "fixture").unwrap(); + match source { + "catalog" => { + capsule_catalog_summary_async(dir.path()).await; + } + "launcher" => { + crate::api::browser_capsules::list_launchable_browser_capsules_async( + dir.path(), + ) + .await; + } + _ => { + assert!(crate::setup::walletconnect::local_exit_async( + dir.path(), + "darwin-arm64" + ) + .await + .is_some()); + } + } + assert!( + !reads(&sdk).is_empty(), + "{source} must exercise SDK verification" + ); + assert!( + reads(&sdk) + .iter() + .all(|thread| *thread != std::thread::current().id()), + "{source} blocked the async thread" + ); + } + } + + #[test] + fn walletconnect_sdk_caches_hash_failure_until_file_or_pin_changes() { + let (dir, sdk, config, mut value) = fixture(); + let cache = Mutex::default(); + value["sdk_sha256"] = serde_json::json!("00".repeat(32)); + std::fs::write(&config, value.to_string()).unwrap(); + for _ in 0..2 { + assert!( + ensure_wallet_connector_configured_with_cache(dir.path(), &cache) + .unwrap_err() + .to_string() + .contains("hash mismatch") + ); + } + assert_eq!(reads(&sdk).len(), 1, "unchanged hash failures are cached"); + value["sdk_sha256"] = serde_json::json!(format!("{:x}", Sha256::digest(b"fixture-sdk"))); + std::fs::write(&config, value.to_string()).unwrap(); + ensure_wallet_connector_configured_with_cache(dir.path(), &cache).unwrap(); + assert_eq!(reads(&sdk).len(), 2, "a new pin is checked immediately"); + std::fs::write(&sdk, b"tampered!!!").unwrap(); + assert!(ensure_wallet_connector_configured_with_cache(dir.path(), &cache).is_err()); + assert_eq!( + reads(&sdk).len(), + 3, + "changed bytes are checked immediately" + ); + } + #[test] fn other_targets_need_neither_a_runtime_nor_a_blocking_pool_hop() { use std::future::Future; diff --git a/elastos/crates/elastos-server/src/gateway_cmd.rs b/elastos/crates/elastos-server/src/gateway_cmd.rs index 7954d7f0f..05cbec866 100644 --- a/elastos/crates/elastos-server/src/gateway_cmd.rs +++ b/elastos/crates/elastos-server/src/gateway_cmd.rs @@ -275,7 +275,8 @@ where wait_for_public_tunnel_url(&provider_registry, std::time::Duration::from_secs(90)) .await?; let public_base = format!("{}/", url.trim_end_matches('/')); - let public_apps = api::browser_capsules::list_launchable_browser_capsules(&data_dir) + let public_apps = api::browser_capsules::list_launchable_browser_capsules_async(&data_dir) + .await .into_iter() .map(|app| app.name) .collect::>(); diff --git a/elastos/crates/elastos-server/src/server_infra.rs b/elastos/crates/elastos-server/src/server_infra.rs index 07f2b3cdd..9ee400e2f 100644 --- a/elastos/crates/elastos-server/src/server_infra.rs +++ b/elastos/crates/elastos-server/src/server_infra.rs @@ -1199,7 +1199,8 @@ async fn setup_server_infrastructure_impl( // Browser is unavailable. let platform = elastos_server::setup::detect_platform(); let browser_available = elastos_server::setup::browser_available(&platform); - let walletconnect_exit = elastos_server::setup::walletconnect::local_exit(&data_dir, &platform); + let walletconnect_exit = + elastos_server::setup::walletconnect::local_exit_async(&data_dir, &platform).await; let browser_exit = browser_available .then(|| browser_local_exit_config_from_env(&data_dir)) .flatten(); diff --git a/elastos/crates/elastos-server/src/setup/walletconnect.rs b/elastos/crates/elastos-server/src/setup/walletconnect.rs index 0ac2453c2..c94c3b0e0 100644 --- a/elastos/crates/elastos-server/src/setup/walletconnect.rs +++ b/elastos/crates/elastos-server/src/setup/walletconnect.rs @@ -1,6 +1,15 @@ //! Relay-only defaults for a configured WalletConnect Home, independent of a Browser VM. use std::path::Path; +pub async fn local_exit_async( + data: &Path, + platform: &str, +) -> Option<(serde_json::Value, serde_json::Value)> { + let data = data.to_path_buf(); + let platform = platform.to_string(); + crate::api::gateway::blocking_capsule_inventory(move || local_exit(&data, &platform)).await +} + pub fn local_exit(data: &Path, platform: &str) -> Option<(serde_json::Value, serde_json::Value)> { crate::api::gateway::ensure_wallet_connector_configured(data, "wallet-walletconnect").ok()?; if !matches!(platform, "darwin-arm64" | "linux-amd64" | "linux-arm64") { From db92f19bbab483d26ef992a790b1185d15d95a13 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:17:16 -0500 Subject: [PATCH 134/139] fix(walletconnect): bind SDK stamps and hashing to one file handle --- docs/WALLET_PROVIDER.md | 3 +- .../src/api/gateway_wallet_connectors.rs | 78 +++++++++++++++++-- 2 files changed, 73 insertions(+), 8 deletions(-) diff --git a/docs/WALLET_PROVIDER.md b/docs/WALLET_PROVIDER.md index d9322bf9e..545106c5c 100644 --- a/docs/WALLET_PROVIDER.md +++ b/docs/WALLET_PROVIDER.md @@ -251,7 +251,8 @@ config on each admission. A changed pinned digest, SDK size, modification time, or file identity invalidates the entry; Unix identity includes device, inode, and change time. Missing or invalid files fail closed. Runtime restart clears the cache, and it retains at most 16 SDK paths. Matching and mismatched hashes -share the same file-stamp and pin invalidation rules. Existing admitted relay frames +share the same file-stamp and pin invalidation rules. Metadata before and after +hashing comes from the same open file handle. Existing admitted relay frames keep their original admission; new admissions check the current files. WalletConnect is a dedicated connector capsule (`wallet-walletconnect`). The diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 58df6a2e7..925c8ed77 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -327,14 +327,30 @@ struct WalletConnectSdkStamp { identity: (u64, u64, i64, i64), } -fn walletconnect_sdk_stamp(path: &FsPath) -> anyhow::Result { - let metadata = std::fs::symlink_metadata(path).map_err(|error| { +fn open_walletconnect_sdk(path: &FsPath) -> anyhow::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + // Refuse the final symlink on other platforms as well. + anyhow::ensure!( + !std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()), + "WalletConnect connector requires a regular SDK file" + ); + options.open(path).map_err(|error| { if error.kind() == std::io::ErrorKind::NotFound { anyhow::anyhow!("WalletConnect connector is not configured: pinned SDK asset missing") } else { error.into() } - })?; + }) +} + +fn walletconnect_sdk_stamp(file: &std::fs::File) -> anyhow::Result { + let metadata = file.metadata()?; anyhow::ensure!( metadata.is_file() && metadata.len() <= 8 * 1024 * 1024, "WalletConnect connector requires a bounded regular SDK file" @@ -377,7 +393,8 @@ fn ensure_wallet_connector_configured_with_cache( let config = load_walletconnect_connector_config(data_dir)?; validate_walletconnect_connector_config(&config)?; let sdk_path = data_dir.join(WALLETCONNECT_SDK_PATH); - let stamp = walletconnect_sdk_stamp(&sdk_path)?; + let file = open_walletconnect_sdk(&sdk_path)?; + let stamp = walletconnect_sdk_stamp(&file)?; let mut cache = cache .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); @@ -391,11 +408,16 @@ fn ensure_wallet_connector_configured_with_cache( // Async admissions and inventories already own a blocking-pool worker. #[cfg(test)] sdk_verification_tests::record_read(&sdk_path); - let bytes = gateway_walletconnect::read_bytes(&sdk_path, 8 * 1024 * 1024)? - .ok_or_else(|| anyhow::anyhow!("WalletConnect pinned SDK asset missing"))?; + use std::io::Read as _; + let mut bytes = Vec::new(); + (&file).take(8 * 1024 * 1024 + 1).read_to_end(&mut bytes)?; + anyhow::ensure!( + bytes.len() <= 8 * 1024 * 1024, + "WalletConnect SDK exceeds its limit" + ); let digest = format!("{:x}", Sha256::digest(&bytes)); anyhow::ensure!( - stamp == walletconnect_sdk_stamp(&sdk_path)?, + stamp == walletconnect_sdk_stamp(&file)?, "WalletConnect SDK changed during verification" ); let matches = digest.eq_ignore_ascii_case(config.sdk_sha256.trim()); @@ -549,7 +571,19 @@ mod sdk_verification_tests { type Reads = HashMap>; static READS: OnceLock> = OnceLock::new(); + static REPLACE: OnceLock>>> = OnceLock::new(); pub(super) fn record_read(path: &FsPath) { + if let Some(bytes) = REPLACE + .get_or_init(Default::default) + .lock() + .unwrap() + .remove(path) + { + let parent = path.parent().unwrap(); + std::fs::rename(parent, parent.with_extension("original")).unwrap(); + std::fs::create_dir_all(parent).unwrap(); + std::fs::write(path, bytes).unwrap(); + } READS .get_or_init(Default::default) .lock() @@ -734,6 +768,36 @@ mod sdk_verification_tests { ); } + #[test] + fn walletconnect_sdk_stamp_and_hash_use_the_same_open_file() { + let (dir, sdk, _, _) = fixture(); + let cache = Mutex::default(); + REPLACE + .get_or_init(Default::default) + .lock() + .unwrap() + .insert(sdk.clone(), b"tampered!!!".to_vec()); + ensure_wallet_connector_configured_with_cache(dir.path(), &cache).unwrap(); + assert!( + ensure_wallet_connector_configured_with_cache(dir.path(), &cache).is_err(), + "next admission sees the replacement immediately" + ); + assert_eq!(reads(&sdk).len(), 2); + } + + #[cfg(unix)] + #[test] + fn walletconnect_sdk_refuses_a_final_symlink_even_after_a_cached_pass() { + let (dir, sdk, _, _) = fixture(); + let cache = Mutex::default(); + ensure_wallet_connector_configured_with_cache(dir.path(), &cache).unwrap(); + let target = sdk.with_extension("target"); + std::fs::rename(&sdk, &target).unwrap(); + std::os::unix::fs::symlink(&target, &sdk).unwrap(); + assert!(ensure_wallet_connector_configured_with_cache(dir.path(), &cache).is_err()); + assert_eq!(reads(&sdk).len(), 1); + } + #[test] fn other_targets_need_neither_a_runtime_nor_a_blocking_pool_hop() { use std::future::Future; From 4658c7944cd5f0af81a834e5d1a037ca9edfb585 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:17:16 -0500 Subject: [PATCH 135/139] fix(wallet): use one dismissal reason and audit event on owner surfaces --- capsules/wallet-provider/src/approval.rs | 6 +- .../src/tests/approvals/transactions.rs | 4 + .../elastos-server/src/api/gateway_inbox.rs | 12 +- .../src/api/gateway_tests/wallet/inbox.rs | 149 ++++++++++++------ .../src/api/gateway_wallet_approvals.rs | 29 +++- .../crates/elastos-wallet-contract/src/lib.rs | 4 + 6 files changed, 141 insertions(+), 63 deletions(-) diff --git a/capsules/wallet-provider/src/approval.rs b/capsules/wallet-provider/src/approval.rs index e981f81a7..0d4828b02 100644 --- a/capsules/wallet-provider/src/approval.rs +++ b/capsules/wallet-provider/src/approval.rs @@ -424,7 +424,11 @@ impl WalletProvider { } request.status = ApprovalStatus::Rejected; request.resolved_at = Some(now); - request.rejection_reason = Some(reason.trim().to_string()); + request.rejection_reason = Some(if owner_dismissal { + elastos_wallet_contract::WALLETCONNECT_DISMISSAL_REASON.to_string() + } else { + reason.trim().to_string() + }); let request = request.clone(); if let Err(err) = self.save() { return Response::error("storage_error", err); diff --git a/capsules/wallet-provider/src/tests/approvals/transactions.rs b/capsules/wallet-provider/src/tests/approvals/transactions.rs index 5a18c6797..f50aa8e20 100644 --- a/capsules/wallet-provider/src/tests/approvals/transactions.rs +++ b/capsules/wallet-provider/src/tests/approvals/transactions.rs @@ -541,6 +541,10 @@ fn external_transaction_handoff_with_expiry( .find(|r| r.request_id == request_id) .unwrap(); assert_eq!(rejected.status, ApprovalStatus::Rejected); + assert_eq!( + rejected.rejection_reason.as_deref(), + Some("Wallet approval dismissed through Runtime authority") + ); assert!(!approval_authority_is_active(rejected, now_ts())); assert!(matches!( invoke_wallet(&mut provider, principal_id, "system", next()), diff --git a/elastos/crates/elastos-server/src/api/gateway_inbox.rs b/elastos/crates/elastos-server/src/api/gateway_inbox.rs index 8e606154e..72415ef75 100644 --- a/elastos/crates/elastos-server/src/api/gateway_inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_inbox.rs @@ -519,11 +519,7 @@ async fn dispatch_inbox_action( }, ) .await?; - let dismissed = rejected["approval_request"]["approved_at"] - .as_u64() - .is_some() - && rejected["approval_request"]["intent"] == "transaction_intent" - && rejected["approval_request"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID; + let dismissed = wallet_approval_is_dismissal(&rejected["approval_request"]); append_wallet_approval_audit( data_dir, WalletApprovalAuditInput { @@ -537,7 +533,11 @@ async fn dispatch_inbox_action( session_id: &context.session_id, request_id, result: if dismissed { "dismissed" } else { "rejected" }, - reason: "Wallet approval rejected through Runtime authority", + reason: if dismissed { + elastos_wallet_contract::WALLETCONNECT_DISMISSAL_REASON + } else { + "Wallet approval rejected through Runtime authority" + }, }, )?; return Ok(if dismissed { diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs index 1a9d23f48..544f9a329 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs @@ -892,55 +892,106 @@ async fn test_btc_wallet_approval_journey_reviews_in_inbox_and_signs() { #[tokio::test] async fn test_inbox_reject_resolved_wallet_request_returns_bad_request() { - for (status, expected) in [ - ("completed", StatusCode::BAD_REQUEST), - ("approved", StatusCode::OK), - ] { - let dir = tempfile::tempdir().unwrap(); - let authority = passkey_authority(dir.path()); - let token = app_token_for_authority(dir.path(), INBOX_CAPSULE_ID, &authority); - let provider = MockWalletProvider { - challenges: TokioMutex::default(), - bitcoin_challenges: TokioMutex::default(), - accounts: TokioMutex::default(), - approvals: TokioMutex::new(vec![json!({ - "request_id": "wallet-approval:resolved", - "principal_id": authority.principal_id, - "status": status, - "connector_id":"wallet-walletconnect", "approved_at":now_ts()-1, - "intent": "transaction_intent", "requested_by_actor":"browser", - "resource":"elastos://transaction", "reason":"Sent", "account_id":"fixture", - "address":"0xabc", "created_at":now_ts()-2, "expires_at":now_ts()+300 - })]), - defaults: TokioMutex::default(), - }; - let state = wallet_test_state_with_provider(dir.path(), provider).await; - let app = gateway_router(state); - let response = app - .oneshot( - test_browser_request("localhost:61180", "null") - .method("POST") - .uri("/api/apps/inbox/actions") - .header("x-elastos-home-token", token) - .header(CONTENT_TYPE, "application/json") - .body(Body::from( - r#"{"action_id":"wallet-reject-request:wallet-approval:resolved"}"#, - )) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), expected, "{status}"); - let body = axum::body::to_bytes(response.into_body(), usize::MAX) - .await - .unwrap(); - if status == "approved" { - assert!(String::from_utf8_lossy(&body).contains("Request dismissed.")); - } - if expected == StatusCode::BAD_REQUEST { - assert!(String::from_utf8(body.to_vec()) - .unwrap() - .contains("cannot be rejected")); + for surface in [INBOX_CAPSULE_ID, WALLET_CAPSULE_ID, SYSTEM_CAPSULE_ID] { + for (status, expected) in [ + ( + "completed", + if surface == INBOX_CAPSULE_ID { + StatusCode::BAD_REQUEST + } else { + StatusCode::INTERNAL_SERVER_ERROR + }, + ), + ("approved", StatusCode::OK), + ("pending", StatusCode::OK), + ] { + let dir = tempfile::tempdir().unwrap(); + let authority = passkey_authority(dir.path()); + let token = app_token_for_authority(dir.path(), surface, &authority); + let provider = MockWalletProvider { + challenges: TokioMutex::default(), + bitcoin_challenges: TokioMutex::default(), + accounts: TokioMutex::default(), + approvals: TokioMutex::new(vec![json!({ + "request_id": "wallet-approval:resolved", + "principal_id": authority.principal_id, + "status": status, + "connector_id":"wallet-walletconnect", "approved_at":if status == "pending" { None } else { Some(now_ts()-1) }, + "intent": "transaction_intent", "requested_by_actor":"browser", + "resource":"elastos://transaction", "reason":"Sent", "account_id":"fixture", + "address":"0xabc", "created_at":now_ts()-2, "expires_at":now_ts()+300 + })]), + defaults: TokioMutex::default(), + }; + let state = wallet_test_state_with_provider(dir.path(), provider).await; + let app = gateway_router(state); + let uri = if surface == INBOX_CAPSULE_ID { + "/api/apps/inbox/actions".to_string() + } else { + format!("/api/apps/{surface}/wallet/approvals/wallet-approval:resolved/reject") + }; + let input = if surface == INBOX_CAPSULE_ID { + json!({"action_id":"wallet-reject-request:wallet-approval:resolved"}) + } else { + json!({"reason":"Reject from stale card"}) + }; + let response = app + .oneshot( + test_browser_request("localhost:61180", "null") + .method("POST") + .uri(uri) + .header("x-elastos-home-token", token) + .header(CONTENT_TYPE, "application/json") + .body(Body::from(input.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), expected, "{status}"); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + if status == "approved" { + assert!(String::from_utf8_lossy(&body).contains("Request dismissed.")); + } + if expected == StatusCode::OK { + let auth = crate::auth::load_auth_state(dir.path()).unwrap(); + let event = auth + .audit + .iter() + .find(|event| event.challenge_id.as_deref() == Some("wallet-approval:resolved")) + .unwrap(); + assert_eq!( + event.event_type, + if status == "approved" { + "wallet.approval.dismissed" + } else { + "wallet.approval.rejected" + }, + "{surface} {status}" + ); + assert_eq!( + event.result, + if status == "approved" { + "dismissed" + } else { + "rejected" + } + ); + assert_eq!( + event.reason.as_str(), + if status == "approved" { + "Wallet approval dismissed through Runtime authority" + } else { + "Wallet approval rejected through Runtime authority" + } + ); + } + if expected != StatusCode::OK { + assert!(String::from_utf8(body.to_vec()) + .unwrap() + .contains("cannot be rejected")); + } } } } diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index 364a5d841..39e9cecb8 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -35,6 +35,12 @@ pub(in crate::api::gateway) async fn system_wallet_approval_reject( .await } +pub(in crate::api::gateway) fn wallet_approval_is_dismissal(request: &serde_json::Value) -> bool { + request["approved_at"].as_u64().is_some() + && request["intent"] == "transaction_intent" + && request["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID +} + pub(in crate::api::gateway) async fn reject_wallet_approval_request( state: &GatewayState, context: &HomeLaunchTokenContext, @@ -60,24 +66,33 @@ pub(in crate::api::gateway) async fn reject_wallet_approval_request( .await { Ok(rejected) => { - let dismissed = rejected["approval_request"]["approved_at"].as_u64().is_some() - && rejected["approval_request"]["intent"] == "transaction_intent" - && rejected["approval_request"]["connector_id"] == WALLET_WALLETCONNECT_CAPSULE_ID; + let dismissed = wallet_approval_is_dismissal(&rejected["approval_request"]); let _ = append_wallet_approval_audit( &state.data_dir, WalletApprovalAuditInput { capsule_id, - event_type: "wallet.approval.rejected", + event_type: if dismissed { + "wallet.approval.dismissed" + } else { + "wallet.approval.rejected" + }, principal_id: &context.principal_id, session_id: &context.session_id, request_id, - result: "rejected", - reason: "Wallet approval rejected through Runtime authority", + result: if dismissed { "dismissed" } else { "rejected" }, + reason: if dismissed { + elastos_wallet_contract::WALLETCONNECT_DISMISSAL_REASON + } else { + "Wallet approval rejected through Runtime authority" + }, }, ); let mut summary = system_wallet_approvals_summary(state, authority, false).await; if dismissed { - summary.note = Some("Request dismissed. Check your connected wallet before sending again.".to_string()); + summary.note = Some( + "Request dismissed. Check your connected wallet before sending again." + .to_string(), + ); } Json(summary).into_response() } diff --git a/elastos/crates/elastos-wallet-contract/src/lib.rs b/elastos/crates/elastos-wallet-contract/src/lib.rs index 8fe313834..87506c328 100644 --- a/elastos/crates/elastos-wallet-contract/src/lib.rs +++ b/elastos/crates/elastos-wallet-contract/src/lib.rs @@ -17,6 +17,10 @@ use sha2::{Digest, Sha256}; use std::collections::BTreeSet; use std::fmt; +/// Canonical reason when the owner dismisses an approved WalletConnect send. +pub const WALLETCONNECT_DISMISSAL_REASON: &str = + "Wallet approval dismissed through Runtime authority"; + /// Time to retain an approved WalletConnect send receipt after its request expires. /// The phone can finish a send after expiry; an abandoned prompt releases its quota afterward. pub const WALLETCONNECT_TRANSACTION_COMPLETION_GRACE_SECS: u64 = 24 * 60 * 60; From ce86a5aef2a3ba7bc40fc79a4dc76d301f898da1 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:17:16 -0500 Subject: [PATCH 136/139] test(wallet): refresh the request module and dismissal fixture contract --- capsules/wallet/browser/wallet.js | 2 +- scripts/wallet-product-layout-smoke.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/capsules/wallet/browser/wallet.js b/capsules/wallet/browser/wallet.js index 031ee093f..1d445c843 100644 --- a/capsules/wallet/browser/wallet.js +++ b/capsules/wallet/browser/wallet.js @@ -30,7 +30,7 @@ import { import { createWalletFlows } from "./wallet-flows.js?v=wallet-20260819c"; import { createWalletCreateAccountFlow } from "./wallet-create-account-flow.js?v=wallet-20260711b"; import { createWalletReceiveFlow } from "./wallet-receive-flow.js?v=wallet-20260523a"; -import { createWalletRequests } from "./wallet-requests.js?v=wallet-20261115a"; +import { createWalletRequests } from "./wallet-requests.js?v=wallet-20261115b"; import { createWalletSendFlow } from "./wallet-send-flow.js?v=wallet-20260711b"; import { createWalletStateLoader } from "./wallet-state.js?v=wallet-20260819f"; import { createWalletPreferences } from "./wallet-preferences.js?v=wallet-20260819d"; diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 363089850..91578bf4c 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -342,7 +342,7 @@ async function startServer() { assert(request.headers["x-elastos-home-token"] === "wallet-home-token", "dismissal carries Wallet authority"); state.rejectBodies.push(await readBody(request)); state.approvals[0].status = "rejected"; - json(response, 200, { approval_requests: state.approvals }); + json(response, 200, { approval_requests: state.approvals, note: "Request dismissed. Check your connected wallet before sending again." }); return; } if (url.pathname === "/api/wallet/prices" && request.method === "GET") { From cba4812c5103bb9809138c30ae1f5bbfd39cca39 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:28:18 -0500 Subject: [PATCH 137/139] fix(wallet): bind dismissal feedback to the current receipt state --- capsules/wallet/browser/wallet-requests.js | 4 +++- .../elastos-server/src/api/gateway_tests/wallet/inbox.rs | 4 ++++ .../elastos-server/src/api/gateway_wallet_approvals.rs | 1 + scripts/wallet-approved-dismissal.test.mjs | 7 +++---- scripts/wallet-product-layout-smoke.mjs | 2 +- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/capsules/wallet/browser/wallet-requests.js b/capsules/wallet/browser/wallet-requests.js index 3a0427e51..1c372ceef 100644 --- a/capsules/wallet/browser/wallet-requests.js +++ b/capsules/wallet/browser/wallet-requests.js @@ -188,7 +188,9 @@ export function createWalletRequests({ headers: shellHeaders({ "content-type": "application/json" }), body: JSON.stringify({ reason: button.dataset.walletApprovedTransaction === "true" ? "Dismissed in Wallet" : "Rejected in Wallet" }), }); - showStatus(result?.note || "Request rejected.", "success"); + showStatus(result?.receipt_status === "dismissed" + ? "Request dismissed. Check your connected wallet before sending again." + : "Request rejected.", "success"); notifyHomeSummaryChanged(); await refreshWalletState(); } catch (error) { diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs index 544f9a329..1f3adeef2 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/wallet/inbox.rs @@ -953,6 +953,10 @@ async fn test_inbox_reject_resolved_wallet_request_returns_bad_request() { .unwrap(); if status == "approved" { assert!(String::from_utf8_lossy(&body).contains("Request dismissed.")); + if surface != INBOX_CAPSULE_ID { + let response: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(response["receipt_status"], "dismissed"); + } } if expected == StatusCode::OK { let auth = crate::auth::load_auth_state(dir.path()).unwrap(); diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs index 39e9cecb8..4e54040f1 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_approvals.rs @@ -89,6 +89,7 @@ pub(in crate::api::gateway) async fn reject_wallet_approval_request( ); let mut summary = system_wallet_approvals_summary(state, authority, false).await; if dismissed { + summary.receipt_status = Some("dismissed".to_string()); summary.note = Some( "Request dismissed. Check your connected wallet before sending again." .to_string(), diff --git a/scripts/wallet-approved-dismissal.test.mjs b/scripts/wallet-approved-dismissal.test.mjs index 87ab3482f..64c0ab462 100644 --- a/scripts/wallet-approved-dismissal.test.mjs +++ b/scripts/wallet-approved-dismissal.test.mjs @@ -33,7 +33,7 @@ test("Wallet dismisses earlier-session connector sends without another approval" calls.push({ path, input }); if (refuse) throw new Error("Runtime refused dismissal"); request = { ...request, status: "rejected" }; - return { note: "Request dismissed. Check your connected wallet before sending again." }; + return { receipt_status: "dismissed" }; }, notifyHomeSummaryChanged() {}, openApprovalMethod() { assert.fail("dismissal opens no signer"); }, @@ -91,9 +91,8 @@ test("Activity distinguishes pending rejection, approved dismissal and a late wa for (const dismissed of [false, true]) test(`Wallet uses the current rejection result (dismissed=${dismissed})`, async () => { const messages = []; const requests = createWalletRequests({ - fetchJson: async () => ({ note: dismissed - ? "Request dismissed. Check your connected wallet before sending again." - : null }), + fetchJson: async () => ({ receipt_status: dismissed ? "dismissed" : null, + note: "Fixture provider summary unavailable" }), shellHeaders: headers => headers, showStatus: message => messages.push(message), notifyHomeSummaryChanged() {}, refreshWalletState: async () => {}, diff --git a/scripts/wallet-product-layout-smoke.mjs b/scripts/wallet-product-layout-smoke.mjs index 91578bf4c..749db90cd 100644 --- a/scripts/wallet-product-layout-smoke.mjs +++ b/scripts/wallet-product-layout-smoke.mjs @@ -342,7 +342,7 @@ async function startServer() { assert(request.headers["x-elastos-home-token"] === "wallet-home-token", "dismissal carries Wallet authority"); state.rejectBodies.push(await readBody(request)); state.approvals[0].status = "rejected"; - json(response, 200, { approval_requests: state.approvals, note: "Request dismissed. Check your connected wallet before sending again." }); + json(response, 200, { approval_requests: state.approvals, receipt_status: "dismissed", note: "Request dismissed. Check your connected wallet before sending again." }); return; } if (url.pathname === "/api/wallet/prices" && request.method === "GET") { From 1c9cf51852e2cbd06466bd67bbffe4d3f1c1930b Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 10:51:10 -0500 Subject: [PATCH 138/139] fix(runtime): bind async inventory results before matching --- .../src/api/gateway_capsule_catalog.rs | 10 +++++--- .../src/api/gateway_home_external_link.rs | 5 ++-- .../src/api/gateway_home_system.rs | 25 +++++++++++-------- .../src/api/gateway_marketplace.rs | 5 ++-- 4 files changed, 27 insertions(+), 18 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs index ac40cf06e..103516031 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs @@ -176,11 +176,12 @@ pub(super) async fn capsule_interfaces( State(state): State, headers: HeaderMap, ) -> Response { - match { + let inventory_result = { let data = state.data_dir.clone(); let headers = headers.clone(); blocking_capsule_inventory(move || require_capsule_catalog_token(&data, &headers)).await - } { + }; + match inventory_result { Ok(_) => Json( capsule_interface_registry_summary_with_bindings( &state.data_dir, @@ -265,11 +266,12 @@ pub(super) async fn capsule_interface_invoke( owner: Option>, Json(request): Json, ) -> Response { - let resolved = match { + let resolved = { let data = state.data_dir.clone(); let request = request.clone(); blocking_capsule_inventory(move || resolve_capsule_affordance(&data, &request)).await - } { + }; + let resolved = match resolved { Ok(resolved) => resolved, Err(err) => { return capsule_invoke_request_error( diff --git a/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs b/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs index aa4389bc5..2efc6f952 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_external_link.rs @@ -36,12 +36,13 @@ pub(super) async fn home_external_link( ) .into_response(); } - let app = match { + let app = { let data = state.data_dir.clone(); let headers = headers.clone(); let token = input.app_token.clone(); blocking_capsule_inventory(move || home_external_link_app(&data, &headers, &token)).await - } { + }; + let app = match app { Ok(app) => app, Err(err) => return (StatusCode::FORBIDDEN, err.to_string()).into_response(), }; diff --git a/elastos/crates/elastos-server/src/api/gateway_home_system.rs b/elastos/crates/elastos-server/src/api/gateway_home_system.rs index 60aaef2f2..69f9251e9 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_system.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_system.rs @@ -448,11 +448,12 @@ pub(super) async fn home_summary( { return home_error_response(err); } - let browser_state = match { + let browser_state = { let data = state.data_dir.clone(); let context = context.clone(); blocking_capsule_inventory(move || home_browser_state(&data, &context)).await - } { + }; + let browser_state = match browser_state { Ok(state) => state, Err(err) => return home_error_response(err), }; @@ -6337,11 +6338,12 @@ pub(super) async fn home_browser_state_get( Ok(context) => context, Err(err) => return home_error_response(err), }; - match { + let inventory_result = { let data = state.data_dir.clone(); let context = context.clone(); blocking_capsule_inventory(move || home_browser_state(&data, &context)).await - } { + }; + match inventory_result { Ok(state) => Json(state).into_response(), Err(err) => home_error_response(err), } @@ -6356,11 +6358,12 @@ pub(super) async fn home_browser_state_update( Ok(context) => context, Err(err) => return home_error_response(err), }; - match { + let inventory_result = { let data = state.data_dir.clone(); let context = context.clone(); blocking_capsule_inventory(move || home_save_browser_state(&data, &context, input)).await - } { + }; + match inventory_result { Ok(state) => Json(state).into_response(), Err(err) => gateway_assistant_workspace_v2::migration_error_response(&err) .unwrap_or_else(|| home_error_response(err)), @@ -6372,10 +6375,11 @@ pub(super) async fn home_active_shell_get( headers: HeaderMap, ) -> Response { let context = require_home_active_shell_token_context(&state.data_dir, &headers).ok(); - match { + let inventory_result = { let data = state.data_dir.clone(); blocking_capsule_inventory(move || home_active_shell_summary(&data, context.as_ref())).await - } { + }; + match inventory_result { Ok(summary) => Json(summary).into_response(), Err(err) => home_error_response(err), } @@ -6390,14 +6394,15 @@ pub(super) async fn home_active_shell_update( Ok(context) => context, Err(err) => return home_error_response(err), }; - match { + let inventory_result = { let data = state.data_dir.clone(); let context = context.clone(); blocking_capsule_inventory(move || { home_save_active_shell(&data, &context, input.active.trim()) }) .await - } { + }; + match inventory_result { Ok(summary) => Json(summary).into_response(), Err(err) => { let text = err.to_string(); diff --git a/elastos/crates/elastos-server/src/api/gateway_marketplace.rs b/elastos/crates/elastos-server/src/api/gateway_marketplace.rs index 9200407e3..9ed9d2ddf 100644 --- a/elastos/crates/elastos-server/src/api/gateway_marketplace.rs +++ b/elastos/crates/elastos-server/src/api/gateway_marketplace.rs @@ -4,11 +4,12 @@ pub(super) async fn marketplace_catalog( State(state): State, headers: HeaderMap, ) -> Response { - match { + let inventory_result = { let data = state.data_dir.clone(); let headers = headers.clone(); blocking_capsule_inventory(move || require_capsule_catalog_token(&data, &headers)).await - } { + }; + match inventory_result { Ok(_) => Json(capsule_catalog_summary_async(&state.data_dir).await).into_response(), Err(err) => ( StatusCode::FORBIDDEN, From 4cd5a7302ac4b8ec3441c05fe886c8e5b115bba8 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sun, 15 Nov 2026 12:30:56 -0500 Subject: [PATCH 139/139] test(walletconnect): wait for file stamp ticks in cache tests --- .../elastos-server/src/api/gateway_wallet_connectors.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs index 925c8ed77..1eaaed56b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs +++ b/elastos/crates/elastos-server/src/api/gateway_wallet_connectors.rs @@ -649,6 +649,8 @@ mod sdk_verification_tests { "same-size tampering invalidates the cache" ); assert_eq!(reads(&sdk).len(), 2); + // Allow coarse filesystem change clocks to advance before a same-size rewrite. + tokio::time::sleep(std::time::Duration::from_millis(20)).await; std::fs::write(&sdk, b"fixture-sdk").unwrap(); check().await.unwrap(); let replacement = sdk.with_extension("replacement"); @@ -658,6 +660,8 @@ mod sdk_verification_tests { check().await.is_err(), "file replacement invalidates the cache" ); + // Allow coarse filesystem change clocks to advance before a same-size rewrite. + tokio::time::sleep(std::time::Duration::from_millis(20)).await; std::fs::write(&sdk, b"fixture-sdk").unwrap(); check().await.unwrap(); value["sdk_sha256"] = serde_json::json!("00".repeat(32)); @@ -759,6 +763,8 @@ mod sdk_verification_tests { std::fs::write(&config, value.to_string()).unwrap(); ensure_wallet_connector_configured_with_cache(dir.path(), &cache).unwrap(); assert_eq!(reads(&sdk).len(), 2, "a new pin is checked immediately"); + // Allow coarse filesystem change clocks to advance before a same-size rewrite. + std::thread::sleep(std::time::Duration::from_millis(20)); std::fs::write(&sdk, b"tampered!!!").unwrap(); assert!(ensure_wallet_connector_configured_with_cache(dir.path(), &cache).is_err()); assert_eq!(